radio input replacement using jquery
Posted
by altvali
on Stack Overflow
See other posts from Stack Overflow
or by altvali
Published on 2010-06-07T14:02:50Z
Indexed on
2010/06/07
14:42 UTC
Read the original article
Hit count: 276
It may seem a bit odd to ask this since there are several solutions out there but the fact is that all of them look pretty and none of what i've seem save the input value for form submission the right way.
I'm looking for something that will replace all radio inputs with divs that get special classes when they are hovered or clicked, and an input type hidden for every group of radio inputs with the same name, hidden input that will be updated with the value corresponding to the div the user clicks on. Long sentence, i know. Here's what i've come up with:
$('input:radio').each(function(){
if (this.style.display!='none') {
var inputName = $(this).attr('name');
var inputValue = $(this).attr('value');
var isChecked = $(this).attr('checked');
if (!$('input:hidden[name='+inputName+']').length)
// if the hidden input wasn't already created
$(this).replaceWith('<div class="inputRadioButton" id="'+inputName+'X'+inputValue+'"></div><input type="hidden" name="'+inputName+'" value="'+inputValue+'" />');
else{
$(this).replaceWith('<div class="inputRadioButton" id="'+inputName+'X'+inputValue+'"></div>');
if (isChecked)
$('input:hidden[name='+inputName+']').attr({'value':inputValue});
}
//this bind doesn't work
$("#"+inputName+"X"+inputValue).click(function(){
if($('input:hidden[name='+inputName+']').val()!=inputValue){
$('input:hidden[name='+inputName+']').attr({'value':inputValue});
$('div[id*='+inputName+'].inputRadioButton').removeClass('inputRadioButtonSelected');
}
if (!$("#"+inputName+"X"+inputValue).hasClass('inputRadioButtonSelected'))
$("#"+inputName+"X"+inputValue).addClass('inputRadioButtonSelected');
});
}
});
Please tell me how to fix it. Thank you.
Edit I've found the reason. It should normally work but some of my radio inputs generated by an e-commerce software had brackets in them (e.g. id[12] ) and jQuery was parsing that. The fix is adding
var inputButton = document.getElementById(inputName+"X"+inputValue);
before the bind and replacing $("#"+inputName+"X"+inputValue)
with $(inputButton)
.
© Stack Overflow or respective owner