For my code, I am trying to call 2 parameters into a function. Once you have left the 2nd input box, and multiply the 2 numbers passed through and put it in the third text box. if either of the first 2 input boxes are empty, then color them light red. This is my code so far, what am I missing?
Javascript:
function multiply(one, two) {
if(one==""){
this.style.color='red';
}
if(two==""){
this.style.color='red';
}
else{
txt1=one * two;
return txt1;
}
}
HTML5:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply(mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
<input … onblur="multiply.call(this,this.form.elements.mFirst.value,this.form.elements.mLast.value)" >
function multiply(one, two) {
if(one && two){
this.form.elements.answer.value = one * two;
} else {
this.style.color='red';
}
}
Empty strings are non-truthy values, thus one && two will only be true if neither value is an empty string.
Using call allows you to set the value of this used inside the function.
Demo: http://jsfiddle.net/b5Ltt/
You might want to look at the HTML5 <output> element.
You are not passing this to your multiply() function.
If you want to change this.style you can pass this as an argument.
Also, you should change mFirst.value to this.form.elements.mFirst.value and the same for mLast.value
HTML:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply( this , mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
JavaScript:
function multiply( _this, one, two) {
var txt1 = 0;
if(one=="" || two==""){
// Should set both colors to red
_this.form.elements.mFirst.style.color = 'red';
_this.form.elements.mLast.style.color= 'red';
}else{
// parse float in the case of a decimal and set de
one = parseFloat(one);
two= parseFloat(two);
txt1 = one * two;
_this.form.elements.answer.value = txt1;
}
}
First Value: <input type="text" name="mFirst" id="mFirst" />
Second Value: <input type="text" name="mLast" id="mLast" onblur="multiply()" />
Multiplication of First and Second Value: <input type="text" name="answer" id="answer" />
function multiply()
{
var num_one = document.getElementById('mFirst').value;
var num_two = document.getElementById('mLast').value;
if(typeof num_one === 'number' && typeof num_two === 'number')
{
document.getElementById('answer').value = (parseInt(num_one) * parseInt(num_two));
}
else
{
document.getElementById('answer').style.color = 'red'; // not recommended method
}
}
Using a similar note, why this doesn't work?
function monetaryfields()
{
if (multiply) { total.value = unitary.value * quantity.value; }
else { unitary.value = total.value / quantity.value; }
}
<form>
<ul>
<li>Quantity: <input type="text" name="quantity" onblur="monetaryfields.call(true)" /></li>
<li>Unitary: <input type="text" name="unitary" onblur="monetaryfields.call(true)" /></li>
<li>Total: <input type="text" name="total" onblur="monetaryfields.call(false)" /></li>
</ul>
</form>
Related
I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
i have multiple input number fields with the same class, and i have to sum them but when I try with my javascript i get always NaN result
var arrNumber = new Array(); //contain the number of specific input field
var totale;
$(".input-n-pro").bind('keyup mouseup', function () {
totale = 0;
$('.input-n-pro').each(function(){
var this_num = $(this).val();
totale = parseInt(this_num)+parseInt(totale);
})
console.log("totale="+totale);
});
The html of input is this, generated by php, one for every row of a table
<input type="number" name="<?php echo $data["name"];?>" min="0" max="500" placeholder="0" class="form-control input-xs input-n-pro" style="display: inline">
I don't know it won't work, it work with only js withous jquery but i have to get the id of every field to do that and i want to do that for everyone with the same class because they are dinamic fields
P.S. The other part of my work, is to get every name of those fields and store them so i can have an array in js where i have the name of input and his number value, but i don't know how to do because they are dinamic
You probably parsing something that is not an integer. Then the parseInt won't work and returns NaN. If you sum a NaN, then it stays a NaN, example:
// working testcase:
const testArray = ['2', '3', '4'];
let total = 0;
for (value of testArray) {
total += parseInt(value);
}
// returns 9
console.log(total);
// your testcase:
const testArray2 = ['2', '3', 'notANumber'];
let total2 = 0;
for (value of testArray2) {
total2 += parseInt(value);
}
// returns NaN since we are adding 2 + 3 + NaN = NaN
console.log(total2);
So the solution is to 'negate' the NaN by treating it as 0:
// solution:
const myArray = ['2', '3', 'notANumber', '4'];
let total = 0;
for (value of myArray) {
// treat NaN, undefined or any falsey values as 0.
total += parseInt(value) || 0;
}
// returns 9
console.log(total);
To integrate this concept in your code, you'll get something like:
let total = 0;
$('.input-n-pro').each(() => {
let valueInString = $(this).val();
let actualValue = parseInt(valueInString) || 0;
total += actualValue;
});
if one of inputs value is empty then parseInt returns NAN. So you can better do a check using IsNan function. if input is empty than assign 0. For example;
var x= parseInt($('#abc').val()); if (isNaN(x)) x = 0;
Part 1 and 2 of your question
The reason you get NaN is most probably that if any of the inputs has no value, asking for that value returns an empty string (form fields always return strings) "". parseInt("") returns NaN.
Using vanilla ECMAScript 6, the solution is a one-liner with the help of Array.prototype.reduce:
const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0);
For your second question, just use Array.prototype.map. Also a one-liner.
const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }});
Note: The Array spread operator [...document.querySelectorAll('.input-n-pro')] makes an array from the NodeList document.querySelectorAll returns, so you can use Array methods on the list (like reduce and map).
Example:
calc.addEventListener('click', () => {
const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0);
console.log(sum);
})
getArr.addEventListener('click', () => {
const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }});
console.log(theArr);
})
<input type="number" value="5" class="input-n-pro" name="a" />
<input type="number" value="3" class="input-n-pro" name="b" />
<!-- lets insert one input that contains no number -->
<input type="text" value="foo" class="input-n-pro" name="m" />
<input type="number" value="2" class="input-n-pro" name="c" />
<input type="number" value="11" class="input-n-pro" name="d" />
<input type="number" class="input-n-pro" name="e" />
<br />
<button id="calc" type="button">Calculate Sum</button>
<button id="getArr" type="button">Get Array of name-value pairs</button>
bind() has been deprecated => use on
arrNumber = [], //contain the number of specific input field
totale = 0;
doTotale(); // first round
$(".input-n-pro").on('keyup mouseup change', doTotale);
function doTotale()
{
totale = 0;
arrNumber.length = 0;
$('.input-n-pro').each(function()
{
let
name = $(this).attr('name'),
val = parseInt($(this).val(),10) || 0;
arrNumber.push( {name, val });
totale += val;
})
console.clear();
console.log("totale =",totale);
console.log("arrNumber =", JSON.stringify(arrNumber) );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
AA : <input type="number" name="AA" value="5" class="input-n-pro" /> <br>
BB : <input type="number" name="BB" value="3" class="input-n-pro" /> <br>
CC : <input type="text" name="CC" value="foo" class="input-n-pro" /> <br> <!-- lets insert one input that contains no number -->
DD : <input type="number" name="DD" value="2" class="input-n-pro" /> <br>
EE : <input type="number" name="EE" value="11" class="input-n-pro" /> <br>
FF : <input type="number" name="FF" class="input-n-pro" />
My full code can be found here: http://pastebin.com/t3JCBRrX
I made an easy calculation script for my website. I'd like two modifications but I can't seem to do it.
This is what I have now:
The function:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').value = result;
}
The form:
<label for="e" id="answer">Kosten: </label>
<input type="field" name="Antwoord" id="e" disabled><br>
<input type="button" onclick="bereken()" value="Bereken">
I'd like to prefix the result with a euro sign (result is '€123' instead of '123').
I would also like the result to be just plain text, instead of a disabled input field.
Any help would be greatly appreciated, as I'm just a beginner. Thanks!
edit: the calculation is that complicated because I don't want the answer to be '1200' when '0' has been entered
See this FIDDLE
Just insert the value with '€' appended
document.getElementById('e').innerHTML = '€'+result;
Also you can change the disabled input to label if you want it to be plain text
var ap, result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken() {
setValue();
result = (((ap * 275) / (ap * 275)) * 1200 + (ap * 275) || 0).toFixed(e);
document.getElementById('e').innerHTML = '€' + result;
}
<input type='text' id='ap' placeholder='enter value' />
<label for="e" id="answer">Kosten:</label>
<label type="field" name="Antwoord" id="e" disabled></label> <br>
<input type="button" onclick="bereken()" value="Bereken">
change document.getElementById('e').value = result; to document.getElementById('e').value = "€"+result;.
change disabled to readonly.
Try this:
JS Code:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').innerHTML = result;
}
HTML Code:
<input type="text" id="ap"/>
<label for="e" id="answer">Kosten: </label>
<span>€</span><span id="e"> </span><br>
<input type="button" onclick="bereken()" value="Bereken"/>
The form code:
<td><form action="cart.php" method="get">
<input type="button" onclick="buttonSubtract1()" name="subtract1" value="-
"/>
<input type="text" size="4" id="qty1" name="quantity1" value="0"/>
<input type="button" onclick="buttonAdd1()" name="add1" value="+"/>
<input type="submit" name="product1" value="Add"/>
The javascript:
var i = 0;
var qty1 = document.getElementById('qty1').value;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
I changed the code to increment and de-increment using javascript which worked fine so I tried to make it so that de-incrementation only works if the number is positive but now incrementing is working fine but it is not allowing de-incrementation of any number. Why is this?
You just have to put the var qty1 = document.getElementById('qty1').value; into the subtract function like this:
var i = 0;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
var qty1 = document.getElementById('qty1').value;
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
}
In your Example, you just write the First Value (0) into the Window objekt.
It stays zero until you change it in the window object again.
But if you ask the Value everytime the function is called, you get always the newest number.
Fiddle:
http://jsfiddle.net/9wHU9/
If I have 50 pairs of input textboxes, i.e.
<input type="text" id="name_0" /><input type="text" id="name_1" />
<input type="text" id="dept_0" /><input type="text" id="dept_1" />
...
<input type="text" id="age_0" /><input type="text" id="age_1" />
<input type="text" id="weight_0" /><input type="text" id="weight_1" />
i.e 50 variables of these.
When the page loads, I populate each pair with identical data.
What is the best way to check if the _0 is different from the _1?
then returning a message showing which pair has changed.
The comparison should take place once the values have been changed and a button is clicked.
$("input[type=text]").each(function () {
var $this = $(this);
if ( /_0$/.test(this.id) ) {
if ( $this.val() != $this.next("input").val() ) {
$this.css("color", "red"); // or whatever
}
}
});
Tomalak's answer should work, but just in case your inputs are scattered or not necessarily beside each other, something like this should suffice.
$('input:text[id$="_0"]').each(function() {
var new_id = this.id.replace('_0','_1');
if ($(this).val() !== $('input#'+new_id).val()) {
// not the same
}
});
var changed = [];
$("[id$=_0]").each(function() {
var name = this.id.replace("_0", "");
if (this.value != $("#" + name + "_1").val()) {
changed.push(name);
}
});
console.log(changed);