0

我有 2 个正在使用的页面:第一个页面是从 php 服务器获取值并填充选择/输入的页面,第二个页面是一个对话框,它从第一页中的隐藏输入中获取值. 第一个转换打开对话框并正确获取值。之后我将值保存在 php 会话中并重新加载第一页。在此过程之后,当我再次打开对话框时,jquery 无法获取 val() 并显示未定义。我不确定这是由于重新加载页面问题还是其他原因。如果我刷新页面,那么它将再次正常工作。

<div data-role="page" id="page1">
    <div data-theme="a" data-role="header">
          .....
    <div data-role="navbar" data-iconpos="top">
          .....
    </div>
    <div data-theme="c" id="cashtab" data-role="content">
        <div style="display:none" id="proddata" data=""></div>
        <div style="display:none" id="prodstock" data=""></div>
        <form id="mainsubmit" action="form.php" method="post" data-ajax="false">
            <input id="formproduct" type="hidden" name="product" value=""/>
            <div id="productsearch" style="width:48%; float:left; margin-right:2%;">
                <label for="search">Search Product:</label><br/><br/>
                <ul id="productautocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Select a product... (type at least 3 letters)" data-filter-theme="d"></ul>
            </div>
            <div id="packingselect" style=" width:23%; float:left; margin-right:2%;">
                 <label for="packing">Select Packing:</label>
                 <select name="packing" id="packing" data-iconpos="left">
                 </select>
            </div>
            <div id="qtyenter" style=" width:23%; float:left; margin-right:2%;">
                 <label for="quantity">Select Qty:</label>
                 <input type="number" data-clear-btn="true" name="quantity" id="qty" value=""/>
            </div><br/><br/><br/><br/><br/><br/><br/><br/>
            <div style="display:inline-block; width:33%; margin-left:33%; margin-right:33%;">
                 <a href="#page3" data-rel="dialog" data-role="button" >ADD</a>
            </div>
        </form>
    </div>
</div>

<div data-role="page" id="page3" data-url="dialog.html" data-close-btn="right">
    <div data-role="header">
        <h1>Batch Selection</h1>
    </div>
    <div data-role="content">
    <div style="overflow:auto;">
    <table id="batchsel" style="border:1px;">
        <thead>
        <tr>
            <th></th>
            <th>Batch No</th>
            <th>Exp Date</th>
            <th>Brate</th>
            <th>Srate</th>
            <th>Packing</th>
            <th>Stock</th>
            <th>Supplier</th>
            <th>ST%</th>
            <th>Bill Date</th>
            <th>Bill No</th>
            <th>btax</th>
        </tr>
        </thead>
              <!--data populated from server once the values from first page is read properly. 
              <!-- currently not loading the second time as unable to fetch val() -- >
        <tbody>
        </tbody>
    </table>
    </div>
    <div id="remainingdata">
        <p1 id="changeable_requirements"></p1>
        <!-- function the send the checked checkboxes relavent info to store in session --> 
        <button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
    </div>
    </div>
</div>


<script>
$( document ).on( "pageinit", "#page1", function() {

//for product select autopopulate -- working //

$("#productautocomplete").live( "listviewbeforefilter", function ( e, data ) {
        var $ul = $( this ),$input = $( data.input ),value = $input.val(),html = "";
        $ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
            $ul.listview( "refresh" );
        $.getJSON('ajax/getProductList.php', {term:$input.val()}, function(data) {
        var items = [];
        var str = "";
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                var value = data[key].value;
                var label = data[key].label;
                var stock = data[key].stock;
                var proddata = data[key].data;
                str += '<li code="'+value+'" name="'+label+'" stock="'+stock+'" data="'+proddata+'">';
                str += '<a data-ajax="false" rel="external">'+label+' [ '+stock+' ]</a>';
                str += '</li>';
            }
        }
        $ul.html( str );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout" );
        });
        }
    });
    //end search

    //on click set hidden input fields to be used in dialog box. -- working

    $('#productautocomplete li').live('click', function(e) {
    //--------------------fetch data ------------------------
    var id = $(this).attr('code'); 
    var name = $(this).attr('name');
    var data = $(this).attr('data');
    var stock = $(this).attr('stock');
    //add packaging type and unit info to div data
    $('#proddata').attr('data',data);
    //add currstock info to div
    $('#prodstock').attr('data',stock);
    //----------------------hide list
    $('#productautocomplete li').hide();
    //----------------------place name in visible input box
    $('#productsearch input').attr('value',name);
    //----------------------place id in hidden input box for the actual form.
    $('#formproduct').val(id);
    //----------------------fill options for package + show select package div 
    var filteroptions = data.split(",");
    $('#packing option').remove();
    for (var x=0; x<3 ; x++) {
        var eachoption = filteroptions[x].split(":");
        //if unit wise option is less than that of stock show as option. 
        if (eachoption[0]!="0" && eachoption[0] <= stock.valueOf()) {
        $('#packing').append($('<option>', { 
            value: eachoption[0]+':'+eachoption[1],
            text : eachoption[1]+' [ '+eachoption[0]+' ] '
        }));
        }
    }
    });
});

//this is where the problem lies .. 
//have tried with pageinit.. but that only calls it once.
$( document ).on( "pageshow", "#page3", function() {
    $('#batchsel tbody').empty(); 

    // !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!! //
    //doesnt fetch any of 4 following values after pageChange back to page1. 
    //not sure if this is due to how i'm reloading the page1. 
    //see function addProduct below.

    var prodcode = $('#formproduct').val(); // 
    var prodstock = $('#prodstock').attr('data');
    var prodqty = $('#qty').val();
    var packing = $('#packing').find(":selected").val();

    //returns undefined
    alert(prodcode); alert(packing); alert(prodqty); 

    //always ends here when dialog opens second time.
    if (!prodcode || !packing || !prodqty) {
       alert("Please give all required information");
       //does not close also when opens the second time.
       $('#page3').dialog('close');
    }

    var packinginfo = packing.split(":");
    var totalrequired = prodqty * packinginfo[0];
    //alert(packinginfo[1]);alert(totalrequired);
    if (totalrequired > prodstock ) {
    alert("Not enough Stock");
    $('#page3').dialog('close');
    } else {
    //------------------------------ Getting Batch Info ---------------------------------------------------
    var rows = '';
    $.getJSON('ajax/getBatchDetails.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired}, function(data) {
        for (var key in data) {
        if (data.hasOwnProperty(key)) {
            //alert (data[key].Batch);
            rows += '<tr><td><input type="checkbox" class="batchcheckbox" id="batchcheckbox_'+data[key].BatchId+'" value="'+data[key].BatchId+':'+data[key].Stock+'" onchange="resetRemainingQty(this.value);""/></td><td>' + data[key].Batch + '</td><td>' + data[key].ExDt +'</td><td>' + data[key].BRate + '</td><td>' + data[key].SRate + '</td><td>' + data[key].Pack + '</td><td>' + data[key].Stock + '</td><td>' + data[key].Supname + '</td><td>' + data[key].Stax + '</td><td>' + data[key].BillDt + '</td><td>' + data[key].BillNo + '</td><td>' + data[key].btax + '</td><tr>';
        }
        }
        $('#batchsel tbody').append(rows);
        //add remaining amount in the data field of p1. 
        $('#remainingdata p1').attr('data',totalrequired);
        $('#remainingdata p2').attr('data',totalrequired);
        $('#remainingdata p1').html("<h4>Remaining Amount : "+totalrequired+"</h4>");
    });
    //---------------------------------------------end batch info display: -----------------------------------
    }
});

function addProduct() {
    //--------code info---------
    var prodcode = $("#formproduct").val(); // to send
    //--------packing info---------------
    var packing = $('#packing').find(":selected").val();
    var packinginfo = packing.split(":");
    //-----------qty req ---------------------
    var prodqty = $('#qty').val();
    var totalrequired = prodqty * packinginfo[0]; // to send
    //-------------batch info -----------
    var allbatchids = "";
    $('.batchcheckbox').each(function() {
    if($(this).is(':checked')){
        var data = $(this).val();
        var datasplit = data.split(":");
        var batchid = datasplit[0];
        allbatchids += batchid+":";
    }
    });
    allbatchids = allbatchids.substring(0, allbatchids.length - 1); // to send
    alert(prodcode+",,"+packinginfo[1]+",,"+totalrequired+",,"+allbatchids);
    //-------------- send to server to save to session ---------
    $.getJSON('ajax/saveProductSession.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids}, function(data) {
    if (data.error == "1") {
        alert(data.message);
    } else {

        /// !!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!!
        /// 
        /// the loads the page1. but jquery doesnt take val() after this. 
        ///tried multiple variations of this but to no effect. 
        ///removed all options.. redirect to main.php.. reloadpage:false.. etc. 
        ///Any other way to reload the page so that the dialog once open again can 
        ///get the values from the page1 again. 

        $.mobile.changePage("#page1", {  reloadPage: true , dataUrl : "page1", reverse : true, changeHash: true } ); 


    } 
    });
//    
//    $.ajax({
//  type: "POST",
//  url: "ajax/saveProductSession.php",
//  data: { code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids }
//    }).done(function() {});
}
</script>
4

1 回答 1

0

好的 !我让它工作了!无论如何谢谢@Gajotres。脚步 :

1a。通过 changePage 从 main.php 发送变量:

var prodcode = $('#formproduct').val();
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
$.mobile.changePage('batch.php', {
    role: 'dialog', 
    data: {'prodcode': prodcode,'prodstock': prodstock, 'prodqty' : prodqty , 'packing' : packing},
    type: 'get' 
});

2a. 将整个 div id 'page3' 移动到一个名为 'batch.php' 的新 php 页面,我从 php 获取变量并将其设置为 html div。

<?php 
    extract($_GET);
    if (!$prodcode && !$prodstock && !$packing && !$prodqty) {
        header('Location: '.DEF_SITEURL."main.php");
        exit;
    }
?>
<div data-role="page" id="batchpage" data-url="batch.php" data-close-btn="right">

    <div data-role="header">
        <h1>Batch Selection</h1>
    </div>
    <div data-role="content">
    <div style="display:none;" id="batchprodcode" data="<?php echo $prodcode; ?>"></div>
    <div style="display:none;" id="batchprodstock" data="<?php echo $prodstock; ?>"></div>
    <div style="display:none;" id="batchpacking" data="<?php echo $packing; ?>"></div>
    <div style="display:none;" id="batchqty" data="<?php echo $prodqty; ?>"></div>
    <div style="overflow:auto;">
    <table id="batchsel" style="border:1px;">
        <thead>
        <tr>
            <th></th>
            <th>Batch No</th>
            <th>Exp Date</th>
            <th>Brate</th>
            <th>Srate</th>
            <th>Packing</th>
            <th>Stock</th>
            <th>Supplier</th>
            <th>ST%</th>
            <th>Bill Date</th>
            <th>Bill No</th>
            <th>btax</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    </div>
    <div id="remainingdata">
        <p1 id="changeable_requirements"></p1>
        <button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
    </div>
    </div>
</div>

3a。然后,我只需将用于 page3 的 pageshow 更改为在 batch.php 上创建的新 div。该脚本仍然在 main.php 上运行。

$( document ).on( "pageshow", "#batchpage", function() {
   $('#batchsel tbody').empty();
   var prodcode = $('#batchprodcode').attr('data');
   var prodstock = $('#batchprodstock').attr('data');
   var prodqty = $('#batchqty').attr('data');
   var packing = $('#batchpacking').attr('data');
   ...
});
于 2013-03-12T07:49:16.997 回答