Value of Sum not changed after unchecked Checkbox Button - javascript

Im looking solution for this problem.
I have 3 input number that will sum all of that and display it to input4.
All my code is working fine but only when I unchecked the checkbox, the value of sum didn't update.
Scenario example:
Checked on first checkbox and enter value of 1
Checked on second checkbox and enter value of 1. This will trigger the display value and will show result=2
Unchecked the first checkbox will clear the first input value, but the result display not update(still result=2.. Should be result=1)
Html:
<input type="checkbox" id="chkbxcasting" />
<input type="number" id="casting1" name="casting1" value="0" disabled onchange="valChange(this);" onkeyup="sum1();" /><br>
<input type="checkbox" id="chkbxdeburring" />
<input type="number" id="deburring1" name="deburring1" value="0" disabled onchange="valChange(this);" onkeyup="sum1();" /><br>
<input type="checkbox" id="chkbxecoat" />
<input type="number" id="ecoat1" name="ecoat1" value="0" disabled onchange="valChange(this);" onkeyup="sum1();" /><br><br>
<input class="invisibleinput" type="number" id="totalaffectqty" name="totalaffectqty" readonly />
CSS
input[value="0"] { color: #fff; }
Javascript + JQuery
function valChange(obj){
if(obj.value=="0"){
obj.style.color="#fff"
} else{
obj.style.color="#000"
}
}
$(document).ready(function() {
$('#chkbxcasting').on('change', function() {
$("#casting1").prop("disabled", !$(this).is(':checked'));
$("#casting1").val('');
});
$('#chkbxdeburring').on('change', function() {
$("#deburring1").prop("disabled", !$(this).is(':checked'));
$("#deburring1").val('');
});
$('#chkbxecoat').on('change', function() {
$("#ecoat1").prop("disabled", !$(this).is(':checked'));
$("#ecoat1").val('');
});
});
function sum1() {
let casting1 = +(document.getElementById('casting1').value);
let deburring1 = +(document.getElementById('deburring1').value);
let ecoat1 = +(document.getElementById('ecoat1').value);
let result1 = casting1 + deburring1 + ecoat1;
if (!isNaN(result1)) {
document.getElementById('totalaffectqty').value = result1;
}
else {
document.getElementById('totalaffectqty').value = '0';
}
}
This is the demo:
Demo Here
Thank You in Advance

Working Demo - https://jsfiddle.net/disingh123/szmt8rv2/3/
<input type="checkbox" id="chkbxcasting" />
<input type="number" id="casting1" name="casting1" value="0" disabled /><br>
<input type="checkbox" id="chkbxdeburring" />
<input type="number" id="deburring1" name="deburring1" value="0" disabled /><br>
<input type="checkbox" id="chkbxecoat" />
<input type="number" id="ecoat1" name="ecoat1" value="0" disabled /><br><br>
<input class="invisibleinput" type="number" id="totalaffectqty" name="totalaffectqty" readonly />
$(document).ready(function () {
$('body').on('change', function (event) {
const { target: { type } } = event
if (type === 'checkbox') {
const jQueryFiedTarget = $(event.target)
const isChecked = jQueryFiedTarget.is(':checked')
const associatedTextField = jQueryFiedTarget.next()
associatedTextField.prop("disabled", !isChecked);
associatedTextField.val(isChecked ? '' : '0')
if (!isChecked) {
sum1()
}
}
})
$('body').on('keyup', function (event) {
const { target: { type } } = event
if (type === 'number') {
sum1()
}
})
});
function sum1() {
const casting1 = +(document.getElementById('casting1').value);
const deburring1 = +(document.getElementById('deburring1').value);
const ecoat1 = +(document.getElementById('ecoat1').value);
const result1 = casting1 + deburring1 + ecoat1;
document.getElementById('totalaffectqty').value = isNaN(result1) ? '0' : result1
}

Related

Condition: input:checked with the same class

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

How to disable submit button for multiple inputs (jQuery Homework) [duplicate]

This question already has answers here:
Disabling submit button until all fields have values
(11 answers)
Closed 1 year ago.
I'm trying to setup a jQuery function to keep a submit button disabled until all the fields are filled. I got to a point when I can get it to work with 1 field filled. I've tried to change my call statement various ways I can think of, but I've locked myself to only one field... so I'm obviously missing something... I'm still very new to javascript so I'd appreciate some simple basic help. Thanks
My jQuery:
$(document).ready(function () {
$("#valueInput").on("input", function () { // << only for one field
if ($(this).val() != "") {
$("#addCarToGarage").prop("disabled", false);
} else {
$("#addCarToGarage").prop("disabled", true);
}
});
});
My HTML:
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">
You can try following code.
Instead of using id of last input, following approach can be better
$(document).ready(function () {
$('form > input').keyup(function() {
var empty_inputs = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty_inputs = true;
}
});
if (empty_inputs) {
$('#addCarToGarage').attr('disabled', 'disabled');
} else {
$('#addCarToGarage').removeAttr('disabled');
}
});
});
Try something like that
$(document).ready(function () {
let areAllValid = false;
const fields$ = jQuery('input[type="text"], input[type="number"]');
function checkValues() {
areAllValid = true;
for(const field of fields$) {
if(!$(field).val()) {
areAllValid = false
}
}
}
$("input").on("input", function () {
checkValues()
$("#addCarToGarage").prop("disabled", !areAllValid);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">

Javascript textbox either 1 can be entered

I had 2 textbox, but only 1 can be enter and cannot enter both fields. For example if I enter value in input1, input2 is disable. if both value is 0 both field disable to false.
Any help here?
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
function myFunction() {
if (input1 != 0 && input2 == 0){
document.getElementById("input2").disabled = true;
//ALERT(1);
}else if(input1 == 0 && input2 != 0){
//ALERT(2);
document.getElementById("input1").disabled = true;
}else if(input1 == 0 && input2 == 0){
//ALERT(3);
document.getElementById("input1").disabled = false;
document.getElementById("input2").disabled = false;
}
}
<input id="input1" style="width: 100px;" type="number" min="0" value="0.00" onchange="myFunction()"/>
<input id="input2" style="width: 100px;" type="number" min="0" value="0.00" onchange="myFunction()"/>
You can use the blur event, which fires when an element has lost focus.
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
function myFunction() {
input1.addEventListener("blur", event => {
let value = event.target.value;
input2.disabled = !!value && value != 0;
});
input2.addEventListener("blur", event => {
let value = event.target.value;
input1.disabled = !!value && value != 0;
});
}
<input id="input1" style="width: 100px;" type="number" min="0" value="0.00" onchange="myFunction()" />
<input id="input2" style="width: 100px;" type="number" min="0" value="0.00" onchange="myFunction()" />
Consider the following code example.
$(function() {
function isEmpty(fObj) {
console.log($(fObj).val());
return ($(fObj).val() == "" ? true : false);
}
$(".form").on("change blur", "input", function() {
if (!isEmpty(this)) {
$(".form input").not(this).prop("disabled", true);
}
if ($(this).val() == "0") {
$(".form input").prop("disabled", false);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form">
<input id="input1" style="width: 100px;" type="number" min="0" value="0.00" />
<input id="input2" style="width: 100px;" type="number" min="0" value="0.00" />
</div>
You can use change or blur callbacks and examine the target (this) of the event.

Uncheck all checkboxes if "Other" checkbox is checked and get value

So, I have 4 checkboxes:
Heating
AC
Cold Chain
Others
The condition is, you can multiple check the three: Heating, AC, and Cold Chain. But when you check on "Other", the three will be unchecked. And when you check again on any of the three, the Other checkbox will be unchecked.
When the Others is checked, a "Please specify" input text will appear.
And in the summary, Looking for solutions in Others - [value]
This is my fiddle
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];                
CountSelectedCB.length = 0;        
$("input:checkbox").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedCB.push($(this).attr("value"));            
}        
});                
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}   
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Made a simple example for you how you can do this using the prop() and siblings() functions.
Added some classes for better selectors.
$('#wrapper .some-checkbox').on('change', function() {
var $this = $(this);
if ($this.prop('checked')) {
if ($this.is('.some-others')) {
$this.siblings().prop('checked', false);
}
else {
$this.siblings('.some-others').prop('checked', false);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<input class="some-checkbox" type="checkbox" value="Heating">Heating<br>
<input class="some-checkbox" type="checkbox" value="Ac">AC<br>
<input class="some-checkbox" type="checkbox" value="Cold Chain">Cold Chain<br>
<input class="some-checkbox some-others" type="checkbox" value="Others">Others<br>
</div>
You need to check if the checkbox Others is checked, then uncheck the other checkboxes with $('<your-checkbox->').prop('checked', false);
For example:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        
        CountSelectedCB.length = 0;
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("value"));
if ($(this).attr("value") === "Others") {
CountSelectedCB = []; // reset result
$("input:checkbox").each(function() {
if ($(this).attr("value") !== "Others") {
$(this).prop('checked', false); // uncheck
}
});
$('input[name=solutions]').hide(); // toggle input
$('input[name=specify]').show(); // toggle input
}
            }
        });
        
        $('input[name=solutions]').val(CountSelectedCB).blur();
    });
}    
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox(){    
    $("input:radio").change(function() {          
        selectedRB = [];
        notSelectedRB = [];
        
        CountSelectedRB.length = 0;
        $("input:radio").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedRB.push($(this).attr("value"));
            }
        });
        
        $('input[name=existing]').val(CountSelectedRB).blur(); 
    });
}
$('#solutions, #existing').bind('keyup blur', function() {
        
    $('#summary').val('You are looking for solutions in ' + 
                             $('#solutions').val() + 
                             (' \n') +
                             'Are you using an existing customer? ' + 
                             $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" placeholder="Please specify" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br>
Summary:<br>
<textarea type='text' id="summary"></textarea>
Well, I modified your displayCheckbox() function. Please try like this. I think your problem will be solved.
function displayCheckbox(){    
$("input:checkbox").change(function() {
selectedCB = [];
notSelectedCB = [];
CountSelectedCB.length = 0;
if($('input:checkbox[value="Others"]').is(":checked")){
$('input:checkbox').not(this).prop('checked', false);
CountSelectedCB.length = 0;
CountSelectedCB.push($(this).attr("value"));
}else{
$("input:checkbox").each(function() {
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}
$('input[name=solutions]').val(CountSelectedCB).blur();
});
}
Thank you.
  
I've updated your Fiddle code. Please see this, it will solve your problem.
Here is the snippet:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];
selectedValue = $(this).attr("value");                
CountSelectedCB.length = 0;
if (selectedValue === "Others" && $(this).is(":checked")) {
uncheckAllCheckBox();
$(this).prop('checked', true);
CountSelectedCB.push(selectedValue);
} else {
$("input:checkbox").each(function() {
if ($(this).attr("value") === "Others")
$(this).prop('checked', false);
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}                        
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}
function uncheckAllCheckBox() {
$("input:checkbox").each(function() {
$(this).prop('checked', false);
CountSelectedCB.length = 0;
});
}
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Updated JSFiddle Code

If I check 2 input radio the disabled Submit button enables, but if I uncheck them...the Submit button doesn't disable back

I just need a little help with this code.
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function() {
$('input.class_x').on('click', markIt3);
});
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
My request is the following:
can anybody just FIX what is missing in order for the form Submit button to go back to be disabled as it is supposed to be, because this form only enables it when 2 input type radio have been checked?
This form previous description is the main idea of everything:
A form, with several input type radios. Check at least 2 and the Submit button enables. But if you uncheck any of them, the Submit button should disable back, but I cannot manage to achieve this PART.
I just need a little HELP with IT, nothing else.
Please, DON'T change my code too much!Can it be done?
Check the fiddle right here: https://jsfiddle.net/Suiberu/70tkgk5t/13/
Thanks!
Actually problem is deselecting radio button not detected as a change. How about this
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
checkIfValid();
};
$(function() {
$('input.class_x').on('click', markIt3);
});
function checkIfValid() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
};
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="radio" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="radio" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="radio" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required/>
</form>
Or you can change the type of your inputs to checkBoxes and it will simply do the magic.
Here is the JSFiddle link.
var prv3;
var markIt3 = function (e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function () {
$('input.class_x').on('click', markIt3);
});
$('input[type=checkbox]').on('change', function () {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled=true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="checkbox" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="checkbox" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="checkbox" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required />
</form>
Only the type has been changed from radio button to checkbox.
this.checked = false
..does not fire the change event, so the change code doesn't get fired when a radio button is unchecked.
Add the following line of code after that line:
$(this).change();
That will fire the change code.
Try using .prop() function instead
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var $sbmtBtn = $('#SubmitButton');
$sbmtBtn.prop('disabled', true);
if (current.length > 1) {
$sbmtBtn.prop('disabled', false);
} else {
$sbmtBtn.prop('disabled', true);
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" class="class_x">
<input type="radio" class="class_x">
<input id="SubmitButton" type="submit">
</form>
.prop() documentation

Categories