2017-05-31 95 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