The sum of the top inputs is put into the bottom input. I need to fire some JS code if the value of the bottom input goes above 100. My code is not working as it should.
HTML
<div>
<input type="text" class="top" maxlength="3" value="0" />
<input type="text" class="top" maxlength="3" value="0" />
<input type="text" class="bottom" maxlength="5" value="0" />
</div>
JS
$(document).on("change", ".top", function () {
var sum = 0;
$(".top").each(function () {
sum += +$(this).val();
});
$(".bottom").val(sum);
});
$(document).on("change", ".bottom", function () {
var sum = $(".bottom").val();
if (sum > 100) {
alert("Test alert!");
}
});
The issue is because programmatically updating the value of an input does not raise an event, so the change handler you bind is never invoked. To fix this trigger() an event manually after setting val().
Also note there's a couple of other tweaks to the logic which can be made, such as using this in the .bottom event handler to reference the element which raised the event instead of all .bottom elements in the DOM, and also using the input event, which is triggered as typing occurs and also when content is pasted in using the mouse.
$(document).on("input", ".top", function() {
var sum = 0;
$(".top").each((i, el) => sum += +el.value);
$(".bottom").val(sum).trigger('input');
});
$(document).on("input", ".bottom", function() {
var sum = +$(this).val();
if (sum > 100) {
console.log("Test alert!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" class="top" maxlength="3" value="0" />
<input type="text" class="top" maxlength="3" value="0" />
<input type="text" class="bottom" maxlength="5" value="0" />
</div>
Related
newbie here. My target is when is when I click the button, my 2nd textbox will do the copy without comma. How can I make this work? I provided my JS fiddle and codes below. Any help will be appreciated. Thank you
JS Fiddle: https://jsfiddle.net/rain0221/auk4rfdg/6/ // I provided more explanation here
html:
<input type="text" value="" class="form-control" id="box"/>
<input type="text" value="" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
script:
//this function copies the textbox1 values with autocomma and produces same value but without comma on textbox2
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
//this function shows the value of my button to the textbox
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
}
When 5000 clicked, change textbox2 value!
Code snippet:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
document.getElementById("textbox2").value=count.replace(',','');
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<input type="text" value="" class="form-control" placeholder="autocomma textbox" id="box"/>
<input type="text" value="" placeholder="same value but no comma" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
document.addEventListener("input", action)
document.addEventListener("click", action)
function action(ev){if (ev.target.tagName=="INPUT"){
const ch=ev.target.closest("div").children;
if(ev.target!=ch[1])
ch[1].value=(ev.target.value-0).toLocaleString()
if(ev.target==ch[2])
ch[0].value=ev.target.value;
}}
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="5000">
</div>
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="2000000">
</div>
I wrote my snippet without jQuery as it is not really needed here and I reversed the roles of the input fields as it is
a better user experience if the input is not tampered with directly
difficult to "undo" a .toLocaleString(), see here
The trigger for action is the input event which also includes paste actions done via mouse clicks.
I also removed the id attributes from your input values. This way you can add further input groups to your page and re-use the script without further change.
All my addEventListener() actions are done in the "delegated" mode, to the parent document. By doing it this way the event will also be triggered by dynamically added elements (elements that might get added through some user interaction).
From my below Not working code [1], its will works fine with siblings() to disable others input field when they are have sum or amount going greater than maximum value, if all input fields are in same parent element.
For example:
<parent>
<child input>
<child input>
<child input>
<child input>
</parent>
If you try CODE ELEMENT STEPPING as above to below code, the code can be work.
Not working code [1]:
$('.variations input').on('change input mouseup keyup', function() {
var maxVal = 15; //Here is maximim value
var sum = 0;
$('.variations input').each(function() {
sum += +$(this).val();
});
if (sum >= maxVal) { //amount in any fields can't greater than maxVal
$(this).siblings().not(this).prop('disabled', true);
} else {
$(this).siblings().not(this).prop('disabled', false);
}
});
HTML:
<div class="variations">
<input type="number" name="sRewards" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward1" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward2" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward3" value="" class="inputReward" />
</div>
So I want to know how can we use jQuery siblings() to do stuff with others child element.
For real situation I might call many steps by using a lot of table elements:
https://jsfiddle.net/L01uexv1/1/
I will be more happy if someone suggest me on my real situation code too.
Thanks a lot!
Firstly you have to use the .parent() function and find all 'input' elements of the siblings, then just disable them, using .prop() function.
$('.variations input').on('change', function() {
var maxVal = 15; //Here is maximim value
var sum = 0;
$('.variations input').each(function() {
sum += +$(this).val();
});
if (sum >= maxVal) {
$(this).parent().siblings().find('input').prop('disabled', true);
} else {
$(this).parent().siblings().find('input').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="variations">
<input type="number" name="sRewards" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward1" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward2" value="" class="inputReward" />
</div>
<div class="variations">
<input type="number" name="sReward3" value="" class="inputReward" />
</div>
I recently have a result in a modal from calculatesum JavaScript displayed as <span id="sample">0</span> (the value will increase based on the number key in by users)
How do I display this final sample value in another input box outside of the modal? Help?
JavaScript as below:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(0));
}
HTML or rangeslide code as below:
<input type="text" class="form-control slider-text-field" id="homeContentInput" placeholder="250,000">
</td><td> (RM)</td></tr></table>
<br/>
<input type="range" value="250000" min="15000" max="500000" step="10000" id="homeContentRange">
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max">RM 500,000</span>
Basically, I need to replace placeholder="250,000" for the first input box and value="250000" with the final value from <span id="sample">0</span>.
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
//$("#sum").html(sum.toFixed(0));
$("#homeContentInput").val(sum.toFixed(0));
$("#homeContentRange").val(sum.toFixed(0));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
*****************************************************************
<br>if you just want to add up the values then this will work, else you need to be more clear with your question.
<br>form2-1:
<input class="txt" type="text" id="form2-1" value="0">
<br>form2-2:
<input class="txt" type="text" id="form2-2" value="0">
<br>form2-3:
<input class="txt" type="text" id="form2-3" value="0">
<br>Not sure what you want to do bellow this... *****************************************************************
<br>
<input type="text" class="form-control slider-text-field" id="homeContentInput" placeholder="250,000">(RM)
<br>
<input type="range" value="250000" min="15000" max="500000" step="10000" id="homeContentRange">
<br>
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max ">RM 500,000</span>
<br>*****************************************************************
Not sure if I understand this right but I think you want something along these lines?
I assume you want
the first field readonly
the second field as the slider
on submit calculates the total, in which you can post the results in another div.. In your case a modal.
Place the result where ever you like
<p id="result"> </p>
<input id="value1" type="text" value="250000" readonly="readonly"/>
<span> + </span>
<input id="value2" type="text" id="textInput" value="15000">
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max">RM 500,000</span>
<input type="submit" onclick="output();">
<p id="result"> </p>
<input type="range" type="range" value="250000" min="15000" max="500000" step="10000" onchange="updateTextInput(this.value);">
<script type="text/javascript" language="javascript" charset="utf-8">
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}
function updateTextInput(val) {
document.getElementById('value2').value=val;
}
</script>
I'm trying to do a simple calculation onblur with arrays but it's not firing. If I change it to a span or div it works fine. Why isn't it working with an input field?
I need it to be an input field because it's easier to store the values in a database.
<input type="text" class="input-small" name="partnumber[]">
<input type="text" class="input-small" name="partdescription[]" >
<input type="text" class="input-small" name="partprice[]" onblur="doCalc(); calculate(); ">
<input type="text" class="input-small" name="partquantity[]" onblur="doCalc(); calculate(); ">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
Calculation
function doCalc() {
var total = 0;
$('tr').each(function() {
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
});
$('.parttotal').each(function() {
total += parseInt($(this).text(),10);
});
}
Firstly, I wouldn't use inline events.. Here I've used delegated events, an advantage here if you dynamically add any more lines, it will still work..
Next make sure each line has some sort of wrapper for each line, here I've used a simple DIV. Yousr might be your TR..
The rest then becomes easy, as can be seen here, this example I've just included the price, qty & total, and done 2 lines for testing..
function calc() {
var h = $(this).closest('div');
var qty = h.find('[name="partquantity[]"]');
var price = h.find('[name="partprice[]"]');
var total = h.find('[name="parttotal[]"]');
total.val(qty.val() * price.val());
}
$('body').on('blur', '[name="partprice[]"],[name="partquantity[]"]', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
you can't use .html() to set the value of a textbox.
Change this line:
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
to
$(this).find('.parttotal').val($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
Note the change ('.parttotal').html becomes ('.parttotal').val
I literally started trying to teach myself javascript less than 48 hours ago. Outside of just wanting to learn it I also have a small personal project I'm working on and using as sort of my working learn as I go example. But I've hit a problem, which I'm sure is rather basic, I'm just hampered by lack of much javascript knowledge.
Basically it is just an averaging problem.
There are going to be 4 inputs fields with the 4th being a rounded to the nearest whole number average of the first three fields.
This 4 field configuration is going to get used multiple times on the page.
I want it to work in "real time" and not with a calculate button so I'm assuming "onKeyup" is needed. (no validation of any kind is needed or submit or saving or anything)
The only code I've been able to get close is really really ugly, long, and convoluted. I can't help but think there is a very simple way to do it and just get the same function to apply to each grouping of inputs. It will look like below but probably much longer.
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
Thanks in advance. This is part of a larger problem but I've tried to strip it down to it's essence and seeing it work and understanding it will go a long way to helping me solve some other problems.
To start with use a different markup, there should only be a single id per page, so use classes, it make it easier to target everything too. Also if the effect is to use the last input as a display you can use readonly instead of disabled
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>
Here is an example done in jquery
$(function() {
$('.group input').on('click', function() {
var count = parseInt($(this).val()) || 0;
$(this).siblings(':not(.final)').each(function() {
if ($(this).val()) count = count + parseInt($(this).val());
});
$(this).siblings('.final').eq(0).val(count);
});
});
And the demo is here: http://jsfiddle.net/4S4Vp/1/
This should be understandable for your level. The second set of inputs will be named a-2 with calc(2) and so on.
<input id="a-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="b-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="c-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="final-1" value="0" disabled />
function calc( n ) {
var a = document.getElementById("a-" + n ).value;
var b = document.getElementById("b-" + n ).value;
var c = document.getElementById("c-" + n ).value;
document.getElementById("final-" + n ).value = Math.round((parseInt(a)+parseInt(b)+parseInt(c))/3);
}
This is really quick and dirty, but if you know how many inputs you have, this should work:
// these would instead be your textboxes
var a = document.getElementById('a').value();
var b = document.getElementById('b').value();
var c = document.getElementById('c').value();
var avg = (a+b+b)/3;
document.getElementById('c').value() = avg;
Here is a jsfiddle so you can play with the idea and see if it works as you want it to.
Use jquery.
see the live demo on jsfiddle
some text
<div id="div1">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>
some text
<div id="div2">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>
<script type="text/javascript">
$("#div1 input").bind('change keyup click',function(){
var final = 0;
$("#div1 input").not("#div1 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div1 #final").val(final/3);
});
$("#div2 input").bind('change keyup click',function(){
var final = 0;
$("#div2 input").not("#div2 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div2 #final").val(final/3);
});
</script>
I hoped to flag this as duplicate, but because this answer does not have code, enjoy:
// find all inputs in the page and gather data trying to convert it to number
var data = [].map.call( document.querySelectorAll('input'), function (v) {
if (typeof v.value * 1 === 'NaN') {
return 'NaN';
}
return v.value * 1;
});
// not all data will be valid, so we filter it
data = data.filter( function (v) {
return !isNaN(v);
});
// and then calculate average
var avg = data.reduce( function (v, v1) {
return v + v1;
}) / data.length;