Testing if a checkbox is checked with jQuery

2019-01-03 03:48发布

If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?

$("#ans").val() will always give me one right in this case:

<input type="checkbox" id="ans" value="1" />

20条回答
放我归山
2楼-- · 2019-01-03 04:23
<input type="checkbox" id="ans" value="1" />

Jquery : var test= $("#ans").is(':checked') and it return true or false.

In your function:

$test =($request->get ( 'test' )== "true")? '1' : '0';
查看更多
女痞
3楼-- · 2019-01-03 04:26

Stefan Brinkmann's answer is excellent, but incomplete for beginners (omits the variable assignment). Just to clarify:

// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;

It works like this:

 var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;

Example:

var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );

Alerts 'no'

If this is helpful, please upvote Stefan Brinkmann's answer.

查看更多
Evening l夕情丶
4楼-- · 2019-01-03 04:28

Just use $(selector).is(':checked')

It returns a boolean value.

查看更多
你好瞎i
5楼-- · 2019-01-03 04:30
// use ternary operators
$("#ans").is(':checked') ? 1 : 0;
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-03 04:30
$('input:checkbox:checked').val();        // get the value from a checked checkbox
查看更多
小情绪 Triste *
7楼-- · 2019-01-03 04:30

I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use prop() attribute.

var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;

this worked in my case maybe someone will need it.

When I've tried .attr(':checked') it returned checked but I wanted boolean value and .val() returned value of attribute value.

查看更多
登录 后发表回答