I am trying to create an dynamic order form using Jquery and PHP and got stuck. I have a Jquery code that onclick
adds a new set of fields. Also in that jquery code I apply some style and jquery to one of the fields. Its an Multiselect, Searchable dropdown list.
Problem here however. I can apply this style so that it has the search bar etc. to the first one. the ones after are just random multilists with no vallues or searchbar.
Here is my code:
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
//THIS WORKS!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
//THIS DOESNT WORK!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'<a href="#" class="remove_field">Remove</a>' +
'</div>' +
'<div><input type="number" name="quantity'+ x +'" min="1" max="10"><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<div class="input_fields_wrap">
<form method="post"><input type="submit" value="Add item" class="add_field_button"></form>
<div>
<select id="country1" multiple="multiple" style="width:300px;">
<!-- Dropdown List Option -->
</select>
</div>
</div>
So in the Jquery I put 2 comments in caps rage to mark what I mean that doesnt work.
Screenshots:
This on first sight
When I click in the multiselect tab this works.
Picture speaks for itself. just messed up and if I click it nothing happends.
$(add_button).click
to$(".add_field_button").click
), isnt enough.