i am creating a select list dynamically where user can add options after adding select list. Below is my code
<script type="text/html" id="select_field">
<div class='row'>
<div class='col-md-3'><label>Select list name</label>
<div class='form-group'><input type='text' class='form-control select_name'></div>
</div>
<div class="col-md-3">
<label for=""></label>
<select name="" class="form-control select-list" ></select>
</div>
<div class="append_list"></div>
<a class="btn btn-primary pull-right add_values">Add Values</a>
</div>
</script>
JS:
Below JS adds an text field with 2 buttons option to add / remove field to the select list
$form_holder.on('click','.add_values', e => {
var html = "<div class='clearfix'></div>" +
"<div class='col-md-4'><input type='text' class='form-control add_select_option' name='add_value' ><br>" +
"<a class='add_option btn btn-default' value='Add' >Add</a>" +
"<a class='remove_option btn btn-danger' value='Remove' >Remove</a><br></div>";
let $target = $(e.target);
let $value= e.target.value;
let $div = $target.closest('.row').find('.append_list');
$div.append(html);
});
Below Code adds an option to the select list :
$form_holder.on('click','.add_option', e => {
let $target = $(e.target);
console.log($target);
let $value= e.target.value;
let $value_toadd = $target.closest('.col-md-4').find('.form-control').val();
console.log($value_toadd);
let $select_list = $target.closest('.row').find('.select-list');
$($select_list).append($('<option>', {
value: $value_toadd,
text: $value_toadd
}));
});
Now values are added successfully , but my problem is that ::
if I have added value using one text field and click on add button again it embeds new value to the select list using the same text field, how do i uniquely identify each of the text fields while adding entries to select list , please advise .
I also have to use same unique value to remove the entry from the select list
You can give custom attribute to your inputs i.e : data-id . Then , whenever user click on add button check if the custom attr is already present in one of the option of select if yes show some message else add new data to selects .
Demo Code :
var $form_holder = $("form")
$form_holder.on('click', '.add_values', e => {
let $target = $(e.target);
let $value = e.target.value;
let $div = $target.closest('.row').find('.append_list');
//add custom attr
var html = "<div class='clearfix'></div>" +
"<div class='col-md-4'><input type='text' class='form-control add_select_option' name='add_value' data-id='" + $div.find(".col-md-4").length + "'><br>" +
"<a class='add_option btn btn-default' value='Add' >Add</a>" +
"<a class='remove_option btn btn-danger' value='Remove' >Remove</a><br></div>";
$div.append(html);
});
$form_holder.on('click', '.add_option', e => {
let $target = $(e.target);
let $value = e.target.value;
var data_id = $target.closest('.col-md-4').find('.form-control').data('id'); //get custom attr added
let $value_toadd = $target.closest('.col-md-4').find('.form-control').val();
let $select_list = $target.closest('.row').find('.select-list');
//check if select doesn't have that data-id
if ($select_list.find("option[data_value=" + data_id + "]").length <= 0) {
//then only add
$($select_list).append($('<option>', {
data_value: data_id,
value: $value_toadd,
text: $value_toadd
}));
} else {
console.log(" already there ")
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class='row'>
<div class='col-md-3'><label>Select list name</label>
<div class='form-group'><input type='text' class='form-control select_name'></div>
</div>
<div class="col-md-3">
<label for=""></label>
<select name="" class="form-control select-list"></select>
</div>
<div class="append_list"></div>
<a class="btn btn-primary pull-right add_values">Add Values</a>
</div>
</form>
Related
What I want is, I want to generate a new input type = text whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
Couple of problem in your code.
Use slice(-1) to get last character of id. It's remove your dependency using hardcode substr(13,... and you can use that value to increase new generated id by +1 .
Check length for input using $('.form-group').find('input').length < 5 which check the length of input inside form-group class and user only able to add 5 inputs.
Finally don't forgot to append your generated element on form-group class using $('.form-group').append(tr); .
I also add example to delete added tr using minus class.
Example:
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
if ($('.form-group').find('input').length < 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.slice(-1));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'>Remove</i></div></td></tr>";
}
$('#yourid').append(tr);
} else {
alert("warning........")
}
}
$(document).on('click', 'div.minus', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group" id="yourid">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true">icon</i>
</div>
</div>
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that div as following:
$('#dvDVRdata1').append(tr);
The thing is you need to append the element, which you did not do in the code in your question.
As for remove, you also have not done it in your question yet. Here's the example of add and remove.
$(document).ready(function(){
$('.add').on('click', function () {
addDynamicTextbox();
});
$('.del').click(function (e) {
deleteDynamicTextbox(e);
});
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems != 5) {
var formGroup = $('.form-group');
var elem = `<div class="dvDVRdata" id="dvDVRdata${numItems+1}">
<label for="txtDVRAddress${numItems+1}">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress${numItems+1}" runat="server" />
</div>`;
formGroup.append(elem);
}
}
function deleteDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems > 1) {
$(`#dvDVRdata${numItems}`).remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/js/all.min.js" integrity="sha512-rpLlll167T5LJHwp0waJCh3ZRf7pO6IT1+LZOhAyP6phAirwchClbTZV3iqL3BMrVxIYRbzGTpli4rfxsCK6Vw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<div class="dvDVRdata" id="dvDVRdata1">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" />
</div>
</div>
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<div class="del">
<i class="fa fa-minus" aria-hidden="true"></i>
</div>
I have an ajax function that is actually working well but I don't know how to use it on the HTML.
What I need to achieve is that basically, attached to each checkbox there is a certain number of questions. They're all selected by default but, if I deselect one of them, the number of questions of that particular checkbox should be removed.
The function I am using is working fine (in the console) but I couldn't find a way to use it on the HTML.
I post some code for more clarity.
let subjectId;
$("#selection").on("change", function () {
const selectSubjBtn = document.getElementById("select_subject");
subjectId = $(this).children(":selected").val();
let labelText = gettext(
"Select the number of questions by moving the button to the right or left!"
);
let title = gettext("Select Number of Questions");
let selectedQuestionsNum;
$.ajax({
type: "GET",
url: "/quiz/ajax_questions/" + subjectId,
success: function (response) {
let questions = response.questions;
let topics = response.topics;
let topicQuestionNum = response.question_num_list;
if (topicQuestionNum != 0) {
let topicsObj = topics.map(function (e, i) {
return [e, topicQuestionNum[i]];
});
let subTopicHtml;
// $("#sub_topic_box").append(
// '<input class="form-check-input mt-0 ms-3" type="checkbox" value="" id="selectAll" checked aria-label="Checkbox for following text input">'
// );
topicsObj.forEach((el) => {
subTopicHtml = '<div class="row mt-3">';
subTopicHtml += '<div class="input-group mb-3">';
subTopicHtml += '<div class="input-group-text">';
subTopicHtml +=
'<input class="form-check-input selectedTopic mt-0" type="checkbox" value="' +
el[1] +
'" id="' +
el[0].id +
'" checked aria-label="Checkbox for following text input">';
subTopicHtml += "</div>";
subTopicHtml +=
'<input value="' +
el[0].name +
'" type="text" class="form-control" aria-label="Text input with checkbox" disabled>';
subTopicHtml +=
'<span class="input-group-text">' + el[1] + "</span>";
subTopicHtml += "</div></div>";
$("#sub_topic_box").append(subTopicHtml);
});
$("#selectAll").click(function () {
if (this.checked) {
$(":checkbox").each(function () {
this.checked = true;
});
} else {
$(":checkbox").each(function () {
this.checked = false;
});
}
});
let selectedQuestionTopic =
document.getElementsByClassName("selectedTopic");
let selectedCheckboxes = [];
let selectedBoxesNum;
function selectedTopics() {
selectedCheckboxes = [];
let checked = document.querySelectorAll(
"[type='checkbox']:checked"
);
checked.forEach(function (el) {
selectedCheckboxes.push(Number(el.value));
selectedBoxesNum = selectedCheckboxes.reduce(
(pv, cv) => pv + cv,
0
);
});
console.log(selectedBoxesNum);
return selectedBoxesNum;
}
selectedQuestionTopic.forEach(function (el) {
el.addEventListener("change", function () {
selectedTopics();
});
});
quizBox.innerHTML = `
<div class="h5 mb-3">${title}</div>
<div class="row mt-3">
<label for="customRange1" class="form-label">${labelText}</label>
<div class="input-group">
<input type="text" class="form-control" id="textInput" value="${selectedQuestionsNum}" oninput="${selectedQuestionsNum};" >
<span class="input-group-text">on ${
questions.length
}</span>
<input type="range" name="question_number" class="form-range mt-3" min="0" max="${
questions.length
}" value="${
questions.length
}" id="customRange1" onchange="updateTextInput(this.value);"
oninput="updateTextInput(this.value);">
<div class="mt-3">
<button class="btn btn-primary" id="select_subject">${gettext(
"Select Subject"
)}</button>
</div>
</div>
</div>
`;
} else {
quizBox.innerHTML = `
<div class="h5 mb-3">${title}</div>
<div class="row mt-3">
<label for="customRange1" class="form-label">${labelText}</label>
<div class="input-group">
<input type="text" class="form-control" id="textInput" value="${
questions.length
}" oninput="customRange1.value=amount.value" >
<span class="input-group-text">on ${
questions.length
}</span>
<input type="range" name="question_number" class="form-range mt-3" min="0" max="${
questions.length
}" value="${
questions.length
}" id="customRange1" onchange="updateTextInput(this.value);"
oninput="updateTextInput(this.value);">
<div class="mt-3">
<button class="btn btn-primary" id="select_subject">${gettext(
"Select Subject"
)}</button>
</div>
</div>
</div>
`;
}
},
error: function (error) {
console.log(error);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Basically, topicQuestionNum variable is an array, which I sum in the selectedTopics function and, in case I uncheck one of the checkboxes, it gives me a new result.
What I need to do, is updating also the result in the input field I create with the ajax request down below.
I tried in many different ways but I don't have much experience, especially with Javascript.
I'm doing a task sheet. I dynamically add items to the list along with the delete button, but the button is not displayed. Why?
I can certainly write the code differently, but why does this code not work?
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var del = $("<input type='button' value='X'></input>").text();
//var item = $("<li></li>").text(text + del);
var item = $("<li></li>").text(text + del); // DONT WORK! WHY?
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>
With this code I want to achieve this result. But I can not. Who will help explain where I'm wrong?
<li>Some Text <input type='button' value='X'></input></li>
In your code $("<input type='button' value='X'></input>").text() returns undefined.
Try this:
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var delHTML = "<input type='button' value='X'></input>";
var item = $("<li></li>").html(text + delHTML);
$("ul").append(item);
}
});
});
Your issue stemmed from not appending the delete button to the list item reference. As it's written I can add a list item to the ul but the button's delete button element was never attached to the list item.
Second, I removed .text() from var del = $("<input type='button' value='X'></input>").text();.
Here's my full solution.
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
// Creating elements
var deleteBtn = $("<input type='button' value='X'></input>");
var item = $("<li></li>").text(text);
// Appending elements
item.append(deleteBtn);
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>
Hi I am trying to create an invoicing system. I have a form that I add fields to for every line item and that works I can add and remove the form fields. My problem is I dont know a way to get the price from the prepended line item and add it up to get a subtotal.
this is the html nothing interesting here
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div>
<div class="line-item-box quantity">
<label>Qty:</label>
<input type="text" name="quantity" id="quantity">
</div>
<div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Here is the jquery
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="price-row">' + subtotal + '</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
return false;
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
So I would like to add up the price var for each line item which will be added to the dom dynamically and then display it with the subtotal var.
Is this possible? If so how can I do this?
For a total use a each loop and sum each parsed value of the price,put this in a function and trigger it each time you update the list of items
js:
function price_subtotal(){
var subtotal = 0;
$('.price-saved').each(function(i,v){
subtotal+= parseFloat($(v).text().replace('$',''));
});
$('.subtotal').html(subtotal);
}
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="subtotal price-row">0</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
price_subtotal();
return false;
});
$(document).on('click', '.remove-btn', function() {
$(this).closest('.line-item').remove();
price_subtotal();
});
});
DEMO
I am making my way through building a system that uses a bit more JavaScript than I am used to, so please excuse my naivety with the whole mess!
I have a form with a drop down list, and four input boxes:
When a user selects Item A from the drop list, two fields are populated with dynamic data from my database. If they select Item B, the two fields are repopulated with data. This is working just as I'd like.
I have a button/link below that div that allows the user to "add" another div below it on-the-fly (no page refresh), containing another drop list and four input boxes. This is working okay, too. The user can select an item from the drop list and the input boxes change accordingly.
The problem comes when the user tries to add a third (or any number over the initial add) div to the lot. The drop list will alter the content of the firstly added div but never affects the subsequent divs. I am guessing this has something to do with ids and can imagine what is happening in English but cannot put it into anything that works programmatically (due to my limited JS knowledge).
I tried looping through the second instance of the code to increment #item_select, #item_details and #item_price, but doing this is obviously not the way to make it work as it hasn't helped! lol
Here is the code that I've written so far:
<div class="row">
<div class="input-field white col s3">
<select class="browser-default" id="item_select1" name="item_select1">
<option disabled selected value="">
Choose an item
</option>
<option data-description1=
"This is the detail for the One Page - Basic item."data-price1="500" value="1">
Basic - One-page Site
</option>
<option data-description1=
"This is the detail for the Additional Basic Pages item."data-price1="100" value="2">
Basic - Additional Page(s)
</option>
</select>
</div>
<div class="input-field white col s4">
<input class="validate" id="item_details1" name="item_details1" type="text">
</div>
<div class="input-field white col s2">
<input class="validate" id="item_price1" name="item_price1" onkeyup="sum1();" type="text" value="_"> <label for="item_price1">Price</label>
</div>
<div class="input-field white col s1">
<input class="validate" id="item_qty1" onkeyup="sum1();" type="text"> <label for="item_qty1">Qty</label>
</div>
<div class="input-field white col s2">
<input class="validate" id="item_total1" type="text" value="_">
<label for="item_total1">Total</label>
</div>
</div>
<div id="content"></div><i class="tiny material-icons" onclick="addRow()" style="margin-bottom:50px;">add_circle_outline</i><a onclick="addRow()">add another item</a>
<script>
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<div class="row"><div class="input-field col s3"><select class="browser-default" name="item_select2" id="item_select2"><option value="" disabled selected>Choose an item<\/option><option data-price2="500" data-description2="This is the detail for the One Page - Basic item." value="1">Basic - One-page Site<\/option><option data-price2="100" data-description2="This is the detail for the Additional Basic Pages item." value="2">Basic - Additional Page(s)<\/option><\/select><\/div><div class="input-field white col s4"><input id="item_details2" name="item_details2" type="text" class="validate"><\/div><div class="input-field white col s2"><input id="item_price2" name="item_price2" type="text" class="validate" value="_" onkeyup="sum2();"><\/div><div class="input-field white col s1"><input id="item_qty2" type="text" class="validate" onkeyup="sum2();"><\/div><div class="input-field white col s2"><input id="item_total2" type="text" class="validate" value="_"><\/div><\/div>\
<i class="tiny material-icons" onclick="removeRow(this)">remove_circle<\/i><a onclick="removeRow(this)" style="color:red;"> remove above row<\/a>';
document.getElementById('content').appendChild(div);
}
function removeRow(input) {
document.getElementById('content').removeChild(input.parentNode);
}
$(document).ready(function() {
$("#item_select1 option").filter(function() {
return $(this).val() == $("#item_details1").attr('data-description1');
return $(this).val() == $("#item_price1").attr('data-price1');
}).attr('selected', true);
$("#item_select1").live("change", function() {
$("#item_details1").val($(this).find("option:selected").attr("data-description1"));
$("#item_price1").val($(this).find("option:selected").attr("data-price1"));
});
});
function sum1() {
var txtFirstNumberValue = document.getElementById('item_price1').value;
var txtSecondNumberValue = document.getElementById('item_qty1').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('item_total1').value = result;
}
}
$("#item_select1").change(function() {
$('#item_qty1').val('');
$('#item_total1').val('');
});
$(document).ready(function() {
$("#item_select2 option").filter(function() {
return $(this).val() == $("#item_details2").attr('data-description2');
return $(this).val() == $("#item_price2").attr('data-price2');
}).attr('selected', true);
$("#item_select2").live("change", function() {
$("#item_details2").val($(this).find("option:selected").attr("data-description2"));
$("#item_price2").val($(this).find("option:selected").attr("data-price2"));
});
});
</script>
Any help would be appreciated. Again, my JavaScript skills are not the greatest, so a very straightforward answer (especially if code samples are involved) would be even more appreciated! :)
I have a few suggestions for you:
1) You have created the first row in HTML, and the others via JavaScript. Do it all in one place, this will make maintain your code easier later on. In this case, I have done it all in JavaScript.
2) Use class selectors (.item_qty) instead of IDs (#item_qty1), and then use jQuery Traversing functions to find the tags that you need. Here I used .closest() and .find() a lot.
3) I prefer to separate the JS event handlers from HTML code, making use of event delegation instead of onclick and such.
4) The .live() event handler has been deprecated and removed since jQuery v1.9. You can use .on() in its place.
Here's the modified code using these suggestions (JSFiddle):
<div id="content"></div>
<i class="tiny material-icons addRowLink" style="margin-bottom:50px;">add_circle_outline</i><a class="addRowLink">add another item</a>
<script>
$(document).ready(function() {
addRow();
$('#content').on("change", 'select.productSelect', function() {
$(this).closest('.row').find(".item_details").val($(this).find("option:selected").attr("data-description"));
$(this).closest('.row').find(".item_price").val($(this).find("option:selected").attr("data-price"));
$(this).closest('.row').find(".item_price").trigger("change");
});
$('#content').on('change keyup', "input.item_qty, input.item_price", function() {
sum(this);
});
$(".addRowLink").on('click', function() {
addRow();
});
$('#content').on('click', '.removeRowLink', function() {
removeRow(this);
});
});
function addRow() {
rowNumber = $('#content .row').length + 1;
var arr = [
{value: '', disabled: true, selected: true, text: 'Choose an item'},
{value: '1', "data-description": "This is the detail for the One Page - Basic item.", "data-price": 500, text: 'Basic - One-page Site'},
{value: '2', "data-description": "This is the detail for the Additional Basic Pages item.", "data-price": 100, text: 'Basic - Additional Page(s)'},
];
select = $('<select class="browser-default productSelect" name="item_select' + rowNumber + '" id="item_select' + rowNumber + '"></select>');
$(arr).each(function() {
select.append($("<option>", this).text(this.text));
});
var newRow = $('<div class="row">').append(select);
var newhtml = '';
newhtml += ' <div class="input-field white col s4"> \r\n';
newhtml += ' <input class="validate item_details" name="item_details' + rowNumber + '" type="text" /> \r\n';
newhtml += ' </div> \r\n';
newhtml += ' <div class="input-field white col s2"> \r\n';
newhtml += ' <input class="validate item_price" name="item_price' + rowNumber + '" type="text" value="_" /> <label for="item_price' + rowNumber + '">Price</label> \r\n';
newhtml += ' </div> \r\n';
newhtml += ' <div class="input-field white col s1"> \r\n';
newhtml += ' <input class="validate item_qty" name="item_qty' + rowNumber + '" type="text" /> <label for="item_qty' + rowNumber + '">Qty</label> \r\n';
newhtml += ' </div> \r\n';
newhtml += ' <div class="input-field white col s2"> \r\n';
newhtml += ' <input class="validate item_total" name="item_total' + rowNumber + '" type="text" value="_" /> \r\n';
newhtml += ' <label for="item_total' + rowNumber + '">Total</label> \r\n';
newhtml += ' </div> \r\n';
newRow.append(newhtml);
if (rowNumber > 1) {
newRow.append('<i class="tiny material-icons removeRowLink">remove_circle</i><a class="removeRowLink" style="color:red;"> remove above row</a>');
}
$('#content').append(newRow);
}
function removeRow(t) {
$(t).closest('.row').remove();
}
function sum(t) {
row = $(t).closest('.row');
var price = row.find('.item_price').val();
var qty = row.find('.item_qty').val();
var result = parseInt(price) * parseInt(qty);
if (!isNaN(result)) {
row.find('.item_total').val(result);
} else {
row.find('.item_total').val("_");
}
}
</script>
Try this, its a short proof of concept in a nutshell. Should bring you on the right track.
jsfiddle goes here
(function(){
'use-strict';
//This stores data for the select input.
//You may extend the select input with additional option field(s) to match this.
var data = [];
data.push({id : 0, text : 'one', price : 500});
data.push({id : 1, text : 'additional', price : 100});
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', add, false);
var select = document.getElementsByTagName('select');
select[0].addEventListener('change', change, false);
//1. is first input type text and 2. is second one
function change() {
var divChildElements = this.parentNode.children;
divChildElements[1].value = '';
divChildElements[2].value = '';
divChildElements[1].value = data[this.value].text;
divChildElements[2].value = data[this.value].price;
}
//This builds your select and input fields
function add() {
var docFrag = document.createDocumentFragment();
var div = document.createElement('div');
var select = document.createElement('select');
var divs = document.getElementsByTagName('div');
var lastDiv = divs.length-1;
var inputs = 2;
select.addEventListener('change', change, false);
for(var i=0;i<data.length;i++) {
var option = document.createElement('option');
option.value = data[i].id;
option.appendChild(document.createTextNode(data[i].text));
select.appendChild(option);
}
div.appendChild(select);
for(var i=0;i<2;i++) {
var input = document.createElement('input');
div.appendChild(input);
}
docFrag.appendChild(div);
divs[lastDiv].parentNode.insertBefore(docFrag, divs[lastDiv].nextSibling);
}
}());