I've created few buttons, and when clicked I want to affect the final cost, working but not as it should be. The button has a value and the final value of cost doesn't work, can someone let me know what I'm doing wrong?
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].click) {
total += parseFloat(input[i].value);
}
}
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
But when I pick one, the final price won't work perfectly. is displaying a different number! can some help me?
Attach the click event to all the buttons and add the cost on every click like the snippet below shows.
NOTE : If you want to add the cost just one time by button you could disable the button immediately after the click using :
this.setAttribute('disabled','disabled');
Hope this helps.
var products = document.querySelectorAll(".buttonBg");
for (var i = 0; i < products.length; i++) {
products[i].addEventListener("click", totalIt);
}
function totalIt() {
var total = document.querySelector("#total");
var currentVal = parseInt( total.innerText );
var new_val = parseInt( this.value );
if( this.classList.contains('clicked') ){
total.innerText = ( currentVal - new_val ).toFixed(2);
}else{
total.innerText = ( currentVal + new_val ).toFixed(2);
}
document.querySelector("#total2").innerText = total.innerText;
this.classList.toggle('clicked');
}
.clicked{
color: green;
}
<div class="priceWrapper">
<h3 class="priceText1">$<span id="total">0.00</span></h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
<h3 class="priceText1">$<span id="total2">0.00</span></h3>
I have adapted your code to make this work see below
Note below i have added id's to the product buttons.
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" id="product1" name="product" value="25.00" type="button">
Producto 3
</button>
</label>
<label>
<button class="buttonBg" id="product2" name="product" value="10.00" type="button">
Producto 4
</button>
</label>
</form>
</div>
Then i have modified your code
//
// this will be the element clicked so just add it, as below
//
function addProduct() {
el = this;
total += parseFloat(el.value);
total_el.innerText = "$" + total.toFixed(2);
};
//
// Cache your total get a reference to the total element (faster!)
// when you write your code don't keep doing stuff when it can be done
// once - speed is everything and as you write more complex stuff
// doing it write from day one will pay off in your work (toptip)
//
var total = 0;
var total_el = document.querySelector(".priceText1");
//
// Bind up the click event
//
document.getElementById('product1').onclick = addProduct;
document.getElementById('product2').onclick = addProduct;
And here you can see the end result
https://jsfiddle.net/64v3n1se/
To scale this you would add the click handler using a class and a loop but for simpleness i have... kept it simple.
Because during your calculation you are getting all button's values and add them up so whenever the button is clicked you calculate the sum of the values of the buttons.
Your way of thinking right now, as far as I can tell, is wrong.
You can change your html code and script code like this.
With this way we are passing object of button to the function and we increase the global total variable within the function. Later on you change the dom.
var total = 0;
function totalIt(obj) {
total = total + parseFloat(obj.value);
document.querySelector(".priceText1").innerText = "$" + total.toFixed();
}
And pass the object of button in the html with
<button class="buttonBg" name="product" value="10.00" type="button" onclick="totalIt(this)">
Related
I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.
i want to update rooms rate which is shown on screen shot. when i click on edit room rate it hide existing button and show text box containing existing room value . when i fetched this data using while loop in php it works only on first element. please help me
used javascript as bellow
<script>
function hide_editbtn()
{
var rmrate = document.getElementsByClassName("roomrate");
for(var i = 0; i < rmrate.length; i++){
rmrate[i].style.display = "none";
rmrate[i].disabled = true;
}
var updbtn = document.getElementsByClassName("updateratebtn");
for(var i = 0; i < updbtn.length; i++){
updbtn[i].style.display = "none";
rmrate[i].disabled = true;
}
}
function show_editbtn()
{
var rmratelink = document.getElementsByClassName("roomratelink");
for(var i = 0; i < rmratelink.length; i++){
(function(index){
rmratelink[i].onclick = function(){
document.getElementById("roomrate").style.display="block";
document.getElementById("roomrate").disabled = false;
}
})(
}
}
</script>
Used html Content as bellow
<div class="card-stacked order-sm-1 newelmnt">
<div class="card-body pt-sm-0 pb-0 px-0 pr-sm-6 pr-md-8">
<p> </p>
<h3 class="card-title font-weight-normal text-truncate elconnt">
Ac Room
</h3>
<div class="d-flex align-items-baseline price mb-1">
<span class="d-block text-primary font-weight-500 display-5 mr-1">Rs.<label id="hotelroomrate">1500</label> <span class="btn-group-toggle roomratelink" data-toggle="buttons" onclick="show_editbtn()" id="roomratelink" style="margin-top:10px;">
<label class="btn btn-xs btn-outline-primary mb-2">
<input type="checkbox"> Edit Room Rate
</label>
</span>
</span>
<label class="sr-only" for="user-name"> </label>
<input type="text" class="form-control roomrate" id="roomrate" aria-describedby="user-name" placeholder="Modify Room Rate" style="width:180px;padding-right:10px;"/>
<span class="btn-group-toggle updateratebtn" data-toggle="buttons" id="updateratebtn" >
<label class="btn btn-outline-primary mb-2" style="background:#512da8;color:#fff;margin-top:5px;">
<input type="checkbox"> Submit
</label>
</span>
</div>
</div>
</div>
screen shot
i want to update rooms rate which is shown on screen shot. when i click on edit room rate it hide existing button and show text box containing existing room value . when i fetched this data using while loop in php it works only on first element. please help me
You could try removing the listener because you just wanna show the buttons.
Second, use class instead of an ID for the elements. IDs are unique. So when you loop it only the first occurence will be handled.
Make the #roomrate ID a class .roomrate.
for(var i = 0; i < rmratelink.length; i++){
let btn = rmratelink[i].getElementsByClassName('roomrate')[0];
btn.style.display="block";
btn.disabled = false;
}
Hope it helps
I have a php loop that call products from database. there is a quantity input field and a ajax add to cart button.
Now ajax add cart function get product id and quantity from the add cart link data attribute. So I want that when I change the quantity field value the add cart link data-quantity will changed automatically. So I can add sent the product quantity to cart.
I tried to do this but unfortunately its change all products quantity on click, because of same class. there is any why to do this that only change the quantity where I clicked?
maybe product id class work here? but how I set a dynamic product id in jquery?
here is my code:
HTML
<div class="row">
<div class="col-md-4">
<img src="img1.jpg" /><br />
<h2>Product 1</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img2.jpg" /><br />
<h2>Product 2</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img3.jpg" /><br />
<h2>Product 3</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img4.jpg" /><br />
<h2>Product 4</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
</div>
Jquery
<script>
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$('a.add-to-cart').attr('data-quantity', newVal);
$('.input').val(newVal);
});
});
</script>
CodePen: https://codepen.io/alshedupur/pen/KmMxJv
Please don't push minus before give me a solution. Maybe you know this, but I don't know. If you share your knowledge it will help me and maybe others too.
You use selector that matches all inputs as they share the class, you can either push an unique id per item or you can use selector to find only items within the same container.
E.g.
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var $parent = $button.parent();
var oldValue = $parent.find('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$parent.find('a.add-to-cart').attr('data-quantity', newVal);
$parent.find('.input').val(newVal);
});
});
I would like to know how can I create textboxes and insert data at page load.
What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.
I have an array string from an ms sql database that looks something like this
test,test;bla;bla2;test44;test55;test66
I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:
I don't know how to do it using the code below.
Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.
THANKS
SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0
<script type='text/javascript'>//<![CDATA[
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
});
//]]>
</script>
<script id="template_add_form" type="text/template">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</script>
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
FORM SUBMIT CODE:
<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>
CALLING IT VIA CLASSIC ASP:
if strComp(Request.Form("action"), "submit")= 0 then
Response.write("IT WORKS")
end if
Here is a solution that works :
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
formArray = [ ], // init array enpty
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
$('#template_add_form').remove();
});
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
<div id="template_add_form" type="text/template" style="display: none;">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</div>
</form>
</body>
Here's what I changed to your code :
Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :
<div id="template_add_form" type="text/template" style="display: none;">
Initialized array empty, so that we can put our own first line : formArray = [ ],
Created a function to add a string in the form :
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
At the end, I added some example data, then pushed an empty line and updated the form :
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :
$('#template_add_form').remove();
To be able to do that, I cloned it entirely at start :
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
I have a set of number fields, each with a class "product-quantity", and a set of empty divs. the number fields are set with a data-attr small, medium, and goes up to 5xl. The empty div's are set with a data-attr small, medium, and goes up to 5xl as well because the small number field is associated with the small div and so one.
When you increase or decrease the number inside the small number field a div "small" should insert after the empty div with the attr small.
When you increase or decrease the number inside the medium number field a div "medium" should insert after the empty div with the attr medium.... and so on
additionally, all of the above belongs to a product x container, and there are multiple products on a page.
I have this jsfiddle that simulates what I am trying to do:
http://jsfiddle.net/7PhJZ/25/
however, right now when I add/subtract a number to the small number fields, it adds/subtracts a div to both the empty small/ medium div as well as in both products. and same for the medium.
I am having a hard time trying to associate which number field belongs to which empty div, which belongs to which product.
html:
<div id="product-1">
<div class="size-field">
<div id="size-label">
s
</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small" min="0"
max="9999" data-product-id="1">
</input>
</div>
</div>
<div id="size-label">
m
</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="1">
</input>
</div>
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
<br clear="all">
<div id="product-2">
<div class="size-field">
<div id="size-label">
s
</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small" min="0"
max="9999" data-product-id="2">
</input>
</div>
</div>
<div id="size-label">
m
</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="2">
</input>
</div>
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
js:
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'}).insertAfter($("[data-size]"));
}
});
$('.product-quantity').on('change', function () {
var val = $(this).val(),
ele = $(this).closest('[id^="product"]').find('[data-size="'+this.name+'"]');
ele.nextUntil('[data-size]').remove();
for (var i = 0; i < parseInt(val); i++) {
$('<div/>', {
'class': 'name-number-field'
}).insertAfter(ele);
}
});
FIDDLE
EDIT:
Based on the comments, what you're really trying to do is just add one if the value increments, and remove the last if the value decrements, and for that the approach would be somewhat different:
$('.product-quantity').each(function() {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
ele = $(this).closest('[id^="product"]').find('[data-size="'+this.name+'"]'),
inc = val >= old;
if (inc) {
$('<div/>', {
'class': 'name-number-field'
}).insertAfter(ele);
}else {
$('.name-number-field', ele.parent()).last().remove();
}
$(this).data('val', this.value);
});
FIDDLE
Make Use of your data-product-id and hook the textbox's parent and target the required elements.
Try this,
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'})
.insertAfter($(this).parents('#product-' + $(this).data('product-id')).find("[data-size]"));
}
});
DEMO
Edit:
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'})
.insertAfter($(this).parents('#product-' + $(this).data('product-id')).find("[data-size='"+ $(this).attr('name') +"'][data-size]"));
}
});
NEW - DEMO