JQuery function: html () gets old data in form

I am using jQuery to read data on an HTML page. On this page, I have an element <form>that contains tags <input>for the user to enter their values.
Upon initialization, this form has some default values ​​for these elements <input>. When I submit this form, I use the method html()to get the HTML string of the current state of this page, but I don’t understand why this result string still contains the old values ​​(the default values ​​for input) and not the new ones. Is there a way to update or save a user-entered value for these elements <input>before calling html()? How can I get a string that contains the latest value using jQuery methods?
Thank you very much!

+5
source share
3 answers

However, it’s strange that you are trying to do, but all you need to do is update the value attribute of the form elements. This can be done using the following code (put it in a handler submit):

$("form input").attr("value", function() {
    return this.value;
});

DEMO: http://jsfiddle.net/BXha6/

+5
source

By default, the jQuery function will html()save the properties defaultValueand defaultChecked, rather than using the current values ​​/ selection (as JavaScript does innerHTML). To get around this, you need to use jQuery first prop(): Read the prop () documentation .

For example, given the code:

<form action='/'>
   <input type='radio' value='1' checked name='first' />
   <input type='radio' value='2' name='first' />

   <input type='checkbox' value='yes' />

   <input type='text' value='Start Text' name='second' />
</form>

then

   $('form').html()

It always displays this exact code no matter what values ​​you added / selected / changed.

, :

$("form input[type='radio']").each(function(){
   if (this.checked){
      $(this).prop("defaultChecked",true);
   } else {
      $(this).prop("defaultChecked",false);
   }
});
$("form input[type='checkbox']").each(function(){
   if (this.checked){
      $(this).prop("defaultChecked",true);
   } else {
      $(this).prop("defaultChecked",false);
   }
});
$("form input[type='text']").each(function(){
   $(this).prop("defaultValue",$(this).val());
});

alert( $(form).html() ); //or var the_code = $(form).html();

HTML, .

+2

the textarea bit is a bit different if you were looking for how to do this:

 $("textarea").html( function() {
    return this.value;
});

http://jsfiddle.net/BXha6/7/

0
source

All Articles