Disable button if one radio is checked - javascript

I have three radio each one has name started with delivery_option and a submit button with css class continue. I want to test if a radio is checked the button must be enabled, otherwise it should be disabled.
i made the code below
$(document).ready(function() {
$('#checkout-delivery-step input:radio').each(function() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
});
});
but it does not work, what was the issue?

You are running the code only once. The code has to be run every time when the radio button is clicked or changed. So you need to use the following:
// Make this a function.
function checkProgress() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
}
$(function () {
// Set the status once the doc loads.
checkProgress();
// Set it again when any of the radio buttons are clicked.
$("input:radio[name*='delivery_option']").on("click change", checkProgress);
});
Snippet
// Make this a function.
function checkProgress() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
}
$(function () {
// Set the status once the doc loads.
checkProgress();
// Set it again when any of the radio buttons are clicked.
$("input:radio[name*='delivery_option']").on("click change", checkProgress);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Group 1</h3>
Option 1: <input type="radio" name="delivery_option_1" />
Option 2: <input type="radio" name="delivery_option_1" />
Option 3: <input type="radio" name="delivery_option_1" />
<h3>Group 2</h3>
Option 1: <input type="radio" name="delivery_option_2" />
Option 2: <input type="radio" name="delivery_option_2" />
Option 3: <input type="radio" name="delivery_option_2" />
<p>Submit?</p>
<input type="button" value="Submit" class="continue" disabled />

You can try something like this with removeAttr which will remove the attribute from any element which is already set.
Also, for the radio you can do this way, once it is clicked then you can enable the button because it doesn't provide a way to deselect it.
Finally, the name for elements can be the same if it is a group and only the id must be unique. Check here.
So, proper code will be
<label for="delivery_option1">Option1:</label><input type="radio" id="delivery_option1" name="delivery_option" />
<label for="delivery_option2">Option2:</label> <input type="radio" id="delivery_option2" name="delivery_option" />
<label for="delivery_option3">Option3:</label><input type="radio" id="delivery_option3" name="delivery_option" />
$(function(){
$("input:radio[name*='delivery_option']").click(function(){
$(".continue").removeAttr("disabled");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Option1: <input type="radio" name="delivery_option1" />
Option2: <input type="radio" name="delivery_option2" />
Option3: <input type="radio" name="delivery_option3" />
<input type="button" value="Submit" class="continue" disabled />

Related

Javascript Validation for Multichoice Checkboxes

I would like to create an alert that displays if none of the choices in my check box have been displayed.
<script>
function mFunction () {
if (!!this.form.checkbox.checked) {
alert('not checked');
return false;
}
};
</script>
js above
<body>
<form>
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction()">
</form>
I wanted an alert if nothing selected, and no alert if something is selected.
you can check this by
[...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked)
function mFunction (e)
{
if(![...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked))
{
alert('not checked');
e.preventDefault();
}
};
function checkForm(t,e) {
e.preventDefault();
console.log('checked');
};
<form onsubmit="checkForm(this,event);">
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction(event)">
</form>
You can directly check the checked items like below.
function mFunction () {
let matches = document.querySelectorAll('input[type=checkbox]:checked');
if (matches.length < 1) {
alert('not checked');
return false;
}
};
If its plain javascript, you can try adding an event listener when checkbox is clicked.
Maintain an array in the listener. If something is selected maintain a checkbox selection counter or boolean tracking selection.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener( 'change', function() {
if(this.checked) {
// Checkbox is checked..
} else {
// Checkbox is not checked..
}
});

If all three radio buttons are false, don't validate

I have three different blocks of code, with radio buttons.
The only thing that changes are id and the name of them.
What I need is: if all radio buttons are checked on the value="false" (the user choose to check all the "no"), the form won't be valid.
I'm currently using jQuery validation and all I got to have is that radio buttons are all required.
I tried with this code, but it's not working.
registerForm.validate({
rules: {
'data': {
required: {
depends: function() {
return $('.yesandno').is(':checked').val() === "false";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
EDIT:
In the end, I mixed Ele's code-reply with the jQuery validation plugin that it is used on the portal I'm working on.
This is the code:
submitHandler: function(form) {
$('#btn-register').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
return false;
} else {
form.submit();
}
});
}
You could use filter and check the length:
// this filter will only return radios that are checked and have a value of false
$('.yesandno').filter(function() {
return this.checked && this.value === "false";
}).length === 3;
With a jQuery selector you can accomplish that
$('.yesandno:checked[value="false"]').size() === 3
Look at this code snippet
$('button').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
console.log('All radionbuttos were checked to NO');
} else {
console.log('Either at least one Radionbutto is YES or a (YES/NO) radiobutton was not still checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data2" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data2" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data3" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data3" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<br>
<button>Click to see selected value!</button>
See? the condition is true when size === 3.
You can check at least one true value to pass your validation instead of checking all three radio buttons for false to fail validation. This will be helpful to scale your HTML radio options without having to change the JQuery code again and again for the length match for false options selection.
function passValidation(){
$('.yesandno').filter(function() {
return this.checked && this.value === "true";
}).length > 0;
}
Call passValidation() function during validation and if it returns true then there is at least one radio button with Yes option selected. And false from passValidation() means no Yes option is selected.

Javascript - unselect checkboxes, items mutually exclusive

I have a group of check boxes that are all part of one array. What I require is that if the first one is selected (I don't mind), then any of the others are unselected, and vice versa - if one of the bottom three options are selected, then I don't mind needs to be unselected.
The last three options can all be selected at the same time.
This Link is similar to what I am asking to do. Any help would be appreciated
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair">Au Pair</label>
</div>
</fieldset>
The code is exactly the same as the link you provided.
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair">Au Pair</label>
</div>
</fieldset>
And then:
// We cache all the inputs except `#field_1071_0` with `:not` pseudo-class
var $target = $('input:not(#field_1071_0)');
$('#field_1071_0').on('change', function () {
// if 'i don't mind' is selected.
if (this.checked) {
// remove the 'checked' attribute from the rest checkbox inputs.
$target.prop('checked', false);
}
});
$target.on('change', function () {
// if one of the bottom three options are selected
if (this.checked) {
// then I don't mind needs to be unselected
$('#field_1071_0').prop('checked', false);
}
});
Demo: https://jsfiddle.net/426qLkrn/4/
I cannot remember an in-house feature of JavaScript or jQuery that makes it possible to solve your problem. So, you have to solve it by your own.
You can add a data attribute to your checkboxes where you list all the checkboxes (as an id) which cannot be selected at the same time with the current checkbox, e.g.:
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind" data-exclude="['field_1072_1','field_1072_2','field_1072_3']" />
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter" data-exclude="['field_1071_0']" />
...
Then, you add, for example, an onchange event to each of the checkboxes. This event checks whether the checkbox has changed to checked or to unchecked. If it has changed to checked, you have to uncheck all checkboxes within the list:
document.getElementById("field_1071_0").onchange= function(e) {
if (this.checked) {
this.dataset.exclude.forEach(function (exc) {
document.getElementById(exc).checked = false;
});
}
};
Or, with jQuery:
$("#field_1071_0").change(function (e) {
if ($(this).prop("checked")) {
$(this).data('exclude').forEach(function (exc) {
$("#" + exc).prop("checked", false);
});
}
});
The good thing is: You can apply this function to each checkbox you want, e.g.:
$("input:checkbox").change(function (e) {
if ($(this).prop("checked")) {
$(this).data('exclude').forEach(function (exc) {
$("#" + exc).prop("checked", false);
});
}
});
Now, each checkbox has the desired behaviour. So, this solution is a general way to solve it.
Comment: If you do not have access to the HTML code, i.e., to the input fields to add some information like the data-attribute, you can add those information via jQuery/JavaScript too:
$("#field_1071_0").data("exclude", ['field_1072_1','field_1072_2','field_1072_3']);
$("#field_1072_1").data("exclude", ['field_1071_0']);
...
jquery prop method can be used to pragmatically check or unchecked a check box. is can be use to evaluate if a condition is true or false.
Hope this snippet will be useful
// if first check box is selected , then checkedremaining three
$("#field_1071_0").on('change', function() {
//$(this) is the check box with id field_1071_0
// checking if first checkbox is checked
if ($(this).is(":checked")) {
//opt2 is a common class for rest of the check boxes
// it will uncheck all other checkbox
$(".opt2").prop('checked', false)
}
})
//unchecking first checkbox when any of the rest check box is checked
$(".opt2").on('change', function() {
if ($(this).is(":checked")) {
$("#field_1071_0").prop('checked', false)
}
})
<!--Adding a class `opt2` to the last three checkboxes-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" class="opt2" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" class="opt2" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair" class="opt2">Au Pair</label>
</div>
</fieldset>

Cannot deselect radio button?

I have been attempting to allow radio buttons to be deselected using jQuery, but I am running into issues with the prop function. When this code runs, my conditional ($(e.currentTarget).prop('checked')) always evaluates to true.
Here is a fiddle which demonstrates my issue: Jsfiddle
FYI: I am using jQuery 1.8.2, and I cannot update it because it is a legacy project with many dependencies. Also, I MUST use radio buttons per the client's request.
Javascript:
$("input[name=optionMedia]").click(function(e) {
if ($(e.currentTarget).prop('checked')) {
$(e.currentTarget).prop('checked', false);
}
});
Html:
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
You can do it like this
$('input.bigSizeInput').mouseup(function() {
if ($(this).is(':checked')) {
setTimeout(function() {
$('input.bigSizeInput:checked').prop('checked', false);
}, 1)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1" />
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
This is because checked is a property. If its there it is true, if its not it is not true. Hence you either should switch to a checkbox or use
$("..").removeProp('checked')
Using checkbox to check/uncheck is better than radio button. But if you want to use radio button, you need to check if radio is checked, copy it using and remove checked attribute of copied element and then insert it after target radio. At the end remove original radio.
$(document).on("mousedown", "input[name=optionMedia]", function(e) {
if (this.checked)
$(this).clone().prop('checked', false).insertAfter(this).end().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

Checkbox to toggle all selection

I have this javascript code
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}
});
And I have this
<form action="" method="POST">
Toggle All :
<input type="checkbox" name="select-all" id="select-all" />
then at my table I have multiple checkbox
<input type="checkbox" name="checkbox-1" id="checkbox-1" value="1"> Select
<input type="checkbox" name="checkbox-2" id="checkbox-2" value="2"> Select
<input type="checkbox" name="checkbox-3" id="checkbox-3" value="3"> Select
<input type="checkbox" name="checkbox-4" id="checkbox-4" value="4"> Select
When I click on toggle all, it does not check checkbox-1 to checkbox-4
What went wrong in my javascript code.
Thanks!! I want to actually do a function that will send all the value of checkbox1-4 by post when they are checked on form submit.
Simply do like this.
$('#select-all').click(function(event) {
$(':checkbox').prop("checked", this.checked);
});
You do not need to loop through each checkbox to check all.
Demo
Wrap the code in dom ready if your script is in head tag
$(document).ready(function() {
$('#select-all').click(function(event) {
$(':checkbox').prop("checked", this.checked);
});
});

Categories