How can i change the value of checkbox upon change - javascript

I would like to change the value of the checkbox, but failed with the following code.
$("input:checkbox").on("change", function () {
if (this.checked == true) {
this.val("1");
}
else {
this.val("0");
}
});
I not sure why it is no responds without the code, which it should've the "checked" when I'm calling this element, but no. So i will need to add a value field manually.
<input class="c-switch-input" type="checkbox" name="pk_{{$d['id']}}" value="{{$d['status']}}">

You are mixing jQuery and DOM incorrectly
EITHER
this.value = "1";
OR
$(this).val("1")
But use a ternary:
$("input:checkbox").on("change", function () {
this.value = this.checked ? "1" : "0";
console.log(this.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" />

Related

button is not being enabled if checkbox is on

I want to enable button only if checkbox is on. What I am doing wrong here ? Thanks in advance..
index.html
<p><input id="agree" type="checkbox" /> I agree</p>
<input id="continue" value="continue" type="button" disabled="disabled" />
custom.js
$( document ).ready(function () {
$('#agree').change(function () {
var state = $(this).attr('value');
if (state == 'on') {
$('#continue').removeAttr('disabled')
} else if (state == '') {
$('#continue').attr('disabled','disabled');
}
});
});
You could simplify it to the following:
Example Here
$('#agree').on('change', function () {
$('#continue').attr('disabled', !this.checked);
});
$('#agree').on('change', function () {
$('#continue').attr('disabled', !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input id="agree" type="checkbox" />I agree</p>
<input id="continue" value="continue" type="button" disabled="disabled" />
The reason your code wasn't working was because you were using .attr(). Since there is no value attribute, you needed to use .prop(). This still wouldn't work though because the value will always return on. You need to get the checked property accessing this.checked or .prop('checked') - working example using your original snippet.
$('#agree').on('change', function () {
if (this.checked) {
$('#continue').removeAttr('disabled')
} else {
$('#continue').attr('disabled', 'disabled');
}
});
Try this:
$( document ).ready(function() {
$('#agree').change(function() {
if(this.checked) {
$('#continue').removeAttr('disabled')
} else {
$('#continue').attr('disabled','disabled');
}
});
});
If you want to check if input has checked :
state = $(this).prop( "checked" );
this returns boolean value (true if checked or false if unchecked).

Change variable value when checkbox is checked/unchecked

I was trying to change the value of an variable according to the status of an checkbox
here is my code sample
<script type="text/javascript">
if(document.getElementByType('checkbox').checked)
{
var a="checked";}
else{
var a="not checked";}
document.getElementById('result').innerHTML ='result '+a;
</script>
<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>
Can you please tell me whats the problem with this code.
Try this:
if (document.querySelector('input[type=checkbox]').checked) {
Demo here
Code suggestion:
<input type="checkbox" />Checkbox<br/>
<span id="result"></span>
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = input.checked ? "checked" : "not checked";
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
</script>
In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload function, to run the code after the page loaded.
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
try something like this
<script type="text/javascript">
function update_value(chk_bx){
if(chk_bx.checked)
{
var a="checked";}
else{
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
</script>
<input type="checkbox" value="1" onchange="update_value(this);"/>Checkbox<br/>
<span id="result"></span>
Too complicated. Inline code makes it cool.
<input type="checkbox" onclick="yourBooleanVariable=!yourBooleanVariable;">
For those who tried the previous options and still have a problem for any reason, you may go this way using the .prop() jquery function:
$(document.body).on('change','input[type=checkbox]',function(){
if ($(this).prop('checked') == 1){
alert('checked');
}else{
alert('unchecked');
}
This code will run only once and check initial checkbox state. You have to add event listener for onchange event.
window.onload = function() {
document.getElementByType('checkbox').onchange = function() {
if(document.getElementByType('checkbox').checked) {
var a="checked";
} else {
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
}

How could I change the buttonname and the variable value?

How could I write this in javascript or jQuery:
When I push the button the first time the onoff var in the change function gets the value off and the off button changes to a button named on;
now when I press the on button the var onoff gets the value on and the button changes to an off button again.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript">
function change( inputId ) {
/* ... do something with inputId ... */
var onoff = 'off';
console.log( onoff );
}
</script>
</head>
<body>
<form>
<table>
<tr>
<td>one:</td><td><input name="one" id="one" /></td>
<td><input type="button" id="b_one" value="off" onclick="change('one')"></td>
</tr>
<tr>
<td>two:</td><td><input name="two" id="two" /></td>
<td><input type="button" id="b_two" value="off" onclick="change('two')"></td>
</tr>
</table>
<br /><br /><input type="submit" value="ok"/></div><br />
</form>
</body>
</html>
This is in "pure" JavaScript. You will retrieve the button elements for given input and change its value based on the previous value.
function change( inputId ) {
var button = document.getElementById('b_' + inputId);
button.value = button.value === 'off' ? 'on' : 'off';
}
HERE is the code.
Your change() function won't work because 'off' is assigned to onoff variable everytime the function is called. You have to move the variable definition outside the change() function if you want to use it.
I'm not sure that's a valid use of value. However, something like this:
function Change(id) {
if( $("#"+id).val() == "on") {
// code for on
$("#"+id).val("off"); //switch value
}
else {
// code for off
$("#"+id).val("on"); //switch value
}
}
HTML
<input type="button" id="btnOn" value="Off" />
Javascript
var status = "off"
$("#btnOn").click(function () {
if ($(this).val() == "On") {
$(this).val("Off")
status = "Off";
}
else {
$(this).val("On")
status = "On";
}
alert("status : " + status);
});
Here is the sample : http://jsfiddle.net/JCABs
You can set event handlers without adding inline code:
$('input[type="button"]').on('click', function () {
var onoff = this.value;
//this sets the value of the input to its current opposite
this.value = (this.value == 'off') ? 'on' : 'off';
});
Here is a demo: http://jsfiddle.net/df4pu/
This also sets event handlers for every type=button input so you can reduce the repetitious code.
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Using JQuery to get the default value of a textarea, clearing onfocus and reinstating value on empty

I have some JQuery that isn't working and I need a little help. I a few forms on my website, and they all have a textarea with the class ".form-textarea". What I'm trying to do is use JQuery to get the default value of the textarea, clear the value on focus and reinstate the original value if the the textarea is empty. I realise that an ID would probably be better but I need a generic function to affect all of the textareas with this particular class.
$(document).ready(function()
{
var def = $(".form-textarea")
$(".form-textarea").focus(function(srcc)
{
if ($(this).val() == def)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val(def);
}
});
$(".defaultText").blur();
});
This is an old method I used for the exact same purpose. I believe this is what you're looking for (uses Textareas) : Live demo
This uses the jQuery data API. I've also added an extra class so you can markup your text nicely (disabled_text). This is a general purpose method so all you need to do is add the suggest class to your textarea/input and the script will do the rest
<textarea class='suggest'>Some default value</textarea>
<textarea class='suggest'>Some default value2</textarea>
<textarea class='suggest'>Some default value3</textarea>
<input type='text' value ='me too' class='suggest'>
$('.suggest').each(function() {
$this = $(this);
if ($this.val() != '') {
return;
}
$this.data('defaultval', $this.val());
$this.addClass('disabled_text').focus(function() {
if ($this.val() == $this.data('defaultval')) {
$this.val('');
}
$this.removeClass('disabled_text');
}).blur(function() {
var oldVal = ($this.data('defaultval')) ? $this.data('defaultval') : '';
if ($this.val() == '' && oldVal != '') {
$this.addClass('disabled_text').val(oldVal);
}
})
});
Here, give this a whirl and see if it does the trick.
<script>
$(document).ready(function(){
$default = "defaultText";
$(".form-textarea").focus(function(){
if( $(this).val() == $default ){
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function(){
if( $(this).val() == "" ){
$(this).addClass("defaultTextActive");
$(this).val($default);
}
});
});
</script>
<input class="form-textarea" type="text" value="defaultText" />
<input class="form-textarea" type="text" value="defaultText" />
I've just tried to remove the value "srcc" from the focus function and it works fine

Categories