2017-05-31 94 views
1

我想使用相同的腳本獲取多個文本框的值。在我的腳本中,我正在獲取單個文本框的值更改前後的文本框值。我怎樣才能爲多個文本框編寫相同的JavaScript?如何獲取多個文本框值?

<div align="center"> 
    <table> 
    <tr> 
     <td> 
     <input type="text" id="bill" name="billid" class="update" 
       value="<?php echo $get['BillID']; ?>"> 
     </td> 
     <td> 
     <input type="text" id="proname" name="productname" class="update" 
       value="<?php echo $get['Productname']; ?>"> 
     </td> 
     <td> 
     <input type="text" id="rate" name="rate" class="update" 
       value="<?php echo $get['Rate']; ?>"> 
     </td> 
     <td> 
     <input type="text" id="quantity" name="quantity" class="update" 
       value="<?php echo $get['Quantity']; ?>"> 
     </td> 
     <td> 
     <input type="text" id="amount" name="amount" class="update" 
       value="<?php echo $get['Amount']; ?>"> 
     </td> 
    </tr> 
    <tr> 
     <td></td> 
     <td></td> 
     <td> 
     <input type="submit" name="submit" value="submit" onclick="sendvalue()"> 
     </td> 
    </tr> 
    </table> 
</div> 

我的劇本是

$('#bill').on('focus', function() { 
    $(this).data('val', $(this).val()); 
}); 

function sendvalue() { 
    var prev = $('#bill').data('val'); 
    var current = $("#bill").val(); 
    //alert(prev+";"+current); 

    $.ajax({ 
    type: "POST", 
    url: "updateedit.php", 
    data: ({ 
     previous: prev, 
     currentvalue: current, 
    }), 
    success: function(data) { 
     alert(data); 
    }, 
    error: function() { 
     alert('failed'); 
    }    
    }); 
} 
+0

這是一個比較普遍評論:你真的應該看看[接受](https://meta.stackexchange.com/q/5234)你的問題的答案。它有助於未來的訪問者查看是否有答案(以及哪個答案)幫助您解決問題。 –

+0

使用'$(input [type = text])'或'$(「:text」)'選擇器 – inarilo

+0

您是否考慮過像[AngularJS](https://angularjs.org/)這樣的框架?框架使事情變得更容易。 –

回答

0

而不是使用id選擇嘗試通過輸入類型,還發出一個jQuery.each()得到的結果。

$.each($("input[type=text]"), function(index, value) { 
     //What you want to do for every text input 
    }); 
0

首先按類別update選擇所有輸入併爲焦點事件附加事件列表器。

然後就可以調用sendvalue功能和發送對象的數組來批量更新所有的值到後端(改變你的PHP代碼收到一個數組,而不是一個單一的對象)

$('input.update').on('focus', function() { 
    $(this).data('val', $(this).val()); 
}); 

function sendvalue() { 
    // Array 
    var postData = []; 
    $('input.update').each(function() { 
    var inp = $(this); 
    postData.push({ 
     previous: inp.data('val'), 
     currentvalue: inp.val() 
    }); 
    }); 

    $.ajax({ 
    type: "POST", 
    url: "updateedit.php", 
    data: postData, 
    success: function(data) { 
     alert(data); 
    }, 
    error: function() { 
     alert('failed'); 
    }    
    }); 
} 
+0

感謝您的寶貴答案@kapantzak我在我的PHP頁面上嘗試使用foreach($ _ POST ['postdata']作爲$ value)。但我沒有得到任何價值,我怎麼能嘗試別的。 – arjun

+0

postData仍然沒有得到任何值@kapantzak。我爲它感到震驚。 – arjun