NotRocketScientist NotRocketScientist - 1 month ago 4
Javascript Question

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!

Answer

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>