Given a checkbox object output its value - javascript

I have a page that has a number of checkboxes in it. I would like to write a function that will be called when the ckeckbox is clicked, that determines if the checkbox is checked or not.
<input type="checkbox" onclick="toggleVis('id', this);"/> ID
<input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit
<input type="checkbox" onclick="toggleVis('last', this);"/> Last
Note some checkboxes start checked.
I figured that there must be a way to do this based on a reference passed, so I passed the this value as a parameter.
function toggleVis(name, checkbox)
{
//if(checkbox.checked())
console.log('checked');
if($('.'+name).css('display') != "none")
$('.'+name).css('display', 'none');
else
$('.'+name).css('display', 'table-cell');
}
I am open to use jQuery.

You were close.
if(checkbox.checked) {
console.log('checked');
//...
}
There's no checked() method, but there is a checked property. Note that your code may only work on clicks. Perhaps onchange would be better?

Look at the checkboxobj.checked property (instead of calling it like a function). In your case, you could reference if (checkbox.checked) { ... }. More information can be found on this website

If you wanted to do this with jQuery you might try the following. Note that I'm binding to the checkbox instead of including the 'onclick' or 'onchange' directly on the HTML element.
$('[type=checkbox]').click(function(){
if( $(this).attr('checked') ){
console.log('checked');
if($('.'+$(this).attr('name')).css('display') != "none") {
$('.'+$(this).attr('name')).css('display', 'none');
} else {
$('.'+$(this).attr('name')).css('display', 'table-cell');
}
}
});

And a JQuery-based solution:
var checked = $(checkbox).is(':checked');
Helpful if you want to find the checkbox first by some JQ selector.

<input type="checkbox" class="checkthis"> ID
<input type="checkbox" class="checkthis" checked="checked"> Edit
<input type="checkbox" class="checkthis"> Last
$(input.checkthis).click(function() {
if($(this).is(':checked') {
// do checked stuuf
} else {
// do not checked stuff
}
});

Related

If input has value and radio button is checked remove disabled class from anchor tag

I'm trying to achieve condition, when input has value greater than 1 and radio button is checked then remove disabled class from the anchor.
This is my code
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
$("input").keyup(function () {
if ($("#age").val().length > 1 && $('input[name=education]:checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
It is triggering after input has value without checking radio is checked.
Can anyone help me with this?
Thanks in advance.
Using :checked is fine. But it doesn't return a boolean. You need to check that it returns an element. $(':prop').length > 0 (or using prop('checked')).
Some other stuff you need to change.
The condition should not be on the $("#age").val().length but on the $("#age").val() itself.
Use checkbox, not radiobutton. radiobutton is used to choose one option from others, not to set true/false.
You need to check the values on input keyup, but also on change of the radio (or checkbox).
Try this:
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education']").is(':checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
Use prop('checked') to check radio, refer code below,
$( document ).ready(function() {
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education'][value='univeristy']").prop("checked")) {
$("#diploma").removeClass("disabled");
console.log("Removed class 'disabled'");
} else {
$("#diploma").addClass("disabled");
console.log("Added class 'disabled'");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
</body>
Run this code and see console log.

jQuery - How to removeProp on checkbox change?

I have checkbox that I'm using to toggle whether an input field is "required" using jQuery. This is part of Foundation Abide validation. So, at the end of the input field it needs to add/remove the word "required".
The box is checked by default. When the user unchecks the box it adds "required" to the input as it should (else if). However, if you recheck the box, the "removeProp" doesn't remove "required". What am I doing wrong on this? I've tried both prop and attr functions with the same result.
<input type="checkbox" id="billing" checked>
<input type="text" id="b_name" pattern="alpha" required>
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').removeProp('required');
}
else if (!$(this).is(':checked')) {
$('#b_name').prop('required', true);
}
});
Try this:
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').prop('required', false);
}
else {
$('#b_name').prop('required', true);
}
});
You can clearly see the behavior there. Once it removes the property it is not adding the property back.
You can see the same case mentioned at Jquery docs for .removeProp().
As it says -
Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
So you can set it to false and true on check and uncheck rather than removing the property completly
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').prop('required', false);
}
else if (!$(this).is(':checked')) {
$('#b_name').prop('required', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="billing" checked>
<input type="text" id="b_name" pattern="alpha" required>

jquery not registering one of my radio buttons as selected

I have a radio button selection that jquery is able to loop through them and read the values for each one just fine, but jquery can only detect when one of them has been selected. When selecting the other one, jquery just ignores it and tells me none have been selected.
jquery:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = false;
}
});
html:
<input type="radio" id="upload" name="banner_type" value="upload" />
<input type="radio" id="html" name="banner_type" value="html" />
"upload" is being ignored by jquery, "html" is not
Im doing it this way:
valid=false;
$('[name="banner_type"]').each(function() {
if($(this).is(':checked'))
valid = $(this).val();
});
So each time You check for radio being checked, valid value is renewed.
here's fiddle for You. Function "check" checks validity, returning false if none is selected.
http://jsfiddle.net/CLaDG/
The else part is setting value for valid but not returning it. Also the value is always false for second radio button. Try this:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = $(this).val();
return valid;
}
});
This can be written shorter and better but right now I am just fixing the issue I see.
not sure which version of jQuery you are on, but try using jQuery.prop as well as delegated event on the container might be cleaner, such as:
$('.your-radios-container').on('change','[name="banner_type"]',function(){
valid = $(this).prop('checked');
});
I have forked your fiddle to show you how it could work:
http://jsfiddle.net/AcMBR/2/

Finding whether checkbox is checked or not using jquery

I am new to jquery. I have below the code to find out whether the check box is checked or not. But though the check box is checked it always goes to else block in below the code:
if ($('#someId').is(':checked')) {
alert("checked");
} else {
alert("unchecked");
}
Html code:
By default the check box is not checked. The code is as below.
<td>
select :<br><input type="checkbox" id="someId" name="someId" value="">
</td>
Am I doing anything wrong here? Thanks!
try this:
select :<input type="checkbox" id="someId" name="someId" value="" checked />
<input id="btnSubmit" type="button" value="Submit"/>
$("#btnSubmit").on("click",function(){
if ($("#someId").is(':checked')) {
alert("checked");
} else {
alert("unchecked");
}
});
working fiddle here: http://jsfiddle.net/tLebs/1/
i hope it helps.
Skip jQuery's methods for this if you're only dealing with one checkbox: the DOM checked property is as easy as it could possibly be. jQuery only confuses the issue. Feel free to use jQuery to get hold of the element though.
var isChecked = $("#someId")[0].checked;
I am throwing out a guess that you need a doc ready function
$( document ).ready(function() {
$("#someId").on("click",function(){
if ($(this).is(':checked')) {
alert("checked");
} else {
alert("unchecked");
}
});
});`
see http://learn.jquery.com/using-jquery-core/document-ready/
if ($("#Your_CheckBox").is(':checked')) {
}

Checkbox Check Event Listener

Recently I have been working with the Chrome Plugin API and I am looking to develop a plugin which will make life easier for me for managing a website.
Now what I wish to do is to fire an event when a certain checkbox is checked.
As this website does not belong to me I cannot change the code therefore I am using the Chrome API. One of the main problems is that rather than there being an ID, there is a Name. I was wondering if I could fire the function once the certain checkbox with the 'name' is checked.
Short answer: Use the change event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Single checkbox
Using querySelector.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
<input type="checkbox" name="checkbox" />
Single checkbox with jQuery
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
Multiple checkboxes
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
Multiple checkboxes with jQuery
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
Since I don't see the jQuery tag in the OP, here is a javascript only option :
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});

Categories