您的位置:首页 > Web前端 > JQuery

jquery的val用法举例

2013-10-06 12:31 417 查看
<script language="JavaScript">

//<input type="button" value="使单选下拉框的'2号'被选中"/>

<br>

$("input[type=button]:eq(0)").click(function(){

/* * <select id="one">

<option>1号</option>

<option>2号</option>

<option>3号</option>

</select>

*/

//方法一:普通方法

//$("#one option:eq(1)").attr("selected","selected");

//方法二 $("#one").val("2号");

});

//<input type="button" value="使多选下拉框选中的'2号'和'5号'被选中"/>

<br>

$("input[type=button]:eq(1)").click(function(){

/* * <select id="many" multiple="multiple" style="height:120px;">

<option selected="selected">1号</option>

<option>2号</option>

<option>3号</option>

<option>4号</option>

<option>5号</option>

<option selected="selected">6号</option>

</select>

*/

//方法一:普通方法 //

$("#many option").each(function(index,domEle){

// $(domEle).attr("selected",null);

// if(index==1||index==4){

// $(domEle).attr("selected","selected");

// }

// });

//方法二

$("#many").val(["2号","5号"]);

});

//<input type="button" value="使复选框的'复选2'和'复选4'被选中"/>

<br>

$("input[type=button]:eq(2)").click(function(){

/* * <input type="checkbox" name="c" value="check1"/> 复选1

<input type="checkbox" name="c" value="check2"/> 复选2

<input type="checkbox" name="c" value="check3"/> 复选3

<input type="checkbox" name="c" value="check4"/> 复选4

*/

//方法一:普通方法

// $("input[type=checkbox]").each(function(index,domEle){

// if(index==1||index==3){

// $(domEle).attr("checked","checked");

//

} //

});

//方法二:利用val()方法为多选框赋值,传入的参数是多选框的value属性的值

$("input[type=checkbox]").val(["check2","check4"]);

});

//<input type="button" value="使单选框的'单选2'被选中"/>

<br>

$("input[type=button]:eq(3)").click(function(){

/* * <input type="radio" name="r" value="radio1"/> 单选1

<input type="radio" name="r" value="radio2"/> 单选2

<input type="radio" name="r" value="radio3"/> 单选3 */

//方法一:普通方法 //

$("input[type=radio]").each(function(index,domEle){

// if(index==1){

// $(domEle).attr("checked","checked");

// }

// });

// $("input[type=radio]:eq(1)").attr("checked","checked");

//方法二 //利用val()方法为多选框和单选框赋值的时候,无论赋值是多个还是一个,都需要利用"[]"包裹起来

$("input[type=radio]").val(["radio2"]);

});

//<input type="button" value="打印已经被选中的值">

<br>

$("input[type=button]:eq(4)").click(function(){

$("select option:selected").each(function(index,domEle){

alert($(domEle).text());

});

//多个属性过滤选择器使用时,是交集,不是并集

// $("input[type=checkbox][type=radio]")

$("input:checked").each(function(index,domEle){

alert($(domEle).val());

});

});

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: