[英]How to get form html() via jQuery including updated value attributes?
是否可以通过 .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?
如果你真的必须有 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());
}
}
});
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());
}
}
});
与 textarea 一起工作的版本如下
$("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 if ($this.is("textarea")) {
$this.html($this.val());
} else {
$this.attr("value", $this.val());
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.