;!(function ($)
{
$.fn.setFormValue = function (options)
{
var $this = $(this);
$.each(options, function (key, value)
{
var obj = $this.find("*[name=" + key + "]");
if (obj.attr("type") == "checkbox")
{
if ($.type(value) === "boolean")
{
obj.attr("checked", value);
}
if ($.type(value) === "object")
{
$.each(value, function (i, item)
{
$this.find("*[name=" + key + "][value=" + i + "]").attr("checked", item);
})
}
}
else if (obj.attr("type") == "radio")
{
$this.find("*[name=" + key + "][value=" + value + "]").attr("checked", true);
}
else
{
obj.val(value);
}
})
}
})(jQuery)
使用
$("#form").setFormValue({
"input": "zsw",//input标签
"textarea": "多行文本",//多行文本
"select":"2",//选择标签
"test": {
1: true,
2: false,
3: true
},//多选框
"checkboxtest": true,//多选框2
"radiotest":"2"
})
html代码
<form id="form">
<div class="form-group">
<label for="exampleInputEmail1">input</label>
<input type="text" class="form-control" name="input" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">input</label>
<textarea name="textarea">
</textarea>
</div>
<div class="form-group">
<label>select</label>
<select name="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="checkbox">
<div>
<label>
<input type="checkbox" name="test" value="1">
第一个
</label>
</div>
<div>
<label>
<input type="checkbox" name="test" value="2">
第二个
</label>
</div>
<div>
<label>
<input type="checkbox" name="test" value="3">
第三个
</label>
</div>
<div>
<label>
<input type="checkbox" name="test" value="4">
第四个
</label>
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="checkboxtest">
第一个
</label>
</div>
<div class="checkbox">
<label>
<input type="radio" name="radiotest" value="1">
一
</label>
<label>
<input type="radio" name="radiotest" value="2">
二
</label>
<label>
<input type="radio" name="radiotest" value="3">
三
</label>
</div>
<input type="button" value="确定" οnclick="setValueTest()" />
</form>