JQuery - create new radio buttons

Ok, thatโ€™s what I still have .. thanks Paolo.
And it works fine, but only if I have existing switch options.

What if I need to create a NEW switch without any existing ones?

Ultimately, what I want to do is create an array of options, skip them and list the options as radio buttons. Therefore, initially in the div 'abc' there will be no radio buttons.

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> 
+4
source share
3 answers

Well, given your updated question, this should do it (or be pretty black):

  $(function() { $("#aaa").change(function() { $('<input type="radio" name="colorInput" id="test" value="2">') .appendTo($("#abc")).before('Option 3'); }); }); 

What you need to remember:

  • You can build HTML directly in the jQuery constructor;
  • I assume that you will use dynamic identifiers, values, and labels. It is just a matter of concatenating strings and variables in an expression;
  • You probably need to check for duplicates (not mentioned above);
  • If you put them in a div, as it seems, after the approach above, and not what I originally suggested (for example, $ (": radio: last")), since it is faster and more understandable and does not rely on them already radio button; and
  • Newly created HTML elements will not have matching event handlers unless you use the jQuery 1.3 live () event handler.
+6
source

Instead of handling after and trying to use append . Thus, you do not need to check the last radio button, and the functionality will work if there are 0 switches at startup.

 var radio = $('<input>').attr({ type: 'radio', name: 'colorinput', value: '2', id: 'test' }); $('#abc').append(radio.after('option 3')); 
+4
source
 $(":radio:last").after('<input type="radio" name="blah">'); 
+1
source

All Articles