Harsh Gupta
Harsh Gupta

Reputation: 173

Radio button default checked not working because of JQuery function

I have a list of radio buttons binded to a checkbox in the following manner.

1) When the checkbox is checked, the radio buttons are enabled and have a default button checked (say value=1) (only one radio button can be selected out of the three)

2) When the checkbox is unchecked, the radio buttons are disabled and their selection attribute is removed.

The problem that I'm facing is that due to the following HTML and Jquery code, the default selection of radio button on page load (value=1) is not working. I've not been able to identify the error. Can somebody please helpout?

$('#mailcheck').change(function() {
  $('input[name="freq"]').prop('disabled', !this.checked);
  $('input[name="freq"]').removeAttr('checked');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="notcheck">
  <input type="checkbox" id="mailcheck" checked="checked">I want to receive an email notification of ads uploaded on my college marketplace
</label>
<br>

<ul>
  <li>
    <label>
      <input type="radio" name="freq" value="1" id="freqradio" checked="checked">Daily</label>
  </li>
  <li>
    <label>
      <input type="radio" name="freq" value="3" id="freqradio">Every 3 days</label>
  </li>
  <li>
    <label>
      <input type="radio" name="freq" value="7" id="freqradio">Weekly</label>
  </li>
</ul>

Upvotes: 1

Views: 2879

Answers (1)

user3845133
user3845133

Reputation:

Here is a rough working version:

$('#mailcheck').change(function(){
    if($(this).is(':checked')) {
        $('input[name="freq"]').prop('disabled', false).first().prop('checked', true);
    } else {
        $('input[name="freq"]').prop('disabled', true).prop('checked', false);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label id="notcheck">
 <input type="checkbox" id="mailcheck" checked="checked" >I want to receive an email notification of ads uploaded on my college marketplace
</label><br>

  <ul>
   <li><label><input type="radio" name="freq" value="1" id="freqradio1" checked="checked">Daily</label></li>
   <li><label><input type="radio" name="freq" value="3" id="freqradio2">Every 3 days</label></li>
   <li><label><input type="radio" name="freq" value="7" id="freqradio3">Weekly</label></li>
  </ul>

p.s. the ids must have an unique value

Upvotes: 5

Related Questions