Reputation: 123
I have many radio buttons with different name and value like this
<div>
<input type="radio" id="radio1" name="1" value="A" />
<input type="radio" id="radio1" name="1" value="B" />
<input type="radio" id="radio1" name="1" value="C" />
<input type="radio" id="radio1" name="1" value="D" />
</div>
<div>
<input type="radio" id="radio2" name="2" value="A" />
<input type="radio" id="radio2" name="2" value="B" />
<input type="radio" id="radio2" name="2" value="C" />
<input type="radio" id="radio2" name="2" value="D" />
</div>
and so on like 40 radio button. I save radio's name and value with sessionStorage like this
$(document).ready(function(){
$('input[type="radio"]').on('change', function()
{
sessionStorage.setItem($(this).prop('name'), $(this).val());
});
for (var i = 0; i < sessionStorage.length; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage.getItem(key);
$("#radio"+key).val(function(){
$(this).attr("checked", value);
});
}
});
Checked status returned but radio's value always returned same for all radio's button.
Upvotes: 0
Views: 350
Reputation: 1441
I checked your code and it’s giving me the expected result.
But there is wrong with your for loop. It giving null value for the first radio button. So you can use value="" checked
for give default values.
<div>
<input type="radio" id="radio1" name="1" value="A" value="" checked />
<input type="radio" id="radio1" name="1" value="B" />
<input type="radio" id="radio1" name="1" value="C" />
<input type="radio" id="radio1" name="1" value="D" />
</div>
Upvotes: 0
Reputation: 2857
I believe your issue may lie in the fact that you have multiple elements with the same id. Giving each radio button its own unique ID should solve your issue.
*EDIT -> This issue arises from the fact that elements are quite often identified by their 'id' this leads to problems where instead of applying changes to/getting information from an element with a specific 'id', you edit/get information from the last element with that 'id'.
Upvotes: 0
Reputation: 1674
check this https://jsfiddle.net/Lvmvky3u/1/,
remove the Id
to class
, id
only refers to a unique element
$(document).ready(function() {
$('input[type="radio"]').on('change', function() {
sessionStorage.setItem($(this).prop('name'), $(this).val());
});
for (var i = 0; i < sessionStorage.length; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage.getItem(key);
$(".radio" + key).filter('[value='+value+']').prop('checked', true);
}
});
Upvotes: 1