Javascript if checked display

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. For example, if the age checkbox is checked, then I need to show a textbox to enter age , else hide the textbox. But the following code returns false by default:

if ($('#isAgeSelected').attr('checked')) < $("#txtAge").show(); >else

Starting jquery 1.6 there have been significant changes the way attributes and properties are dealt with. For your case following should work: if($(‘#isAgeSelected’).prop(«checked»)) < $("#txtAge").show(); >else < $("#txtAge").hide(); >The condition in if statement will simply return true or false depending upon the checked/unchecked state of the check box. For more details refer to attributes vs. properties section on this link.

68 Answers 68

How do I successfully query the checked property?

The checked property of a checkbox DOM element will give you the checked state of the element.

Given your existing code, you could therefore do this:

if(document.getElementById('isAgeSelected').checked) < $("#txtAge").show(); >else

However, there’s a much prettier way to do this, using toggle :

$('#isAgeSelected').click(function() < $("#txtAge").toggle(this.checked); >);

This is not an answer to the question. this.checked is not jQuery, as the OP asked for. Also, it only works when user clicks on the checkbox, which is not part of the question. The question is, again, How to check whether a checkbox is checked in jQuery? at any given time with or without clicking the checkbox and in jQuery.

Читайте также:  Таблицы

How would “is not jQuery” be an argument? That attitude is quite harmful and the reason why it’s so hard to get rid of jQuery nowadays! If you can use vanilla JavaScript from ages ago, which works everywhere and is in no way more complicated to use or longer to write, you should definitely do so.

Not only that but jquery is a javascript extension, and therefore contains all of javascript. . In any case «this» is a jquery object so he’s completely wrong anyway.

«How would ‘is not jquery’ be an argument?» Because, while you can indeed use both jquery and plain js on the same script, it’s more readable if you use one coding style rather than two. And if you already accepted the jquery tradeoffs, you may as well use it.

if($("#isAgeSelected").is(':checked')) $("#txtAge").show(); // checked else $("#txtAge").hide(); // unchecked 
 // traditional attr $('#checkMeOut').attr('checked'); // "checked" // new property method $('#checkMeOut').prop('checked'); // true 

Using the new property method:

if($('#checkMeOut').prop('checked')) < // something when checked >else < // something else when not >

Doesn’t work if you have a alongside the checkbox like several frameworks do in order to always submit a value. .is(‘:checked’) on the other hand works in that case.

jQuery 1.5 and below

Any version of jQuery

// Assuming an event handler on a checkbox if (this.checked) 

Doesn’t work if you have a alongside the checkbox like several frameworks do in order to always submit a value. .is(‘:checked’) on the other hand works in that case.

I am using this and this is working absolutely fine:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked"); 

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the «TRUE» value.

 Planned $("#planned_checked").change(function() < if($(this).prop('checked')) < alert("Checked Box Selected"); >else < alert("Checked Box deselect"); >>); 
 $("#planned_checked").change(function() < if($(this).prop('checked')) < alert("Checked Box Selected"); >else < alert("Checked Box deselect"); >>);

Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element’s checked state. Instead, you should use jQuery.prop() :

$("#txtAge").toggle( $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false; // Return value changes with checkbox state ); 

Two other possibilities are:

$("#txtAge").get(0).checked $("#txtAge").is(":checked") 
$get("isAgeSelected ").checked == true 

Where isAgeSelected is the id of the control.

Also, @karim79’s answer works fine. I am not sure what I missed at the time I tested it.

Note, this is answer uses Microsoft Ajax, not jQuery

If you are using an updated version of jquery, you must go for .prop method to resolve your issue:

$(‘#isAgeSelected’).prop(‘checked’) will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $(‘#isAgeSelected’).attr(‘checked’) and $(‘#isAgeSelected’).is(‘checked’) is returning undefined which is not a worthy answer for the situation. So do as given below.

if($('#isAgeSelected').prop('checked')) < $("#txtAge").show(); >else

This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.

You can try the change event of checkbox to track the :checked state change.

$("#isAgeSelected").on('change', function() < if ($("#isAgeSelected").is(':checked')) alert("checked"); else < alert("unchecked"); >>);

Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!

Ideally, you’d want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it’s done so).

$('#isAgeSelected').bind('change', function () < if ($(this).is(':checked')) $("#txtAge").show(); else $("#txtAge").hide(); >); 

I ran in to the exact same issue. I have an ASP.NET checkbox

In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked')) < . >else

I’m sure you can also use the ID instead of the CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked')) < . >else

you can use the css class, as long as you keep in mind that css classes aren’t meant to be unique. If you want to respond to changes in a single element then ID would be the preffered way to go.

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0) < $("#txtAge").show(); >else

This is the best answer for selecting ONLY those that are checked in the first place. $(‘#isAgeSelected :checked’)

I decided to post an answer on how to do that exact same thing without jQuery. Just because I’m a rebel.

var ageCheckbox = document.getElementById('isAgeSelected'); var ageInput = document.getElementById('txtAge'); // Just because of IE ; 

First you get both elements by their ID. Then you assign the checkboxe’s onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.

Here is a fiddle for you to test it.

If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.

elem.style.display = this.checked ? 'inline' : 'none'; 

Slower but cross-browser compatible.

Источник

Display Text When Checkbox Is Checked in JavaScript

Display Text When Checkbox Is Checked in JavaScript

  1. Use JavaScript .checked Property to Display Text When Checkbox Is Checked
  2. Use jQuery is() Function and JavaScript .checked Property to Display Text When Checkbox Is Checked
  3. Use jQuery ready and click Events to Display Text When Checkbox Is Checked

This article introduces you to the different techniques to display text when the checkbox is checked in JavaScript. It also educates you about JavaScript and jQuery functions and events.

Use JavaScript .checked Property to Display Text When Checkbox Is Checked

 html>  head>  title>JavaScript Checkboxtitle>  head>  body>  p>Let see how to know if check box is checked:p>  label for="check">Checkbox:label>  input type="checkbox" id="check" onclick="checkfunction()">  p id="message" style="display:none">Checkbox is Checked Now!p>  body>  html> 
function checkfunction()   var check = document.getElementById("check");  var message = document.getElementById("message");  if (check.checked == true)   message.style.display = "block";  >  else   message.style.display = "none";  > > 

The code given above gets the elements by targeting their id’s values, check and message . Then, it checks if the value of check.checked is true or false .

If it is true , it displays the message stored in the message variable. However, the .checked is a Boolean property that can be either true or false .

We can use this property within pure JavaScript and combine it with the jQuery function.

Rather than displaying the message on the window to tell whether the checkbox is checked or not, we can use the alert function to show a popup message in the browser. You can replace your JavaScript code with the following to practice.

function checkfunction()  if ((document.getElementById("check")).checked)   alert("The checkbox is checked");  >  else  alert("The checkbox is not checked")  > > 

Use jQuery is() Function and JavaScript .checked Property to Display Text When Checkbox Is Checked

 html>  head>  title>JavaScript Checkbox Practicetitle>  script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">script>  head>  body>  input type="checkbox" id="check"> Check it and Submit  button onclick="checked()"> Submit button>  body>  html> 
function checked()   if ($('#check').is(':checked'))   alert("Checked");  >  else   alert("Not Checked");  > > 

The checked() method gets executed in the code given above if you click on the button titled Submit . This method gets the first element whose id attribute’s value is check .

Further, it checks if the element’s checked property is true or false . How? Here, the is() function checks if the selected element matches the selector element.

The is() function checks the current element with the other element; it can be a selector or a jQuery object.

The is() method takes two parameters, one is mandatory, and the other is optional (the selectorElement is mandatory, and the function(index, element) is optional). This function returns true if the condition fulfills false .

Keep in mind that $ is acting like document.getElementById here. The above code will show Checked if the checkbox will be checked; otherwise, Not Checked .

Use jQuery ready and click Events to Display Text When Checkbox Is Checked

html>  head>  title>practice ready and click eventstitle>  script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">script>  head>  body>  input type="checkbox" id="check"> Check it  body>  html> 
$(document).ready(function()  $("input").click(function()  alert("You checed. ");  >); >); 

The ready and click are jQuery Events used in JavaScript.

The ready event happens when the document object model (DOM) is loaded. You can see more details about ready here.

The click is used to assign the click event to the selected element. In our example, it is an input tag. You can read here for more details.

Remember, you can use these events only if you want to check the checkbox. The reason is that it detects the click event rather than checking the checked property.

In the output given above, you can observe that it shows You Checked always. It does not care whether you uncheck or not, but it just detects whether you click or not.

It notices the click event, which is helpful to know if the checkbox is checked only. It would not be a good choice if you also want to know whether the checkbox is unchecked or not.

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article — JavaScript Checkbox

Источник

Оцените статью