9

.html() 関数を介して値属性が更新されたフォームの html を取得することは可能ですか?

(簡略化された) 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());
    });
});

これが私がやろうとしていることの例です: http://jsfiddle.net/brLgC/2/

入力の値を変更して「クリックしてください」を押した後でも、デフォルト値の HTML が返されます。

jQuery 経由で更新された HTML を取得するにはどうすればよいですか?

4

4 に答える 4

5

RGrahamの答えはうまくいかなかったので、次のように変更しました:

$("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());
        }
    }
});
于 2014-11-03T04:23:40.277 に答える
2

Lachlan の作品は「ほぼ」完璧です。問題は、フォームを保存してから復元してから再度保存すると、ラジオとチェックボックスがオフにならず、代わりに複合し続けることです。以下の簡単な修正。

$("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());
        }
    }
});
于 2015-09-11T20:20:46.237 に答える