提问者:小点点

如何通过jQuery获得包含更新值属性的表单html()?


有没有可能通过。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/

在更改输入值并按下“Click me”之后,它仍然返回带有默认值的HTML。

如何通过jQuery简单地获取更新的HTML?


共3个答案

匿名用户

如果您确实必须拥有HTML,则需要实际手动更新“value”属性: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());
    });
});

匿名用户

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());
        }
    }
});

匿名用户

拉克伦的作品“近乎”完美。 问题是,当表单被保存,然后恢复,然后再次保存时,单选框和复选框不会取消选中,而是继续复合。 下面的简单修复。

$("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());
        }
    }
});

相关问题