0

The below snippet illustrates the problem, when the user adds some input to the second text input field, the alert does not include the new input.

<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $('#click').live('click',function(){ alert($('#test').html())})
  })
</script>

<div id="test">
<input type="text" value="test"/>
<input type="text" value=""/>
</div>

<a id="click">clickme</a>

for convenience: http://jsfiddle.net/CqPkP/

4

3 回答 3

3

The .html() function will not get the updated DOM attributes. You have to manually get the updated attributes.. check below demo,

DEMO: http://jsfiddle.net/skram/CqPkP/2/

Full Code:

$(document).ready(function() {
    $('#click').live('click', function() {
        alert($('#test').formhtml())
    })
});

(function($) {
    var oldHTML = $.fn.html;

    $.fn.formhtml = function() {
        if (arguments.length) return oldHTML.apply(this, arguments);
        $("input,button", this).each(function() {
            this.setAttribute('value', this.value);
        });
        $("textarea", this).each(function() {
            // updated - thanks Raja!
            this.innerHTML = this.value;
        });
        $("input:radio,input:checkbox", this).each(function() {
            // im not really even sure you need to do this for "checked"
            // but what the heck, better safe than sorry
            if (this.checked) this.setAttribute('checked', 'checked');
            else this.removeAttribute('checked');
        });
        $("option", this).each(function() {
            // also not sure, but, better safe...
            if (this.selected) this.setAttribute('selected', 'selected');
            else this.removeAttribute('selected');
        });
        return oldHTML.apply(this);
    };

    //optional to override real .html() if you want
    // $.fn.html = $.fn.formhtml;
})(jQuery);

Ref: jQuery html() in Firefox (uses .innerHTML) ignores DOM changes

于 2012-06-11T19:16:46.230 回答
0

Im not sure if I understand u correct but try to use val() function to retrieve the value of the textbox. See mor infos here in the docs http://api.jquery.com/val/

于 2012-06-11T19:14:37.803 回答
0

When the user enters input into an input element, it does not update the HTML of that input. So calling .html() on it won't give you the new data that is in the field.

If you want to just get all the values in the input fields, you can do something like this:

$('#click').live('click',function(){
  alert($('#test input').map(function() { return this.value; }).get());
});

You have to use map because calling val() will only give you the value of the first input element.

于 2012-06-11T19:19:52.110 回答