Val
Val

Reputation: 1350

Appending a new drop down selector using jquery .append method

I am wanting to add anther drop down selector every time I press the button. Currently I am using JQUERY to add the new drop down field, however, I am unable to get the new drop down selector added. Currently the code is not working. Below is the code:

jsfiddle

Jquery:

$(document).ready(function(){
  existingdiv1 = document.getElementById( "dropDown" );    
  $("#btn1").click(function(){
  $("z").append('<strong>Hello</strong>', existingdiv1);
  });
});

HTML:

<div class="control-group">
  <div class="controls">
    <z>
    <select id="servingSizeUnits" class="selectpicker btn-medium btn-block" data-style="btn-info" name="dropDown" id="dropDown">
       <optgroup label="Select Product Type">
           <option name="dropDown" value="val1">val1</option>
           <option name="dropDown" value="val2">val2 </option>
           <option name="dropDown" value="val3">val3</option>
           <option name="dropDown" value="val4">val4</option>
           <option name="dropDown" value="val5">val5</option>
      </optgroup>
    </select>
      </z>    
      </div>    
 </div>    

    <button id="btn2" class="btn btn-primary" data-activate="#payment" type="submit">Add Selector</button>

Any suggestions would be great.

Update 1: I have made sure the SO and fiddle code are the same.

Upvotes: 0

Views: 2007

Answers (2)

Pranav
Pranav

Reputation: 666

First of all you havent included jquery in your fiddle..I have updated your fiddle and im attaching it here. http://jsfiddle.net/aR9r9/2/

$(document).ready(function(){
  $("#btn2").click(function(){
  $(".app").append('<input class="input-block-level" type="text" name="newfield" id="newField" placeholder="New Field">'
  );
  });
});

Here im appending the selector with a div thats enclosing the select.

Upvotes: 1

Shaunak D
Shaunak D

Reputation: 20636

var count = 0;
$(document).ready(function(){
  $("#btn2").click(function(){
     count ++; 
    var select = $('#servingSizeUnits').clone().attr('id',$('#servingSizeUnits').attr('id')+count).attr('name',$('#servingSizeUnits').attr('name')+count); 
  $("z").append(select);
  });
});

Check this Demo Fiddle

Use jquery clone()

Note: You cannot append this -

<input class="input-block-level" type="text" name="newfield" id="newField" placeholder="New Field">

as the Id attribute will be duplicated, which is not advisable.

Upvotes: 1

Related Questions