Dynamically add dropdown box in laravel. Javascript and laravel - javascript

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

Related

How to append options to dynamically created select elements with jquery in Laravel blade file

Good day. I have a form in which I can dynamically add groups on input elements. I have select elements among them.
In my controller, I returned the data to populate the select element to the blade file.
After this, I then append the data to the select element using Jquery.
The problem is that, this works for the initial form group (elements), but it does not work for the dynamically generated one.
What could be the cause please? Or is there a better way of doing this?
This are my blade (html) and jquery codes
Blade file
<button id="add_counsel_button" type="button">Add</button>
<h5>Step 3: Case Counsels</h5>
<div id="dynamic_wrapper">
<div class="field_wrapper" id="row1">
<input type="text" style="width:50%!important;display: inline!important;"
name="counsels[]" id="name1" data-number=1 class="form-control counsel-name">
<input type="hidden" name="counsel_id[]" id="id1">
<div class="counsel-list" id="counsel-list1"></div>
<select name="roles[]" style="width:21%!important;display: inline!important;"
class="form-control roles-list">
<option value="#">Select Role</option>
</select>
<select name="representations[]"
style="width:21%!important;display: inline!important;"
class="form-control reps-list">
<option value="#">Select Representation</option>
</select>
</div>
</div>
Jquery:
$(document).ready(function() {
//Setting the value from the controller
var roles = {!! json_encode($roles->toArray()) !!};
var reps = {!! json_encode($representations->toArray()) !!};
$.each(roles, function(i, item) {
$('.roles-list').append($('<option>', {
value: item.id,
text: item.role
}));
}); //want this to be appended to all 'roles-list' classes
$.each(reps, function(i, item) {
$('.reps-list').append($ '<option>', {
value: item.id,
text: item.type
});
});
$(document).on('click', '#add_counsel_button', function() {
i++;
$('#dynamic_wrapper').append('<div class="field_wrapper" id="row' + i +
'"><input type="text" id="name' + i + '" data-number="' + i +
'" style="width:50%!important;display: inline!important;" name="counsels[]" class="form-control counsel-name"><input type="hidden" name="counsel_id[]" id="id' +
i + '"><div class="counsel-list" id="counsel-list' +
i +
'"></div> <select name="roles[]" style="width:21%!important;display: inline!important;" class="form-control roles-list"> <option value="#">Select Role</option></select><select name="representations[]" style="width:21%!important;display: inline!important;"class="form-control reps-list"><option value="#">Select Representation</option></select><a href="javascript:void(0);" class="remove_button" id="' +
i +
'" style="display: inline!important;"title="Remove field"> <span class="fa fa-trash"></span></a></div>'
);
});
});
You are appending the options before appending the select tag. Change the code like below
$(document).ready(function() {
//Setting the value from the controller
var roles = {!! json_encode($roles->toArray()) !!};
var reps = {!! json_encode($representations->toArray()) !!};
roles_str = '';
reps_str = '';
$.each(roles, function(i, item) {
roles_str += '<option value="'+item.id+'">'+item.role+'</option>';
}); //want this to be appended to all 'roles-list' classes
$.each(reps, function(i, item) {
reps_str += '<option value="'+item.id+'">'+item.type+'</option>';
});
$(document).on('click', '#add_counsel_button', function() {
i++;
$('#dynamic_wrapper').append('<div class="field_wrapper" id="row' + i +
'"><input type="text" id="name' + i + '" data-number="' + i +
'" style="width:50%!important;display: inline!important;" name="counsels[]" class="form-control counsel-name"><input type="hidden" name="counsel_id[]" id="id' +
i + '"><div class="counsel-list" id="counsel-list' +
i +
'"></div> <select name="roles[]" style="width:21%!important;display: inline!important;" class="form-control roles-list"> <option value="#">Select Role</option>'+roles_str+'</select><select name="representations[]" style="width:21%!important;display: inline!important;"class="form-control reps-list"><option value="#">Select Representation</option>'+reps_str+'</select><a href="javascript:void(0);" class="remove_button" id="' +
i +
'" style="display: inline!important;"title="Remove field"> <span class="fa fa-trash"></span></a></div>'
);
});
});

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

How to remove dynamically generated fields from div level?

My concept is to create maximum 20 blocks( it contains some input field) on button click "Add", If you tap on "Add" button then new block could be added, that was successfully done. Now i want to remove the block which is created on "Add" button click.
Eg: If user is create 5 block by using in "ADD" button. If user taps on "Minus" button, in Block 2, then Block 2 should be removed from the list and count of the block should be updated correspondingly.
http://www.w3schools.com/code/tryit.asp?filename=FADO51NINJMD
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#commentForm").validate();
});
function add()
{
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
var label = document.createElement('label');
label.innerHTML = '<h5 class="label">Block '+i+'<input type="button" value="Minus" onclick="minus()"></h5>';
divtest.appendChild(label);
var length = $('#Length').clone().attr('id', 'Length' + i).attr('name', 'Length' + i);
var attribute = $('#Attribute').clone().attr('id', 'Attribute' + i).attr('name', 'Attribute' + i);
var column = $('#Column').clone().attr('id', 'Column' + i).attr('name', 'Column' + i);
length.appendTo(divtest);
attribute.appendTo(divtest);
column.appendTo(divtest);
objTo.appendChild(divtest);
i++
}
function minus()
{
}
</script>
</head>
<body>
<form id="commentForm" method="post" action="">
<div id="room_fileds">
Static Field
<input type="text" name="Length" maxlength="2" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field 1 Length" class="form-control required">
<input type="text" name="Attribute" id="Attribute" placeholder="Field 1 Attribute" class="form-control" required>
<select name="Column" id="Column" class="required" >
<option selected value="">Field Column </option>
<option value="1">YES</option>
<option value="2">NO</option>
</select>
</div>
<br><br>
<input class="submit" type="submit" value="Submit1">
<input type="button" value="Add" onclick="add()">
</form>
</body>
</html>
Set id while creating div node
divtest.setAttribute("id", "div" + i);
For minus function pass created id number in onclick
label.innerHTML = '<h5 class="label">Block '+i+'<input type="button" onclick="minus('+i+')" value="Minus"></h5>';
And set minus function as
function minus(_id)
{
var _div_id = "div" + _id;
var _div_elem = document.getElementById(_div_id);
_div_elem.parentNode.removeChild(_div_elem);
}
var i = 1;
$(document).ready(function () {
//$("#commentForm").validate();
});
function add()
{
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.setAttribute("id","div" + i);
var label = document.createElement('label');
label.innerHTML = '<h5 class="label">Block '+i+'<input type="button" onclick="minus('+i+')" value="Minus"></h5>';
divtest.appendChild(label);
var length = $('#Length').clone().attr('id', 'Length' + i).attr('name', 'Length' + i);
var attribute = $('#Attribute').clone().attr('id', 'Attribute' + i).attr('name', 'Attribute' + i);
var column = $('#Column').clone().attr('id', 'Column' + i).attr('name', 'Column' + i);
length.appendTo(divtest);
attribute.appendTo(divtest);
column.appendTo(divtest);
objTo.appendChild(divtest);
i++
}
function minus(_id)
{
var _div_id = "div" + _id;
var _div_elem = document.getElementById(_div_id);
_div_elem.parentNode.removeChild(_div_elem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form id="commentForm" method="post" action="">
<div id="room_fileds">Static Field
<input type="text" name="Length" maxlength="2" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field 1 Length" class="form-control required">
<input type="text" name="Attribute" id="Attribute" placeholder="Field 1 Attribute" class="form-control" required>
<select name="Column" id="Column" class="required" >
<option selected value="">Field Column </option>
<option value="1">YES</option>
<option value="2">NO</option>
</select>
</div><br><br>
<input class="submit" type="submit" value="Submit1">
<input type="button" value="Add" onclick="add()">
</form>
You can just remove the label parent on click. See the minus function content.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#commentForm").validate();
});
function add()
{
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
var label = document.createElement('label');
label.innerHTML = '<h5 class="label">Block '+i+'<input type="button" value="Minus" onclick="minus()"></h5>';
divtest.appendChild(label);
var length = $('#Length').clone().attr('id', 'Length' + i).attr('name', 'Length' + i);
var attribute = $('#Attribute').clone().attr('id', 'Attribute' + i).attr('name', 'Attribute' + i);
var column = $('#Column').clone().attr('id', 'Column' + i).attr('name', 'Column' + i);
length.appendTo(divtest);
attribute.appendTo(divtest);
column.appendTo(divtest);
objTo.appendChild(divtest);
i++
}
function minus()
{
//This is the clicked label, so we remove the parent (the div)
$(this).parent().remove();
}
</script>
</head>
<body>
<form id="commentForm" method="post" action="">
<div id="room_fileds">
Static Field
<input type="text" name="Length" maxlength="2" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field 1 Length" class="form-control required">
<input type="text" name="Attribute" id="Attribute" placeholder="Field 1 Attribute" class="form-control" required>
<select name="Column" id="Column" class="required" >
<option selected value="">Field Column </option>
<option value="1">YES</option>
<option value="2">NO</option>
</select>
</div>
<br><br>
<input class="submit" type="submit" value="Submit1">
<input type="button" value="Add" onclick="add()">
</form>
</body>
</html>
<div class="removePhoneDiv">
<input type="button" value="Add Text Field" id="add_button" >
<ul style="list-style:none;" id="phoneNumberList">
<li class='Textbox1' style="float:left;width:100%;">
<div style=" margin-top: 2%; " class='form-group' id='answerdiv'>
<input type='text' class='input_phone form-control1'>
<img style="float:left;" src="images/close.png" class="remove_phone_number">
</div>
</li>
</ul>
</div>
<script>
var wrapper = $(".form-group");
$("#add_button").click(function (e) {
e.preventDefault();
$("#phoneNumberList").append("<li class='Textbox1'><div class='form-group' id='answerdiv'><input type='text' class='form-control1' ><img src=\"images/close.png\" class=\"remove_phone_number\"></div></li>");
});
$(".removePhoneDiv").on("click", ".remove_phone_number", function (e) {
e.preventDefault();
$(this).parent('div').parent('li').remove();
})
</script>

Clearing an input field on blur

I'm attempting to clear all inputs with the class "new" on blur, but for some reason it just won't work. I've bashed my head at the this for three hours now, which obvious point am I missing? Relevant code below.
UPDATE 2
I tried changing out the switch-case block with corresponding if blocks, and they give the expected result. This eliminates the current problem, but I don't find it to be a viable answer to the original question which is why my origianl code with switch-case doesn't work.
UPDATE 1
After some research and experimenting I've discovered that I can clear all inputs with the class "new" as long as they're not inside my switch-case block. The selector I'm testing with is $('.new'), once inside the switch-case block this gives no visible effect.
#{
ViewBag.Title = "Viser infrastruktur";
Layout = "~/Views/Shared/_SuperOfficeLayout.cshtml";
}
<table class="table table-striped compact hover row-border">
<thead>
<tr>
<th>Produsent</th>
<th>Modell</th>
<th>Serienummer</th>
<th>Firmware</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="manufacturer" placeholder="Produsent" value="" />
<input type="hidden" class="autosave new" name="id" value="" />
<input type="hidden" class="autosave new" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="model" placeholder="Modell" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="serialNumber" placeholder="Serienummer" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="firmware" placeholder="Firmware" />
</div>
</td>
</tr>
#foreach (var infrastructure in Model.Infrastructures)
{
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="manufacturer" placeholder="Produsent" value="#infrastructure.Manufacturer" />
<input type="hidden" class="autosave" name="id" value="#infrastructure.Id" />
<input type="hidden" class="autosave" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="model" placeholder="Modell" value="#infrastructure.Model" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="serialNumber" placeholder="Serienummer" value="#infrastructure.SerialNumber" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="firmware" placeholder="Firmware" value="#infrastructure.Firmware" />
</div>
</td>
</tr>
}
</tbody>
#section SpecializedScripts
{
<script type="text/javascript">
function saveSettings(element, ajaxUrl, ajaxType) {
var fields = $(element).closest('tr').children('td').children('div').children('.autosave');
var abort = false;
var ajaxData = {};
$(fields).each(function () {
abort = ($(this).val() == '' || $(this).val() == null);
backgroundColor = abort == true ? '#d9534f' : '#f9f598';
$(this).css('background-color', backgroundColor).css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
ajaxData[$(this).prop('name')] = $(this).val();
});
if (abort == true) {
return false;
}
$.ajax({
url: ajaxUrl,
type: ajaxType,
data: ajaxData
}).success(function (data, textStatus, jqXHR) {
$(fields).each(function() {
$(this).css('background-color', '#5cb85c').css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
});
switch(data.status)
{
case 'Deleted':
$(element).closest('tr').remove();
break;
case 'Added':
var tableBody = $('tbody');
var html = '<tr>';
for (var field in data.result) {
if (field == 'id' || field == 'superOfficeCustomerId')
{
html += '<input type="hidden" class="autosave" name="' + field + '" value="' + data.result[field] + '" />';
}
else {
html += '<td>'
+ '<div class="control-group">'
+ '<input type="text" class="col-md-12 autosave form-control" name="' + field + '" value="' + data.result[field] + '" />'
+ '</div>'
+ '</td>';
$('input.new[name=' + field + ']').val('');
}
}
html += '</tr>';
$(tableBody).append(html);
case 'Modified':
$(fields).each(function () {
$(this).val(data.result[$(this).prop('name')]);
});
break;
}
}).fail(function () {
});
}
$(document).on('blur', 'input.autosave', function () {
saveSettings($(this), '/Link/SaveInfrastructure', 'POST');
});
$(document).on('change', 'input.new', function () {
});
</script>
}
Something like this should work:
$('input.new').on('blur', function() { $(this).val(''); $(this).text(''); });
just make sure the input exists when you bind the event otherwise you can do:
$(document).on('blur', 'input.new', function() { $(this).val(''); $(this).text(''); });
For vanilla JavaScript, you can use
<input onBlur={(event) => { event.target.value = ''; }} />

Attempting to print out user input using jQuery

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....!!

Categories