0

I need to check whether a textbox in a form on my webpage has been checked. I implement the textbox in my html code as such:

<input type="checkbox" id="language1" name="language1" 
value="Python"> Python

I tried using the following code to check if the checkbox had been ticked:

if($('#language1').checked){
    // do some stuff }

This did not work - the website never recognised the box being ticked. I then poked around Stack Overflow and found two alternatives to the above, namely:

if($('#language1')[0].checked){

and

if($('#language1').is(':checked'));

Each of the two alternatives worked, but my original implementation didn't. I don't understand why that is the case - I thought all three options should essentially do the same thing? Keen to get to the bottom of this so will appreciate an explanation.

mathmagician
  • 45
  • 1
  • 3
  • 6

3 Answers3

2

I thought all three options should essentially do the same thing?

No . Because the checked property is a property of an input element.

$(selector) returns a jQuery object that contains the element but is not the element itself and the jQuery object does not have a checked property

Using $(selector)[0] returns the first matching element within the jQuery object... where the property exists

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

The first example returns a list of all elements matching the CSS selector. In this case, that list has exactly one element, but it is not the same as that element. That is why you need the [0] in the second example.

(Alternatively, you could use jQuery's built-in get() method to accomplish the same thing.)

function print() {
  if ($('#language1').get(0).checked) {
    console.log("Yes");
  }
  else {
    console.log("No");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="language1" name="language1" 
value="Python"> Python
<br>
<button onclick="print()">Click me</button>
StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
0

Because $('#language1') represents jQuery collection of all HTML elements fit selector #language1 not elements themselves. $('#language1')[0] in turn represents first HTML element in that collection. JQuery provides an interface on that collection to interact with html elements inside it, and that interface does not have checked property, because of it is too specific to checkboxes only, and it is property, and can not be proxies through collection interface. .is(':checked')) is a method, returning true if selector provides in it ':checked' is applicable to any (or all, not sure here) elements in collection,. This is the way how JQuery developers see making a check if elements in collection, have checked flag

skazska
  • 421
  • 2
  • 8