Tutorial :JQuery - create NEW radio buttons



Question:

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>  


Solution:1

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:

  • You can construct the HTML directly in the jQuery constructor;
  • I assume you will be using dynamic IDs, values and labels. That's simply a question of concatenating strings and variables in the expression;
  • You probably need to check for duplicates (not covered above);
  • If you're putting them in a div like you seem to, after the approach above rather than what I originally suggested (ie $(":radio:last")) as its faster and clearer and doesn't rely on their being a radio button in existence already; and
  • Newly constructed HTML elements won't have any relevant event handlers on them unless you're using the jQuery 1.3 live() event handler.


Solution:2

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'));  


Solution:3

$(":radio:last").after('<input type="radio" name="blah">');  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »