Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Denis Koreyba Avatar asked Oct 28 '25 15:10

Denis Koreyba


1 Answers

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
like image 135
Adam Avatar answered Oct 31 '25 04:10

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!