How to change the value of a check box onClick using JQuery?

折月煮酒 提交于 2019-12-30 06:17:07

问题


Here I am trying to change the value of the following check box while clicking on it. In the code below I tried to change the value of the checkbox to 1 and change the value to 0 when unchecked. But it takes only the false condition, when the checkbox is unchecked the value changes to 0 but when checked its not changing to 1. Any suggestions how to fix this out ?

<input type="checkbox" id="read" name="permission[]" onClick="($(this).checked)?$(this).attr('value',1):$(this).attr('value',0)"/>

回答1:


I don't really understand why you would want to do this (the checkbox's value won't be submitted anyways when it's unchecked).

The checked property on the DOM element will always tell you whether it is checked or not. So you can either get this.checked (Javascript DOM) or $(this).prop('checked') (jQuery wrapper).

If you really need to, you should do this:

onclick="$(this).attr('value', this.checked ? 1 : 0)"

or even

onclick="$(this).val(this.checked ? 1 : 0)"

or even better, don't use inline event handlers (like onclick), but use jQuery's event handling wrappers (.on('click') or .click() in older versions).

jsFiddle Demo with jQuery event handling


The problem with your approach

You are using $(this).checked to get the state of your checkbox. The jQuery object (the one that's returned by the $ function) does not have a checked property, so it will be undefined. In Javascript, undefined is a falsy value, that's why your checkbox's value is always 0.




回答2:


You can use this simple click function to achieve it.

HTML:

<input type="checkbox" id="read" name="permission[]" value="0"/>

Jquery:

$("#read").click(function() {

		if($("#read").val()==0)
		{
		 $("#read").val(1);
		}
		else
		{
		 $("#read").val(0);
		}
		alert($("#read").val());
		
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="read" name="permission[]" value="0"/> 
Click the check box to toggle the value 0 and 1



回答3:


// o = object
function get(o) { 

  ( $(o).val() == 0 ) ? $(o).val(1) : $(o).val(0);
    
  // alert( $(o).val() );
    
  console.log( $(o).val() );
		
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="permission[]" onClick="get(this)" value="0"/>


来源:https://stackoverflow.com/questions/9140633/how-to-change-the-value-of-a-check-box-onclick-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!