ANURAG GOLDEN
ANURAG GOLDEN

Reputation: 65

Why are the radios not being checked every time I click the buttons

The radios will be checked by the buttons only 1 time by each buttons, I want them to be checked every time I click the buttons

$(document).ready(function() {
  $("button").click(function() {
    var radio = $(this).parent().attr("for");
    $("#" + radio).attr("checked", "checked");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="radio" name="radio-btn" id="radio1">
<input type="radio" name="radio-btn" id="radio2">
<input type="radio" name="radio-btn" id="radio3">
<input type="radio" name="radio-btn" id="radio4">

<label for="radio1"><button>Games1</button></label>
<label for="radio2"><button>Games2</button></label>
<label for="radio3"><button>Games3</button></label>
<label for="radio4"><button>Games4</button></label>

Upvotes: 1

Views: 33

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Use prop() to set the checked state instead of putting the same attribute on them all.

$(document).ready(function() {
  $("button").click(function() {
    var radio = $(this).parent().attr("for");
    $("#" + radio).prop("checked", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="radio-btn" id="radio1">
<input type="radio" name="radio-btn" id="radio2">
<input type="radio" name="radio-btn" id="radio3">
<input type="radio" name="radio-btn" id="radio4">

<label for="radio1"><button>Games1</button></label>
<label for="radio2"><button>Games2</button></label>
<label for="radio3"><button>Games3</button></label>
<label for="radio4"><button>Games4</button></label>

Upvotes: 1

Related Questions