How to get html () form via jQuery, including updated value attributes?

Is it possible to get html forms with updated value attributes via the .html () function?

(simplified) HTML:

<form> <input type="radio" name="some_radio" value="1" checked="checked"> <input type="radio" name="some_radio" value="2"><br><br> <input type="text" name="some_input" value="Default Value"> </form><br> <a href="#">Click me</a> 

jQuery:

 $(document).ready(function() { $('a').on('click', function() { alert($('form').html()); }); }); 

Here is an example of what I'm trying to do: http://jsfiddle.net/brLgC/2/

After changing the input value and clicking "click me", it still returns HTML with default values.

How can I just get the updated HTML via jQuery?

+6
source share
3 answers

If you really have HTML, you need to actually update the value attribute manually: http://jsfiddle.net/brLgC/4/

 $(document).ready(function() { $('a').on('click', function() { $("input,select,textarea").each(function() { if($(this).is("[type='checkbox']") || $(this).is("[type='checkbox']")) { $(this).attr("checked", $(this).attr("checked")); } else { $(this).attr("value", $(this).val()); } }); alert($('form').html()); }); }); 
+6
source

RGraham's answer did not work for me, so I changed it to:

 $("input, select, textarea").each(function () { var $this = $(this); if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) { if ($this.prop("checked")) { $this.attr("checked", "checked"); } } else { if ($this.is("select")) { $this.find(":selected").attr("selected", "selected"); } else { $this.attr("value", $this.val()); } } }); 
+5
source

Lahlan works "almost" perfectly. The problem is when the form is saved, then restored, and then saved again, and the radio and checkboxes are not removed, but instead just save the recipe. A simple fix below.

 $("input, select, textarea").each(function () { var $this = $(this); if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) { if ($this.prop("checked")) { $this.attr("checked", "checked"); } else { $this.removeAttr("checked"); } } else { if ($this.is("select")) { $this.find(":selected").attr("selected", "selected"); } else { $this.attr("value", $this.val()); } } }); 
0
source

Source: https://habr.com/ru/post/946100/


All Articles