开发者

collect value only from the text input that have been changed

I have a html page that after ajax call show a lot of data rows, in every row i have input text with different value, the user can edit this text input and then press a button to do some calculate action.

How can I collect with javascript(jQuery) only this values that have been changed, and send them to php script. I search a simple way, not to save 开发者_JS百科all big array of old values then compare with new values, Is there such solution?


You can use the .data() function to keep a copy of their original values, then compare that against their values when submitting to make sure that only changed values are submitted.

var inputs = $('input[type="text"]').each(function() {
    $(this).data('original', this.value);
});

$('#form').submit(function(){
    inputs.each(function() {
        if ($(this).data('original') !== this.value) {
            // Do something for the changed value
        } else {
            // And something else for the rest.
        }
    });
});

See a demo of this here: http://www.jsfiddle.net/yijiang/twCE9/


You can use the onChange event of the input field and collect the info in some hidden field or global array field for this.


You bind to the change event for each data input and either store those name-value pairs in a global array or into hidden form fields.

An alternative would be to add a "changed" class to each field which was edited. Then when they submit the form, you could either create a new form with just those elements of class changed or remove the other elements from your form containing all the text inputs.

<input type="text" class="data_input" name="name1" value="value1" />
<input type="text" class="data_input" name="name2" value="value2" />
...
<input type="text" class="data_input" name="nameX" value="valueX" />

Then in your JS

$(document).ready(function() {
    $(".data_input").change(function() {
        $(this).addClass('changed');
    });

Or if you're willing to use a global array:

var changedArr = [];
$(document).ready(function() {
    $(".data_input").change(function() {
        changedArr.push({'name': $(this).attr('name'), 'value': $(this).val()});
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜