I’m trying to alter the ID of an input based on the selection of a radio box.
<input type="text" name="judge"/>
<input type="radio" name="type" value="percent"/>Percent |
<input type="radio" name="type" value="decimal"/>Decimal
<br/>
<button type="button" id="mybutton">Check</button>
<br/><br/>
<div id="output"/>
Clicking radio button percent or decimal will change the ID of the input box.
//Set the ID of the input box on radio change
$('input[name=type]').change(function() {
if ($(this).val() == "percent") {
$('input[name=judge]').attr('id', 'judge_percent');
} else if ($(this).val() == "decimal") {
$('input[name=judge]').attr('id', 'judge_decimal');
}
});
//IF statement depending on the input ID created from the radio button
$('#mybutton').click(function() {
if ($('input[name=type]').val() == "percent") {
value_percent = parseFloat($('#judge_percent').val());
$('#output').html(value_percent);
} else if ($('input[name=type]').val() == "decimal") {
value_decimal = parseFloat($('#judge_decimal').val());
$('#output').html(value_decimal);
}
});
This only works half-way. If I check ‘decimal’ and click my button, I get ‘NaN’, as if it’s not reading the input ID.
Edit:
Here is the correct Jsfiddle: http://jsfiddle.net/6FbdJ/1/
Should be:
This is what you got in the DEMO.
Update:
Change the selector from:
To:
Fixed DEMO
You can replace
$(this).val()withthis.value.