Reputation:
Ok here's what I have so far.. thanks to Paolo.
And it works fine, but only if I have existing radio button options.
What if I need to create a NEW radio button without any pre-existing ones?
Ultimately what I want to do is create an array of options, loop through them and output a list of options as radio buttons. So originally, there will be NO radio buttons within the 'abc' div.
Thanks in advance!
<script>
$(document).ready(function() {
// add a new input when a new color is chosen, for example
$('#aaa').change(function() {
var radio = $('<input>').attr({
type: 'radio', name: 'colorinput', value: '2', id: 'test'
});
$(':radio:last-child', '#abc').after(radio).after('option 3 ');
});
});
</script>
<form id='abcdef'>
<select id="aaa">
<option>red</option>
<option>blue</option>
<option>other</option>
</select>
<div id="abc">
Input<BR>
option 1 <input type="radio" name="colorinput" value="1" />
option 2 <input type="radio" name="colorinput" value="2" />
</div>
<BR>
</form>
Upvotes: 4
Views: 20231
Reputation: 625077
Ok given your updated question, this should do it (or be pretty darn close):
$(function() {
$("#aaa").change(function() {
$('<input type="radio" name="colorInput" id="test" value="2">')
.appendTo($("#abc")).before('Option 3');
});
});
Things to bear in mind:
Upvotes: 6
Reputation: 40235
Instead of dealing with the after and trying using the append. This way you don't have to check for the last radio button and the functionality will work when there are 0 radio buttons at startup.
var radio = $('<input>').attr({
type: 'radio', name: 'colorinput', value: '2', id: 'test'
});
$('#abc').append(radio.after('option 3'));
Upvotes: 4
Reputation: 39926
$(":radio:last").after('<input type="radio" name="blah">');
Upvotes: 1