Here is my code i want to append data based on all three textbox if textbox value is 2 and textbox2's value is 3 and textbox3's value is 1 the The result will be 2 apple 3banans and 1 cherry and user can also remove items with textbox value
I have tried to make this code but it is removing all items could you please help me to solve this problem
$(".change_qty").change(function(){
var total = $(this).val();
var oldLength = $(".box > span").length;
var change = total - oldLength;
var data_text= $(this).data("text");
if (change > 0) {
for (i = 0; i < change; i++) {
$(".box").append(`<span >${data_text}<br /></span>`);
}
}
else {
change = Math.abs(change)
$( ".box > span" ).each(function( index ) {
$(this).remove();
if (index == (change -1)) {
return false;
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>
$(".box > span").length does not regard your different input types. It might be easier to clear everything and recreate the whole output on change. That way the entries also keep the order of input.
$(".change_qty").change(function(){
//REM: Remove all entries
$(".box").empty();
//REM: Recreate all entries
$(".change_qty").each(function(){
let tThis = $(this);
let tText = tThis.data('text');
let tQuantity = Math.abs(tThis.val());
//REM: Append quantity of entries to .box
for(let i=0, j=tQuantity; i<j; i++){
$(".box").append(`<span >${tText}<br /></span>`)
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>
Related
My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>
I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.
I have 8 different text fields in my form, it's a part of customer bill.
Here it is
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty">
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation">
......
up to 8
From this I want to show the sum of all the values as total value
<span>Total extra cost:1678</span>
It should be changed when the values of any text field is changed, so how can I do it perfectly using keyup event?
UPDATE
I have attached an onkeyup event to each textfield
`onkeyup="findSum(this.value)"'
and i am using a global array for store the input values var extras=[]
function findSum(value)
{
if(value!=''){
console.log(value);
extras.push(parseInt(value));
if(extras!='')
$('#extratotal').text(extras.reduce(getSum));
else $('#extratotal').text('0');
}
}
But its not worked well
You can get SUM of all inputs that have form-control class on keyup event like this:
$('input.form-control').on('keyup',function() {
var total = 0;
$('input.form-control').each(function(){
if (this.value == ''){
total += parseInt(0);
}else{
total += parseInt(this.value);
}
});
$('#total').val(total);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" >
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" >
<input type="text" name="other" class="form-control" placeholder="other" >
Total extra cost: <input id="total" >
You can use the target.value property of the event passed to the key listener - this will give you the value of the input field:
document.addEventListener('input', 'keyup', function(e) {
// use e.target.value here
}
Just add this to a running total and update the text inside the listener function.
I have defined in JavaScript instead of jQuery. Try it..
<script>
function sum()
{
var sum = 0;
var array_field = document.getElementsByClassName('sum_field');
for(var i=0; i<array_field.length; i++)
{
var value = Number(array_field[i].value);
if (!isNaN(value)) sum += value;
}
document.getElementById("total").innerHTML = sum;
}
</script>
<body>
<input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()">
<input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()">
<p>Total:<span id="total">0</span></p>
</body>
I currently have this html code:
Add More Field
<div id="addmore">
<ul class="jcform" id="countme">
<li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>
<li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>
</ul>
</div>
Total: <div id="displaytotalscore"></div>
Below is my javascript:
function removeme(numm) {
document.getElementById('remove'+numm+'').remove();
}
function addmore() {
var top_level_div = document.getElementById('addmore');
var count = top_level_div.getElementsByTagName('ul').length;
var ul = document.createElement('ul');
ul.className = 'jcform';
ul.id = 'remove' + count;
var tbl1 = '<li><input class="form-control" id="field1" name="cname[]" type="text"
value=""/></li>
<li><input class="form-control" id="fieldpoints1" name="cpoints[]"
type="text" value=""/></li>
<li><a href="#" class="btn btn-danger" onclick="removeme(' + count + ')">
Removed</a></li>';
ul.innerHTML = tbl1;
document.getElementById('addmore').appendChild(ul)
}
What i want to achieve is, when a user enters values in the text fields id="score", i want to display the total sum in the div id="displaytotalscore". I am not sure how to use onchange event here.
Ok here's the jsfiddle link http://jsfiddle.net/41fw2c4x/
document.querySelector("#score").addEventListener("change", function(){
document.querySelector("#displaytotalscore").textContent = this.value;
}, false);
Add More Field
<ul class="jcform" id="countme">
<li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>
<li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>
</ul>
Total: <div id="displaytotalscore"></div>
This shows the basic working of the onchange event. User fills in a score in the input with id score. When this loses focus (blurs) it will invoke the onchange event setting the score to the div using the property textContent.
Updated with your fiddle:
http://jsfiddle.net/41fw2c4x/2/
function addmore() {
var top_level_div = document.getElementById('addmore');
var count = top_level_div.getElementsByTagName('ul').length;
var ul = document.createElement('ul');
ul.className = 'jcform';
ul.id = 'remove' + count;
var tbl1 = '<li>Name <input class="form-control" id="field1" name="cname[]" type="text" value=""/></li> <li>Score <input class="form-control" id="fieldpoints1" name="cpoints[]" type="text" value=""/></li><li>Removed</li>';
ul.innerHTML = tbl1;
document.getElementById('addmore').appendChild(ul)
}
//my solution
document.querySelector("#addmore").addEventListener("keyup", function(e){
if (e.target && e.target.tagName == "INPUT" && e.target.name == "cpoints[]")
{
updateScore();
}
}, false);
function updateScore()
{
var score = 0;
Array.prototype.map.call(document.querySelectorAll("input[name='cpoints[]']"), function(element){
score += !isNaN(parseInt(element.value)) ? parseInt(element.value) : 0; //when not a digit add 0, or ignore.
});
document.querySelector("#displaytotalscore").textContent = score;
}
function removeme(numm) {
document.getElementById('remove' + numm + '').parentElement.removeChild(document.getElementById('remove' + numm + ''));
updateScore();
}
//solution end
Add More Field
<div id="addmore">
<ul class="jcform" id="countme">
<li>Name
<input id="name" class="form-control" name="cname[]" type="text" value="" />
</li>
<li>Score
<input id="score" class="form-control" name="cpoints[]" type="text" value="" />
</li>
</ul>
</div>Total:
<div id="displaytotalscore"></div>
This adds an keyup event to the main div (addmore). Every time it detect an input element with the name cpoints[], it will iterate over all inputs with that name. Sum the total amount and display it in the div. It ignores values other than numbers by assigning the value 0. It checks if something is a number with the isNaN method.
Why did I switch to the keyup event? It allows me to use only one event, instead of adding an onchange event for every input. Why not set an onchange event on the div then? div don't support onchange events, so we need a different approach, in this case the keyup.
I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle