您的位置:首页 > 其它

Radio CheckBox的常用方法(自己总结)

2013-10-18 00:00 288 查看
代码


<
form
>
性别:
<
input
type
="radio"
name
="sex"
value
="1"

/>
男
<
input
type
="radio"
checked
="checked"
name
="sex"
value
="0"

/>
女
<
br
/>
水果:
<
input
type
="checkbox"
name
="fruit"
value
="1"

/>
苹果
<
input
type
="checkbox"
name
="fruit"
value
="2"

/>
香蕉
<
input
type
="checkbox"
name
="fruit"
value
="3"

/>
橘子
</
form
>

<
button
onclick
="getRadioValue()"

3ff0
>
Radio值
</
button
>

<
button
onclick
="getCheckboxValue()"
>
CheckBox值
</
button
>

<
button
onclick
="doAll()"
>
全选
</
button
>

<
button
onclick
="doNotAll()"
>
反选
</
button
>






获取Radio的值(判断选中哪个)


function
getRadioValue() {
//
var sex = $("input[name='sex']:checked").val(); //方式一

var
sex
=
$(
"
:radio:checked
"
).val();
//
方式二

alert(sex); }


获取CheckBox的值(选中状态下,获取值)


function
getCheckboxValue() {
//
var len = $("input[type=checkbox]:checked").length;

var
len
=
$(
"
:checkbox:checked
"
).length;
if
(len
!=

0
) {
/*
for(var i=0;i<len;i++) { //var thisValue = $($("input[type=checkbox]:checked")[i]).val(); var thisValue = $($(":checkbox:checked")[i]).val(); alert(thisValue); }
*/
$.each($(
"
:checkbox:checked
"
),
function
() { alert($(
this
).val()); }); }
else
{ alert(
'
复选框没有被选中
'
); } }


CheckBox全选


function
doAll() {
/*
$("input[type=checkbox][name=fruit]").each(function(){ jQuery(this).attr("checked", true); });
*/
$(
"
:checkbox[name=fruit]
"
).each(
function
() { $(
this
).attr(
"
checked
"
,
true
); }); }


CheckBox反选


function
doNotAll() {
/*
$("input[type=checkbox][name=fruit]").each(function(){ jQuery(this).attr("checked", false); });
*/
$(
"
:checkbox[name=fruit]
"
).each(
function
() { jQuery(
this
).attr(
"
checked
"
,
false
); }); }


动态给Radio(测试) CheckBox赋值(CheckBox基本同Radio,未测试CheckBox)


$(document).ready(
function
() {
//
给Rodio设置初始值(方法一)

var
_sex
=

1
;
//
模拟后台传来的值

if
(_sex
==

'
1
'
) { $(
"
input[name=sex][value=1]
"
).attr(
"
checked
"
,
true
); }
else
{ $(
"
input[name=sex][value=0]
"
).attr(
"
checked
"
,
true
); } });



<
form
>
性别:
<
input
type
="radio"
<c:if test
="${后台传来的值 }==value"
>
checked="checked"
</
c:if
>
name="sex" value="1" />男
<!--
在标签中用<c:if></c:if>判断
-->

<
input
type
="radio"
checked
="checked"
name
="sex"
value
="0"

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