Setting Checkbox Options w/ JS

Setting Checkbox Options with JS

https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery?page=2&tab=scoredesc#tab-top

NATS




<!-- pre select specific join option - put after initial call setup -->

{literal}
<noscript>
	<style> .jscript-only { display: none } </style>
</noscript>
<script language="javascript">
	$(document).ready(function() {
			{/literal}


// Sets the default selected option
			option = 'option-3100'; // selected option ID
			press_option(option);


{literal}
	});
{/literal}
</script>



 

 

Modern jQuery

Use .prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

jQuery 1.5.x and below

The .prop() method is not available, so you need to use .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

In case you use ASP.NET MVC, generate many checkboxes and later have *to select/unselect all* using JavaScript you can do the following.

HTML

@foreach (var item in Model)
{
    @Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}

JavaScript

function SelectAll() {       
        $('input[id^="ProductId_"]').each(function () {          
            $(this).prop('checked', true);
        });
    }

    function UnselectAll() {
        $('input[id^="ProductId_"]').each(function () {
            $(this).prop('checked', false);
        });
    }

 

 

This may help someone.

HTML5

 <input id="check_box" type="checkbox" onclick="handleOnClick()">

JavaScript.

  function handleOnClick(){

      if($("#check_box").prop('checked'))
      {        
          console.log("current state: checked");
      }
      else
      {         
          console.log("current state: unchecked");
      }    
 }

 

 


if($('jquery_selector').is(":checked")){
  //somecode
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 

Scroll to Top