jQuery(赋值给表单内容)

百度的招聘网站百伯年前就上线了,偶然看到其中用了一个jQuery的函数挺好玩就扒了下来。

var setValue = function(name, val){

if(val != ""){

var htmlType = $("[name='"+name+"']").attr("type");

if(htmlType == "text" || htmlType == "textarea" || htmlType == "select-one" || htmlType == "hidden" || htmlType == "button"){

$("[name='"+name+"']").val(val);

}else if(htmlType == "radio"){

$("input[type=radio][name='"+name+"'][value='"+val+"']").attr("checked",true);

}else if(htmlType == "checkbox"){

var vals = val.split(",");

for(var i=0; i < vals.length; i++){

$("input[type=checkbox][name='"+name+"'][value='"+vals[i]+"']").attr("checked",true);

}

}

}

};

使用实例:

用到的HTML内容:

<select name="education" type="select-one">

<option value="">请选择</option>

<option value="1">初中</option>

<option value="2">高中</option>

<option value="4">中专</option>

<option value="5">大专</option>

<option value="6">本科</option>

<option value="7">硕士</option>

<option value="10">博士</option>

<option value="11">其他</option>

</select>

<br />

<input type="radio" name="radio" value="1" id="radio_0" />1

<input type="radio" name="radio" value="2" id="radio_1" />2

<br />

<input name="chk" type="checkbox" value="1" />1

<input name="chk" type="checkbox" value="2" />2

<input name="chk" type="checkbox" value="3" />3

<br />

<input type="text" name="txt" value="" />

<br />

<input type="button" name="button" value="" />

<br />

<textarea name="textarea" cols="6" rows="7" type="textarea"></textarea>

对应的JS内容:

$(function(){

setValue("education", "1");

setValue("radio", "2");

setValue("chk", "1, 2");

setValue("txt", "1, 2");

setValue("button", "1, 2");

setValue("textarea", "werwer");

});

已有1条评论 »

  1. 范德萨

添加新评论 »