Attempting to print out user input using jQuery - javascript

I have a section in my system that allows users to enter ingredients and then when they click 'live preview' each ingredient is printed out in plain text so they can check spelling using jQuery. However it will only print out the first element and not the ones after. Can anyone see why? Here is the fiddle http://jsfiddle.net/X94At/
HTML
<div class="recipe-ingredients pure-u-1 pad8bottom clearfix">
<span class="heading">Ingredients</span>
<div class="ingredients pure-u-1 clearfix">
<div class="ingredient pure-u-1 clearfix">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" placeholder="Ingredient" class="element pure-u-6-24" />
<input type="text" id="quantity_1" name="quantity[]" value="" placeholder="Quantity" class="element pure-u-4-24" />
<select id="selectQuantity_1" name="quantityType[]" class="element pure-u-3-24">
<option value="grams">Grams</option>
<option value="ounces">Ounces</option>
<option value="Pounds">Pounds</option>
</select>
<input type="text" id="alternative_1" name="alternative[]" value="" placeholder="Alternative Ingredient" class="element pure-u-6-24" />
<input type="text" id="addedQuantiy_1" name="addedQuantity[]" value="" placeholder="Quantity per extra person" class="element pure-u-4-24" />
</p>
</div>
</div>
Add Ingredient
</div>
HTML For the Live Preview
<div id="toPopup">
<div class="close">×</div> <span class="ecs_tooltip">End Preview<span class="arrow"></span></span>
<div id="live-preview-display">
<div id="lp-name"></div>
<div id="lp-ingredientslist">
<h3>Ingredients</h3>
</div>
<div id="lp-step">
<h3>Method</h3>
</div>
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>
jQuery
$(".ingredient").on('blur change focus', function () {
$('.ingredient p').each(function () {
var i = $('.ingredient p').size(),
el = $(this);
if ($('#lp-ingredientslist .ingredient_' + i).length == 0) {
$("#lp-ingredientslist").append('<span class="ingredient_' + i + '"></span>');
}
var ingredient = el.find('input[name="ingredient[]"]').val(),
quantity = el.find('input[name="quantity[]"]').val(),
quantityType = el.find('select[name="quantityType[]"]').val(),
alternative = el.find('input[name="alternative[]"]').val();
if (!quantity || !ingredient)
return;
var alt = '';
if (alternative.length >= 0) {
alt = ' (you can also use ' + alternative + ')';
}
$('#lp-ingredientslist .ingredient_' + i).html(i + '. ' + quantity + ' ' + quantityType + ' of ' + ingredient + alt + '</br></br> ');
});
});
jQuery to add an ingredient
$('.recipe-ingredients #addNewIngredient').on('click', function () {
var i = $('.recipe-ingredients .ingredient').size() + 1;
$('<div class="ingredient pure-u-1 clearfix"><input type="text" id="ingredient_' + i + '" name="ingredient[]" placeholder="Chocolate" class="element pure-u-6-24" /><input type="text" id="quantity_' + i + '" name="quantity[]" value="" placeholder="Quantity" class="element pure-u-4-24" /><select id="selectQuantity_1" name="quantityType[]" class="element pure-u-3-24"><option value="grams">Grams</option><option value="ounces">Ounces</option><option value="Pounds">Pounds</option></select><input type="text" id="alternative_' + i + '" name="alternative[]" value="" placeholder="Alternative Ingredient" class="element pure-u-6-24" /><input type="text" id="addedQuantiy_' + i + '" name="addedQuantity[]" value="" placeholder="Quantity per extra person" class="element pure-u-4-24" />×</div>').appendTo($('.recipe-ingredients .ingredients'));
Thanks!

Not perfect needs improvement
Working Fiddle
$(".ingredient").on('blur change focus', function () {
this line needs to be replaced by
$('.ingredients').on('blur change focus', function () {
as you dynamically are adding the .ingredient class so the changes would appear at .ingredients....
Update
Fiddle with a new look Credit goes to #WASasquatch for pointing it out...
Hope it helps....!!

Related

How to determine if the input is of array type in javascript?

<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc

Dynamic JQUERY array works for some records

Thanks to the help from StackOverflow I have got as far as creating a single line entry with fields and then this adds each field to an array but the Hours SQL statement isn't working e.g. it will have blank sql entries for the first 2 records and then work correctly on another but I cannot see what I am doing wrong. Any help would be very appreciated.
<td colspan="3" align="left"><div id="hoursrow">
<p> <span class="text">Hours Labour :</span></span></p>
<p> <span class="headings"><span class="text"><span class="hours">Start Time:
<input type="time" name="add_start" size="4" />
Finish Time:
<input type="time" name="add_finish" size="4" />
Date:
<input type="date" name="add_date" size="4" />
OVT:
<input type="checkbox" name="add_overtime_hours" id="add_overtime_hours" size="1" maxlength="1" />
</span></span><span class="text"><span class="hours">
<input onclick="addhours(this, event);" type="button" value="Add Labour" />
</span></span></p>
<p class="headings"><span class="text"><span class="hours">
<span class="info">(This row will not be saved unless you click on "Add Labour" first) </span></span></span></p>
</div></td>
<td width="7"></td>
</tr>
<tr>
var rownumhours = 1;
function addhours(obj, e) {
rownumhours++;
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[' + rownumhours + ']" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> Show_Overtime: <input type="text" name="show_overtime_hours[' + rownumhours + ']" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[' + rownumhours + ']" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
' "> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
$(obj).closest('span.headings').find('[name="add_start"]').val("");
$(obj).closest('span.headings').find('[name="add_finish"]').val("");
$(obj).closest('span.headings').find('[name="add_date"]').val("");
$(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
So it is showing on the page properly as I want it to but then the major problem is is won't add properly to the database.
I have echo'd the sql that is to be inserted into the database and it shows the following.
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','10:10','11:11','2017-01-03','') //
The Sql part is as follows
if (
!empty($_POST['add_start']) && !empty($_POST['add_finish']) && !empty($_POST['add_date']) && !empty($_POST['show_overtime_hours'])&&
is_array($_POST['add_start']) && is_array($_POST['add_finish']) && is_array($_POST['add_date']) && is_array($_POST['show_overtime_hours'])&&
count($_POST['show_overtime_hours']) && count($_POST['add_finish']) && count($_POST['add_date']) === count($_POST['add_start'])
) {
$add_start_array = $_POST['add_start'];
$add_finish_array = $_POST['add_finish'];
$add_overtime_hours_array = $_POST['show_overtime_hours'];
$add_date_array =$_POST['add_date'];
for ($i = 0; $i < count($add_start_array); $i++) {
$add_start_values = $mysqli->real_escape_string($add_start_array[$i]);
$add_finish_values = $mysqli->real_escape_string($add_finish_array[$i]);
$add_date_values = $mysqli-> real_escape_string($add_date_array[$i]);
$add_overtime_hours_boolean = $mysqli-> real_escape_string($add_overtime_hours_array[$i]);
$sql_add_hours = "INSERT INTO hours(job_number,start_time,finish_time,date,overtime) VALUES('$increment_job_number','$add_start_values','$add_finish_values','$add_date_values','$add_overtime_hours_boolean')";
$mysqli-> query($sql_add_hours);
// This next section is for debugging only
//echo ($add_date_values);
//echo ($add_start_values);
//echo ($add_finish_values);
echo ($sql_add_hours);
//echo ($add_overtime_hours_values);
}
Ok, after doing some inspections, actually the first group of the html components produced from the JQuery is :
"Start Time:"
<input type="time" name="add_start[2]" size="4" value="23:57">
"Finish Time:"
<input type="time" name="add_finish[2]" size="4" value="22:57">
"Date:"
<input type="date" name="add_date[2]" value="2017-01-13">
"Show_overtime:"
<input type="text" name="show_overtime_hours[2]" size="1" value="0">
"Overtime:"
<input type="checkbox" name="add_overtime_hours[2]" size="1" value="on">
<input type="button" value="Remove" onclick="removeRow(2)">
You see there...,the counter (rownumhours) starts from 2.
Thus in your php part, the first entries for these array :
$add_start_array = $_POST['add_start'];
$add_finish_array = $_POST['add_finish'];
$add_overtime_hours_array = $_POST['show_overtime_hours'];
$add_date_array =$_POST['add_date'];
Also at 2nd-index, but as your loop starts from zero , hence the entry for the location is empty.
So start the rownumhours in javascript part from -1:
var rownumhours = -1;
Quick Fix
You increment the rownumhours before dynamically adding a new row of fields.
The quickest fix is change the rownumhours value to 0
var rownumhours = 0;
So the newly added row of fields will have the index of 1 and up.
Also add [] to the name tag to the first/default row:
<input type="time" name="add_start[]" size="4"> <!-- this will have an index of 0 -->
<!-- DO THE SAME WITH FIRST/DEFAULT SET OF FIELDS -->
Recommendation
But what you can actually do is do not bother with the assigning of index.
Just put [] to the given row of fields:
<td colspan="3" align="left">
<div id="hoursrow">
<p>
<span class="text">Hours Labour :</span>
</p>
<p>
<span class="headings">
<span class="text">
<span class="hours">
Start Time: <input type="time" name="add_start[]" size="4" />
Finish Time: <input type="time" name="add_finish[]" size="4" />
Date: <input type="date" name="add_date[]" size="4" />
OVT: <input type="checkbox" name="add_overtime_hours[]" id="add_overtime_hours" size="1" maxlength="1" />
</span>
</span>
<span class="text">
<span class="hours">
<input onclick="addhours(this, event);" type="button" value="Add Labour" />
</span>
</span>
</span>
</p>
<p class="headings">
<span class="text">
<span class="hours">
<span class="info">(This row will not be saved unless you click on "Add Labour" first)</span>
</span>
</span>
</p>
</div>
</td>
Then remove the rownumhours and do not assign index for dynamically added input fields:
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[]" size="4" value="' + $(obj).closest('span.headings').find('[name="add_start"]').val() + '"> /*** JUST CONTINUE THE REST OF THE INPUT FIELDS ***/
Thank you all so very much for the help. I am sorry It took a few days to reply. I have made the changes by taking the rownumhours ++ off and using the [] for the naming to be taken care of itself which I had no idea it was clever enough to do it on its own.
The Mysql Section worked well and I also left the html section because I only wanted to have different names for the multiple hours into the entries
var rownumhours = 0;
function addhours(obj, e) {
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[]" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[]" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[]" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> <input type="hidden" name="show_overtime_hours[]" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[]" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
' "> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
rownumhours++;
$(obj).closest('span.headings').find('[name="add_start"]').val("");
$(obj).closest('span.headings').find('[name="add_finish"]').val("");
$(obj).closest('span.headings').find('[name="add_date"]').val("");
$(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
</script>

Dynamically add dropdown box in laravel. Javascript and laravel

I want to add dynamic dropdown & textbox. But for textbox is ok. I am not ok in dropdown. The Data are not include in Dropdown.I am loop to retrieve data in blade.I am describe my code.
form.blade.php
<div class="form-group">
<label for="type">Gas Container Type</label>
<select class="form-control input-sm" name="gas" id="gas">
#foreach($gass as $gas)
<option value="{{$gas->name}}">{{$gas->name}}</option>
#endforeach
</select><!-- end of Item_Drop_Down -->
</div>
<input name="name[]" type="text" id="name" class="name" placeholder="Input 1">
Add More Input Field
master.blade.php
<script>
$(document).ready(function () {
var e = document.getElementById("gas");
$('#add').click(function () {
var inp = $('#box');
var i = $('input').size() + 1;
$('<div id="box' + i + '">' + '' +
'<input type="text" id="name" class="name" name="name[]" placeholder="Input ' + i + '"/>' + '' +
'<select id="gas" name="gas[]" ' + i + '"/><img src="remove.png" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>')
.appendTo($('#box form'));
i++;
});
{{--<select data-bind="options: availableCountries, optionsText: 'name', optionsValue: 'value'"></select>--}}
$('body').on('click', '#remove', function () {
$(this).parent('div').remove();
});
});
controller.php
public function store(Request $request)
{
foreach ($request->get('name') as $name) {
$kg = new WarehouseGasIn();
$kg->kg = $name;
//dd($request->get('name'));
$kg->save();
}
<script>
$(document).ready(function () {
$('#add').click(function () {
var inp = $('#box');
var i = $('input').size() + 1 - 2;
$('<div id=box' + i + '"><input type="text" id="name" class="name" name="name[0][]" placeholder="Input ' + i + '"/><select class="form-control input-sm" name="shop" id="shop"><option value="">{{"Shop"}}</option>#foreach($branches as $branch)<option value="{{$branch->id}}">{{$branch->name}}</option>#endforeach</select><select name="name[1][]" id="gas" ' + i + '>#foreach($gass as $gas) <option value="{{$gas->id}}">{{$gas->name}}</option>#endforeach</select><img src="remove.png" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>').appendTo($('#box form'));
i++;
});
$('body').on('click', '#remove', function () {
$(this).parent('div').remove();
});
});
</script>
is this the sort of thing you are trying to achieve?
$(document).ready(function () {
var boxesWrap = $('#boxes-wrap');
var boxRow = boxesWrap.children(":first");
var boxRowTemplate = boxRow.clone();
boxRow.find('button.remove-gas-row').remove();
// nb can't use .length for inputCount as we are dynamically removing from middle of collection
var inputCount = 1;
$('#add').click(function () {
var newRow = boxRowTemplate.clone();
inputCount++;
newRow.find('input.name').attr('placeholder', 'Input '+inputCount);
boxesWrap.append(newRow);
});
$('#boxes-wrap').on('click', 'button.remove-gas-row', function () {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes-wrap">
<div>
<div class="form-group">
<label>Gas Container Type</label>
<select class="form-control input-sm" name="gas[]">
<option value="gas-1">Container 1</option>
<option value="gas-2">Container 2</option>
</select><!-- end of Item_Drop_Down -->
</div>
<input name="name[]" type="text" class="name" placeholder="Input 1">
<button class="remove-gas-row" type="button">Remove</button>
</div>
</div>
Add More Input Field

Cant remove the div which added runt time by appending another div in MVC view

I am developing ASP.NET MVC application.
I am adding the Div Run time by click event on View using Jquery.
After adding div , I am trying to remove it... but It cant get removed.
I have put alert box on the click function of remove link but that also not working.
here is my Complete Code....
<script type="text/javascript">
$(document).ready(function () {
$('.remove').click(function () {
alert("asd");
$(this).parent().parent().remove();
});
function getProductList(rIndex) {
//alert("In Product list");
var productList;
var mainList;
var productListArray = [];
$.ajax({
url: '#Url.Content("~/Product/GetProductList")',
success: function(data) {
mainList = data;
var options = '';
temp = 0;
for (var index = 0; index < data.length; index++) {
productListArray[index] = data[index].Id;
options += '<option value="' + data[index].Id + '">' + data[index].Name + '</option>';
}
productList = options;
$("select#ddProductList_" + rIndex).html(productList);
}
});
}
$('#lnkAddProduct').click(function () {
var rIndex = $("select.clsProductId").length;
// $('#ProductList').append("<div><span style='font-size:12px;'><select class='clsProductId' id='ddProductList_" + rIndex + "' name='ProductId' style = 'font-size:12px;width:120px;margin-right:10px;margin-left:0px;' /></span><input type='text' id='SectionCode' style='width:10%; margin-right:30px;'></div>");
$('#ProductList').append("<div><span style='font-size:12px;'><select class='clsProductId' name='ProductId' id='ddProductList_" + rIndex + "'name='ProductId' style = 'font-size:12px;width:150px;margin-right:10px;margin-left:0px;' /></span><input type='text' id='SectionCode' name='SectionCode' style='width:10%; margin-left:7px;'><input type='text' id='Size' name='Size' style='width:5%; margin-left:20px;'><input type='text' id='Length' name='Length' style='width:8%; margin-left:25px;'><input type='text' name='Thickness' id='Thickness' style='width:8%; margin-left:25px;'><input type='text' id='Weight' name='Weight' style='width:8%; margin-left:25px;'/><input type='text' id='Quantity' name='Quantity' style='width:8%; margin-left:30px;'/><span style='margin-left:10px;padding-top:6px;'> <a href='#' style='font-size:14px;text-decoration:none;font-weight:bold;' id='lnkRemove' class='clsRemove remove'>X</a></span></div>");
getProductList(rIndex);
});
getProductList(0);
});
</script>
<html>
<body>
<div class="span11 " style="margin-bottom : 20px; ">
<div class="row-fluid">
<div class="span1" style="margin-left:10px; width:100px;">
Section Name
</div>
<div class="span1" style="margin-left:60px;width:120px;">
Section Code
</div>
<div class="span1" style="margin-left:10px;width:60px;">
Size
</div>
<div class="span1" style="margin-left:20px;width:80px;">
Length
</div>
<div class="span1" style="margin-left:20px;width:80px;">
Thickness
</div>
<div class="span1" style="margin-left:20px;width:90px;">
Avg. Weight
</div>
<div class="span1" style="margin-left:35px;width:80px;">
Quantity
</div>
</div>
<div class="row-fluid" id="ProductList">
#*<input type="text" id="SectionName" style="width:10%; margin-right:40px;" />*#
<span style='font-size: 12px;margin-left:0px;'><select class='clsProductId span11' id='ddProductList_0' name='ProductId' style='font-size:12px;width:150px;margin-right:3px;margin-left:0px;'>
<option selected="selected" value=""></option>
</select></span>
<input type="text" id="SectionCode" name="SectionCode" style="width:10%; margin-left:10px;" />
<input type="text" id="Size" name="Size" style="width:5%; margin-left:20px;" />
<input type="text" id="Length" name="Length" style="width:8%; margin-left:20px;" />
<input type="text" id="Thickness" name="Thickness" style="width:8%; margin-left:20px;" />
<input type="text" id="Weight" name="Weight" style="width:8%; margin-left:20px;" />
<input type="text" id="Quantity" name="Quantity" style="width:8%; margin-left:30px;" />
#* <span style="margin-left:10px;padding-top:6px;"> <a href='#' style='font-size:14px;text-decoration:none;font-weight:bold;' id='lnkRemove' class='clsRemove remove'>X</a></span>
<a href='#' class='123'>X</a>
<div class="span10" style="margin-left:0px;">
Add Product
<span id="LinkErrorMsg" class="field-validation-error"></span>
</div>
</div>
</body>
</html>
Try event delegation using .on() as your remove link is created runtime.
$("#ProductList").on('click','.remove',function () {
alert("asd");
$(this).closest("div.row-fluid").remove(); // Avoid parent().parent() you can use .closest()
});
ref:
.closest() API docs

Add and Remove form elements when it increment "n" value with button

I have a form with code like the following snippet:
<div class="form-group">
<div class="col-md-12">
<input type="text" required="" name="n_p1" class="form-control depox" placeholder="Nama Penumpang">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" required="" name="t_p1" class="form-control depox" placeholder="Nomor HP">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" required="" name="l_p1" class="form-control depox" placeholder="Alamat Penjemputan">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" required="" name="l_t1" class="form-control depox" placeholder="Alamat Tujuan">
</div>
</div>
I have the "Add button"
<span rel="tooltip" title="Klik untuk menambah penumpang" class="pull-right fa fa-plus fa-3x hover-depox" onclick="addPassenger();"></span>
which serves to add elements such as the above. When the button is clicked, it will run addPassenger() function increments the value will be "n". the value "n" is used to accommodate the array of data in PHP from the input name attribute.
I also have a "Remove button" that will perform the remPassenger(m) function:
<a onclick="remPassenger('+ (n-1) +')" class="text-warning pull-right"><span class="fa fa-times"></span></a>
This is the jquery that there are 2 functions as above.
var total_passenger = 1;
function addPassenger() {
var n = total_passenger+1;
var str = "<hr style=\"border-bottom: 1px solid #fff;\">";
str += '<div class="form-group"><div class="col-md-12"><input type="text" name="n_p' + n + '" class="form-control depox" placeholder="Nama Penumpang ke-' + n + '"></div></div><div class="form-group"><div class="col-md-12"><input name="t_p' + n + '" type="text" class="form-control depox" placeholder="No HP Penumpang ke-' + n + '"></div></div><div class="form-group"><div class="col-md-12"><input name="l_p' + n + '" type="text" class="form-control depox" placeholder="Lokasi Penjemputan Penumpang ke-' + n + '"></div></div><div class="form-group"><div class="col-md-12"><input name="l_t' + n + '" type="text" class="form-control depox" placeholder="Alamat Tujuan Penumpang ke-' + n + '"></div></div><div id="add-passenger' + n + '" style="display: none;"></div>';
jQuery('#add-passenger' + total_passenger.toString()).append(str);
jQuery('#add-passenger' + total_passenger.toString()).slideDown('medium');
total_passenger++;
}
function remPassenger(m){
total_passenger--;
jQuery('#add-passenger' + m).remove();
}
This will fill the jquery element into to accommodate the elements if the button is clicked and remove the elements from the .
<div id="add-passenger1" style="display: none;"></div>
My Problem is when i click "Add Button" and normally then i use "Remove Button" click and it's worked, then i click "Add Button" again. it cant works.
Note: You can visit my site in http://stage.travelcar.co.id go through the steps until you find the form "Data Pemesanan"
Check if this is what you want ?
I made a small modification to your code.Instead of having
<div id="add-passenger1" style="display: none;"></div>
in html and then adding things into this even when another passenger is added it would have created problems later hence i modified your html removing this line from html and adding it to your add passenger method logic (check the demo for clear details)
and adding the add-passenger div before the add link.
these are the changes that i have done(and some smoth removing animation though the question did not neeed it)
Check the working demo
Use jquery on() for dynamically rendering dom elements.
$("#addButton").on("click",addPassenger);

Categories