This is probably a stupidly simple question, but I'm stuck.
I had created a form with multiple checkboxes, and when the checkboxes were clicked, it would pass the values of each checkbox as a comma-separated list to a hidden input field. It worked a treat. but due to some issues, I now have to alter my code so that it uses radio buttons instead - so no comma-separated list of values, just one at a time.
I altered the code to swap it out to radio buttons, and it's working fine except for two things: 1) it's not switching between radio buttons (each time I select a button, it stays selected as I choose others) and 2) it's adding to the list instead of returning the single option selected. In other words, it's still acting like a checkbox, except visually, it's round and has a dot. LOL
This is my code thus far:
jQuery(document).ready(function($) {
$(':radio').click(function() {
var radio = $(this);
var text = $('input[name="cat"]');
if(radio.is(':checked')) {
text.val(text.val() + radio.val());
//alert(text.val());
} else {
text.val(function() {
$(this).val().replace(radio.val(),"");
});
}
});
});
so when I uncomment that "alert" line, I can see what's passed, and it's just adding to the list instead of replacing with the new value. Anyone know how to fix the above so only one option can be selected and passed? (The above code works awesomely as a checkbox thing though. I actually think I got the above code from here somewhere, although I can't remember where!)
EDIT: here's the code that solved the issue and works a treat (thanks to you all :) ) - maybe it'll help someone else in the future.
`jQuery(document).ready(function($) {
$(':radio').change(function() {
var radio = $(this);
var text = $('input[name="cat"]');
if(radio.is(':checked')) {
text.val(radio.val());
//alert(text.val());
} else {
text.val(function() {
$(this).val().replace(radio.val(),"");
});
}
});
});`