I have the following code to insert multiple products and prices before submitting the main quotation form.
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<br>' + '<label>Product '+ counter + ' </label>' +
'<input type="text" name="product" id="product" value="" >' +
'<label>Price '+ counter + ' </label>' +
'<input type="text" name="price" id="price" value="" >'+ '<a href="#" id="save" >Save!</a>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
$("#save").click(function() {
if(!$("#product").val() || !$("#price").val() ){
apprise("You must define a product and price!");
}else{
var product = $("#product").val();
var price = $("#price").val();
var postdata = 'product='+product+'&price='+price;
$.ajax({
type: "POST",
url: "inserter/add_quotation_product.php",
data: postdata,
success: function() {
$('#TextBoxesGroup').html("<div id='message'></div>");
$('#message').html(product+" Saved!");
}
});
return false;
}
main html code:
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Product 1 </label>
<input type=text
id="product"
name="product"
placeholder="product to quote"
required/>
<label>Price 1</label>
<input id="price"
name="price"
type=text
placeholder="price of product"
required>
<a href="#" id="save" >Save!</a>
</div>
</div>
the problem is clicking on the save button that is manually created works well but clicking the save button created by jquery seems be completely inactive!
The click event to the save link is already bound. When adding a new product you create a new save link without the event attached.
You can’t have multiple elements links with the same id so I would assign a class to the save link. It must be in the main html code and in your javascript code that creates the link.
Use the live method of the jquery object in order to bind the event for ‘future’ events as well. http://api.jquery.com/live/
Dependeding on the version of jquery you have to use on : http://api.jquery.com/on