1. 程式人生 > >Javascript/jQuery動態修改radio/checkbox值

Javascript/jQuery動態修改radio/checkbox值

HTML程式碼:

<input name="name1" type="radio" value="1" checked="checked" />1

<input name="name1" type="radio" value="0" />0

Javascript程式碼:

function setInputValue(nameStr, type, value){

var selector = "input[name="+nameStr+"]";//屬性選擇器,name

if(type != null) {
if(type == "radio" || type == "checkbox"){
var obj = $(selector);
for(var i=0; i<obj.length;i++)
if(obj[i].value == value)//比較對應radio元素的值是否是代設定的值.
obj[i].checked = "checked";//是,則將其checked屬性設定為checked.
}
else
$(selector).val(value);
}

}

setInputValue("name1", "radio","1");

注:驗證可行!