Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

radio button enable/disable not working as expected

I am trying to switch my radio buttons either true or false using the following functionality.

But as a first click, I am not getting any response. Later on it works fine. ow to solve this issue and what is wrong here?

var switching = false;

$('button').on("click", function() {
  switching = switching == false ? switching = true : switching = false;
  console.log("switching", switching); //first click true but not works!
  $(":radio").attr("disabled", switching);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>

<button>
  Switch Me
</button>

Live Demo

like image 631
user2024080 Avatar asked Jul 04 '26 19:07

user2024080


2 Answers

You can just start from true and switch like this switching = !switching

var switching = true;

$('button').on("click", function() {
  switching = !switching
  $(":radio").attr("disabled", switching);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>

<button>
  Switch Me
</button>
like image 86
Nenad Vracar Avatar answered Jul 07 '26 09:07

Nenad Vracar


Or you can do it just with one line:

$('button').on("click", function() {
    $(":radio").prop('disabled', function(){ return !this.disabled });
});
button.border { border:2px solid green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>

<button>Switch Me</button>
like image 41
kosmos Avatar answered Jul 07 '26 07:07

kosmos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!