Parth  Mahida
Parth Mahida

Reputation: 614

How to add new select box every time I change value of new created selectbox in jQuery?

I am trying to add a new number input and a checkbox when I select a value from selectbox.After I add a selectbox that selectbox should add a new selctbox. I dont know what is wrong with my code. Thanks in advance.

var counter = 1;
$(document).ready(function(){

  $('#arithmetic' + counter).change(function(e)
                                    {
    counter++
    if( $('#arithmetic' + counter ).val() == '+' || '-' || '*' || '/'  || '%' )
    {

      var newTextBoxDiv = $(document.createElement('div'))
      .attr("id", 'TextBoxDiv' +counter);
      newTextBoxDiv.html('<input type="number" name="input' + counter + ' "  id="input' + counter + '" value="" > \

<select id="arithmetic' + counter + '" >\

<option id="select" value="Select" selected>Select</option>\

<option id="add" value="+">+</option><option id="subtract" value="-">-</option>\

<option id="multiply" value="*">*</option><option id="division" value="/"></option>\
<option id="percentage" value="   %">%</option></select>');


      newTextBoxDiv.appendTo("#container center");
    }
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="container">
  <center>
    <div id="TextBoxDiv1">
      <input type="number"/>
      <select id="arithmetic1">
        <option id="select" value="Select" selected>Select</option>
        <option id="add" value="+">+</option>
        <option id="subtract" value="-">-</option>
        <option id="multiply" value="*">*</option>
        <option id="division" value="/">/</option>
        <option id="percentage" value="%">%</option>
      </select>
    </div>
  </center>

</div>

Upvotes: 1

Views: 66

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

You need to delegate the events on the newly created elements. So, what you need to do is, instead of:

$('#arithmetic' + counter).change(function(e)

Change it to:

$("#container").on("change", '#arithmetic' + counter, function(e)

And there are a few mistakes...

  1. Replace:

    $(document.createElement('div'))
    

    With:

    $("<div />")
    
  2. Remove the <center> tag.

Upvotes: 2

Related Questions