jquery - Dynamically add equal select form fields with data taken from php

120

I have a form with select fields dynamically generated and with the options taken from php (same for all the selects). But I need that every<select>...</select> must be shown in a different line. This can be done having every<select>...</select> inside a<div>...</div>.

This is the code that I have, it´s working but the select fields are not within a div:

<script type="text/javascript">
//<![CDATA[ 
$(function(){
var counter = 1;

$("#addButton").click(function () {

if(counter>10){
        alert("Only 10 textboxes allow");
        return false;
}   

var select = $('<select>').attr({id:'select'+counter,name:'select'+counter});

$.ajax({
url: 'selects.php',
dataType: "html",
success: function(data) {
select.html(data);
}
});        

select.appendTo("#TextBoxesGroup");
counter++;
});

$("#removeButton").click(function () {
if(counter==1){
   alert("No more textbox to remove");
   return false;
}   

counter--;
$("#select" + counter).remove();

});

$("#getButtonValue").click(function () {

var msg = '';
for(i=1; i<counter; i++){
  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
   alert(msg);
});
});
//]]> 
</script>

<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
    <label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
<div id="TextBoxDiv2">
    <label>Textbox #2 : </label><input type='text' id='textbox2' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

And this is the html code generated by select.php:

<option value="1">Uno</option>
<option value="2">Dos</option>
<option value="3">Tres</option>
<option value="4">Cuatro</option>

People are also looking for solutions to the problem: email - How to configure php.ini to work with smtp4dev?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.