Set attribute in checkbox on click - javascript

how can an HTML element/tag for example this:
<input type="checkbox" id="1234" checked onClick="replace(1234)"> I have a car<br>
replaced with this when clicked
<input type="checkbox" id="1234" unchecked onClick="replace(1234)"> I have a car<br>
I want to replace only the input tag and change HTML code in tha position
Thanks

$('#1234').click(function(){
if($(this).is(':checked')) {
$(this).attr('checked',true);
console.log('checked')
}
else {
$(this).attr('checked',false);
console.log('unchecked')
}
});
<!DOCTYPE html>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<input type="checkbox" id="1234" checked > I have a car<br>
</body>
</html>
Kindly check the above snippet. It might help.

This will check if the element has the attribute checked, if so then it will remove it and set a new attribute called unchecked
function replace(id) {
var attr = $("#" + id).attr('checked');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
$("#" + id).removeAttr('checked').attr("unchecked", "")
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="1234" checked onClick="replace(1234)"> I have a car<br>

You can directly call checkbox click event as shown in below code
$(document).on("click", "input[name='chk']", function() {
//alert(this.id);
debugger;
var ischecked2 = $(this).is(':checked');
if (ischecked2) { //checked
console.log("checked");
} else { //unchecked
console.log("unchecked");
}
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js">
</script>
<input type="checkbox" id="1234" name="chk"> I have a car<br>

Use following code. It will help you:
$('#1234').click(function(){
if($(this).is(':checked'))
$(this).attr('checked',true);
else
$(this).removeAttr('checked');
});

Related

How to know if a checkbox is checked onmouseover corresponding label

I want to perform certain actions when hovering over checkbox-labels, but only when the checkboxes are checked.
How can I retrieve that information?
HTML
<input clrcheckbox="" type="checkbox" id="checks">
<label for="checks">Check</label>
JS
document.querySelector('label').onmouseover = () => {
//so here should be something like:
//if(checkbox is checked) {console.log('checked')}
console.log('over');
}
Here a solution with jQuery
<input clrcheckbox="" type="checkbox" id="checks">
<label for="checks">Check</label>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script>
$(document).ready(function(){
var isChecked = function(){
if ($('#checks').filter(':checked').length > 0){
console.log('Do some action')
}
}
$('#checks').mouseover(isChecked)
$('label').mouseover(isChecked)
})
</script>
https://codesandbox.io/s/strange-sunset-nkq5q

Show div when radio button selected

I am novice in javascript and jQuery.
In my html have 2 radio buttons and one div. I want to show that div if I check the first radio-button but otherwise I want it to be hidden
so: If radio button #watch-me is checked --> div #show-me is visible.
If radio button #watch-me is unchecked (neither are checked or the second is checked) --> div #show-me is hidden.
Here is what I have so far.
<form id='form-id'>
<input id='watch-me' name='test' type='radio' /> Show Div<br />
<input name='test' type='radio' /><br />
<input name='test' type='radio' />
</form>
<div id='show-me' style='display:none'>Hello</div>
and JS:
$(document).ready(function () {
$("#watch-me").click(function() {
$("#show-me:hidden").show('slow');
});
$("#watch-me").click(function(){
if($('watch-me').prop('checked')===false) {
$('#show-me').hide();}
});
});
How should I change my script to achieve that?
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
Input elements should have value attributes. Add them and use this:
$("input[name='test']").click(function () {
$('#show-me').css('display', ($(this).val() === 'a') ? 'block':'none');
});
jsFiddle example
$('input[name=test]').click(function () {
if (this.id == "watch-me") {
$("#show-me").show('slow');
} else {
$("#show-me").hide('slow');
}
});
http://jsfiddle.net/2SsAk/2/
$('input[type="radio"]').change(function(){
if($("input[name='group']:checked")){
$(div).show();
}
});
var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});
JSFIDDLE

unable to verify preselected radio button

I have a form which contains data that will be dynamically added to my form. Once the data has been added, I would like to verify the value (specifically if a radio button has been checked) of a radio button and then do different things based on which radio button is checked.
Currently, I am unable to do so as no matter the state of the radio button (i.e checked OR unchecked) I am always getting the alert ("Button is no checked").
Code:
<!DOTYPE HTML>
<html>
<head>
<link type='text/css' rel='stylesheet' href='style.css'>
<!--jQuery Validation-->
<!--Loads JQuery and JQuery validate plugin-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type='text/javascript'>
$(document).ready(function ()
{
function checkradio(radio)
{
if (radio.checked)
{
alert("no is checked");
}
else
{
alert("no is not checked");
}
}
function radiocheck()
{
checkradio($('#no'));
}
$('#submit1').click(function ()
{
radiocheck();
})
});
</script>
</head>
<body>
<input type='radio' id='yes' name='radiobutton' value='yes'>yes
<input type='radio' checked='checked' id='no' name='radiobutton' value='no'>no
<input type='button' id='submit1' name='submit' value='submit'>
</body>
</html>
You are trying to use native DOM element checked property on a jQuery object.
Can use:
if(radio.is(':checked'));
Or pass the native DOM element to checkradio() rather than the jQuery object
checkradio($('#no')[0]);
function checkradio(radio){
if(radio.prop('checked'))
{
alert("no is checked");
}
else
{
alert("no is not checked");
}
}
OR
$('#submit1').click(function(){
if($('#no').prop('checked')){
alert("is checked");
}else{
alert("is not checked");
}
})
try this
checkradio($("input:radio[name=radiobutton]"));
change your code like
checkradio($("input[name='radiobutton']")); //This will give all radio buttons with name "radiobutton"
and in if()
add radio.is(':checked')
FIDDLE

Select All checkboxes using jQuery

I have the following html code:
<input type="checkbox" id="ckbCheckAll" />
<p id="checkBoxes">
<input type="checkbox" class="checkBoxClass" id="Checkbox1" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox2" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox3" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox4" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox5" />
<br />
</p>
When user checks ckbCheckAll all checkboxes must be checked. Also I have following jquery code:
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").attr('checked', this.checked);
});
});
When I see my page in the browser I get the following result:
In the first click on ckbCheckAll all checkboxes were checked (which is correct). In the second click on ckbCheckAll all checkboxes were unchecked (which is correct). But in 3rd attempt nothing happened! also in 4th attempt nothing happened and so on.
Where is the problem?
Use prop
$(".checkBoxClass").prop('checked', true);
or to uncheck:
$(".checkBoxClass").prop('checked', false);
http://jsfiddle.net/sVQwA/
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
Updated JSFiddle Link: http://jsfiddle.net/sVQwA/1/
Here is a simple way to do this :
Html :
<input type="checkbox" id="selectall" class="css-checkbox " name="selectall"/>Selectall<br>
<input type="checkbox" class="checkboxall" value="checkbox1"/>checkbox1<br>
<input type="checkbox" class="checkboxall" value="checkbox2"/>checkbox2<br>
<input type="checkbox" class="checkboxall" value="checkbox3"/>checkbox3<br>
jquery :
$(document).ready(function(){
$("#selectall").click(function(){
if(this.checked){
$('.checkboxall').each(function(){
$(".checkboxall").prop('checked', true);
})
}else{
$('.checkboxall').each(function(){
$(".checkboxall").prop('checked', false);
})
}
});
});
Use below code..
$('#globalCheckbox').click(function(){
if($(this).prop("checked")) {
$(".checkBox").prop("checked", true);
} else {
$(".checkBox").prop("checked", false);
}
});
$('.checkBox').click(function(){
if($(".checkBox").length == $(".checkBox:checked").length) {
//if the length is same then untick
$("#globalCheckbox").prop("checked", false);
}else {
//vise versa
$("#globalCheckbox").prop("checked", true);
}
});
Try the following simple code:
$('input[type=checkbox]').each(function() { this.checked = true; });
Source: How to reset all checkboxes using jQuery or pure JS?
use this
if (this.checked)
$(".checkBoxClass").attr('checked', "checked");
else
$(".checkBoxClass").removeAttr('checked');
also you can use prop please check http://api.jquery.com/prop/
I have seen many answers to this question and found some answer is lengthy and some answer is a little bit wrong. I have created my own code by using the above IDs and class.
$('#ckbCheckAll').click(function(){
if($(this).prop("checked")) {
$(".checkBoxClass").prop("checked", true);
} else {
$(".checkBoxClass").prop("checked", false);
}
});
$('.checkBoxClass').click(function(){
if($(".checkBoxClass").length == $(".checkBoxClass:checked").length) {
$("#ckbCheckAll").prop("checked", true);
}else {
$("#ckbCheckAll").prop("checked", false);
}
});
In the above code, where user clicks on select all checkbox and all checkbox will be selected and vice versa and second code will work when the user selects checkbox one by one then select all checkbox will be checked or unchecked according to a number of checkboxes checked.
$(document).ready(function() {
$('#ckbCheckAll').click(function() {
$('.checkBoxClass').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
OR
$(function () {
$('#ckbCheckAll').toggle(
function() {
$('.checkBoxClass').prop('checked', true);
},
function() {
$('.checkBoxClass').prop('checked', false);
}
);
});
Try this
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$("#checkBoxes input").prop('checked', $(this).prop('checked'));
});
});
That should do it :)
$(document).ready(function(){
$('#ckbCheckAll').click(function(event) {
if($(this).is(":checked")) {
$('.checkBoxClass').each(function(){
$(this).prop("checked",true);
});
}
else{
$('.checkBoxClass').each(function(){
$(this).prop("checked",false);
});
}
});
});
Use prop() instead -
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").each(function(){
if($(this).prop("checked", true)) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
});
});
BUT I like #dmk's much more compact answer and +1'd it
$(document).ready(function () {
$(".class").on('click', function () {
$(".checkbox).prop('checked', true);
});
});
Let i have the following checkboxes
<input type="checkbox" name="vehicle" value="select All" id="chk_selall">Select ALL<br>
<input type="checkbox" name="vehicle" value="Bike" id="chk_byk">bike<br>
<input type="checkbox" name="vehicle" value="Car" id="chk_car">car
<input type="checkbox" name="vehicle" value="Bike" id="chk_bus">Bus<br>
<input type="checkbox" name="vehicle" value="scooty" id="chk_scooty">scooty
Here is the simple code to select all and diselect all when the selectall check box will click
<script type="text/javascript">
$(document).ready(function () {
$("#chk_selall").on("click", function () {
$("#chk_byk").prop("checked", true);
$("#chk_car").prop("checked", true);
$("#chk_bus").prop("checked", true);
$("#chk_scooty").prop("checked", true);
})
$("#chk_selall").on("click", function () {
if (!$(this).prop("checked"))
{
$("#chk_byk").prop("checked", false);
$("#chk_car").prop("checked", false);
$("#chk_bus").prop("checked", false);
$("#chk_scooty").prop("checked", false);
}
});
});
</script>
checkall is the id of allcheck box and cb-child is the name of each checkboxes that will be checked and unchecked depend on checkall click event
$("#checkall").click(function () {
if(this.checked){
$("input[name='cb-child']").each(function (i, el) {
el.setAttribute("checked", "checked");
el.checked = true;
el.parentElement.className = "checked";
});
}else{
$("input[name='cb-child']").each(function (i, el) {
el.removeAttribute("checked");
el.parentElement.className = "";
});
}
});
jQuery( function($){
// add multiple select / deselect functionality
$("#contact_select_all").click(function () {
if($("#contact_select_all").is(":checked")){
$('.noborder').prop('checked',true);
}else
$('.noborder').prop('checked',false);
});
// if all checkbox are selected, check the selectall checkbox
$(".noborder").click(function(){
if($(".noborder").length == $(".noborder:checked").length) {
$("#contact_select_all").attr("checked", "checked");
} else {
$("#contact_select_all").removeAttr("checked");
}
});
});
I know its too late, but I'm posting this for the upcoming developers.
For select all checkbox we need to check three conditions,
1. on click select all checkbox every checkbox should get selected
2. if all selected then on click select all checkbox, every checkbox should get deselected
3. if we deselect or select any of the checkbox the select all checkbox also should change.
with these three things we'll get a good result.for this you can approach this link https://qawall.in/2020/05/30/select-all-or-deselect-all-checkbox-using-jquery/
I got my solution from here, they have provided solution with examples.
<table>
<tr>
<th><input type="checkbox" id="select_all"/> Select all</th>
</tr>
<tr>
<td><input type="checkbox" class="check" value="1"/> Check 1</td>
<td><input type="checkbox" class="check" value="2"/> Check 2</td>
<td><input type="checkbox" class="check" value="3"/> Check 3</td>
<td><input type="checkbox" class="check" value="4"/> Check 4</td>
<td><input type="checkbox" class="check" value="5"/> Check 5</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.check').each(function(){
this.checked = true;
});
}else{
$('.check').each(function(){
this.checked = false;
});
}
});
$('.check').on('click',function(){
if($('.check:checked').length == $('.check').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
hope this will help anyone ...:)
Add jquery-2.1.0.min.js file
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
Write the codes given below:
<script>
$(document).ready(function () {
$("#checkAll").change(function() {
var checked = $(this).is(':checked'); // Get Checkbox state
if (this.checked) //If true then checked all checkboxes
$(".classofyourallcheckbox").prop('checked', true);
else
$(".classofyourallcheckbox").prop('checked', false); //or uncheck all textboxes
});
});
</script>

hiding div based on unchecking checkboxes

I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox

Categories