Denis Koreyba
Denis Koreyba

Reputation: 3718

How to check state of a checkbox if it doesn't have "checked" attribute?

I'm trying to check the state of a checkbox using Selenium Webdriver or Javascript but having done a lot of research I still can't do it.

My problem is: the checkbox doesn't have "checked" attrubute:

<input type="checkbox" name="site[new_sign_up]" id="site_new_sign_up" value="1">

For regular normal checkboxes I use the next string to detect if a checkbox is checked or not:

if (checkbox.GetAttribute("checked") != null && checkbox.GetAttribute("checked").Equals("true"))

I know it could be done with JS:

$get("isAgeSelected").checked == true

But still I can't do it as my checkbox doesn't have "checked" property.

If using selenium I check "Selected" property of element it also doesn't tell me the truth of checkbox state.

Any suggestions of how to do it? Thanks in advance.

Upvotes: 4

Views: 7009

Answers (4)

Suman Websyner
Suman Websyner

Reputation: 1

you can check and uncheck the checkbox by using this code.

if(checkBox1.getAttribute("checked") != null) // if Checked

checkBox1.click(); //to Uncheck it

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55613

The DOM API provides a checked property on all input types, regardless of if they have a checked attribute or not (or even if they aren't check-able, i.e. text elements)

You SHOULD NOT rely on a checked attribute being present to determine if the checkbox is checked.

var x = document.createElement('input');
console.log(x.checked); //false
x.type = 'checkbox';
console.log(x.checked); //false
x.checked = true;
console.log(x.checked); //true
console.log(x); //<input type="checkbox"> - see? no checked attribute, yet it is still checked

Upvotes: 5

Ravi Shankar
Ravi Shankar

Reputation: 1559

We can achieve in js by using below code

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#site_new_sign_up').click(function(){
    if($('#site_new_sign_up').prop('checked')) {
         console.log('Checked');
    } else {
        console.log('Not Checked');
    }
 })
});
</script>

<body>
  <input type="checkbox" name="site[new_sign_up]" id="site_new_sign_up" value="1">
 </body>
</html>

Upvotes: 0

Denis Matafonov
Denis Matafonov

Reputation: 2802

In jquery you should use .prop instead of attribute

$('input').prop('checked') //true-false meaning the checkbox is checked or not

Upvotes: 0

Related Questions