Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

dom

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

The (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>

The jQuery:

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

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

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

How can I simply get the updated HTML via jQuery?

like image 729
santacruz Avatar asked May 29 '13 15:05

santacruz


People also ask

How can I get attribute value in jQuery?

The jQuery attr() method is used to get attribute values.

Which jQuery function is used the change the value of attribute?

Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.

Which jQuery method sets or returns the value of selected form elements?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


1 Answers

Lachlan's works "almost" perfect. The issue is when the form is saved and then restored then saved again the radio and checkboxs do not uncheck and instead just keep compounding. 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());
        }
    }
});
like image 194
BWM Avatar answered Sep 17 '22 19:09

BWM