What is more common way to check the checkbox and radio state?

I see around about some use .length and some just a “!” to check.

 if (!$(this).is(':checked'))
 {
 // do something
 }
 else
 {
 // do something
 }

 if ($(this).is(':checked').length)
 {
 // do something
 }
 else
 {
 // do something
 }

 if ($(this).not(':checked'))
 {
 // do something
 }
 else
 {
 // do something
 }

.length is give back a number? so work that way and the “!” means is not so that works also what is more common way? still the .not() is also works. Or still any other ways?

  1. There is no length property on is() and it returns a Boolean.

  2. not() isn’t doing what you think it is (it does have a length property).

  3. You can also use prop(‘checked’).

Open the console to see the logs

1 Like

Thank you! By the way you you recomand for to check if .prop(‘checked’) not checked?

You can use ! (not)

!$('#check').prop('checked')

Or you can explicitly check for true/false

$('#check').prop('checked') === true
$('#check').prop('checked') === false
1 Like

Still figure it out with :not(:checked) :sunny:

Try this code

var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
    if (radios[i].type === 'radio' && radios[i].checked) {
        // get value, set checked flag or do whatever you need to
        value = radios[i].value;       
    }
}
1 Like

Or use querySelector:

let checked = document.querySelector("input:checked"),
    value = checked.value || null;

if(value){
  // do something with value
} else {
  // value is null so do something else
}

we’ll cover the different methods for selecting the checkbox and radio button elements. Then, there’ll be a practice exercise where we’ll give you an HTML form and the example code for the hands-on. You may also love to try out mind-boggling [Selenium Webdriver quizzes on our blog.

  1. [Various methods] to select a checkbox and radio button.
  2. *[Use ID for Selecting Checkbox/Radio button.]
  3. *[Use the “IsSelected” Method to Check the State of Checkbox/Radio button
  4. *[Use Element Value for Selecting Checkbox/Radio button.]
  5. *[Use CssSelector for Selecting Checkbox/Radio button.]
  6. ***[HTML form and example code for hands-on practice.]

Checkbox And Radio Button Operations In Webdriver.

1- Various Methods To Select A Checkbox And Radio Button.

1.1- Use ID For Selecting Checkbox/Radio Button.

You can use the ID attribute to select a Radio Button or a CheckBox. We’ve provided the Webdriver command to click which you can apply to both types of elements.

// Java code example to select checkbox/radio button. WebElement target = driver.findElement(By.id(“checkbox1”)); target.click();

1.2- Use The IsSelected Method To Check The State Of Checkbox/Radio Button.

If you’ve selected/deselected a Checkbox/Radio Button and you just want to check its final state. Then, you can use the < IsSelected> command to know that the correct status of the element.