;!(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="確定" onclick="setValueTest()" />
</form>
