onchange event not accepting my javascript code - javascript

I have two text input for the user to type numbers, and I would like the page to output the total of these two numbers in another text input
<input id="attendance_1" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
I get the error:
ReferenceError: invalid assignment left-hand side

I suggest putting the code of your onchange in a function and just calling that function onclick. It makes things way more easy to debug.
Example
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var val = parseInt(document.getElementById('attendance_output').value);
val += parseInt(field.value);
document.getElementById('attendance_output').value = val;
}

Try below code. it should work.
your code is not working because += sign in expression.
<input id="attendance_1" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />

So this is really basic JS with typechecks
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var oVal = parseInt(document.getElementById('attendance_output').value);
var iVal = parseInt(field.value);
if(!oVal || Number.isNaN(oVal)) {
oVal = 0;
}
if(!iVal || Number.isNaN(iVal)) {
iVal = 0;
}
oVal = oVal + iVal;
document.getElementById('attendance_output').value = oVal;
}

try this. :) it will not work properly if the user input string, so i think it should have validation.
function addValue() {
var num1 = document.getElementById('attendance_1').value;
var num2 = document.getElementById('attendance_2').value;
if (num1 === ''){
num1 = 0;
}
if(num2 === ''){
num2 = 0;
}
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('attendance_output').value = sum;
}
you can make the textbox accept only numbers, by using jquery
$(document).ready(function() {
$("#attendance_1, #attendance_2").keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});

Use this code inside
onchange="document.getElementById('attendance_output').value=+document.getElementById('attendance_output').value+ +this.value"
Hope it will be useful for you :)

This may be an option. I removed the inline JS completely. Went from onchange to an oninput handler, which will only do the calculation if the values given are actually numbers not strings.
var inpt = document.querySelectorAll('.attendance');
var out = document.getElementById('attendance_output');
var onInput = function(e) {
if(/\d/.test(this.value)) {
var sum = [].slice.call(inpt).reduce(function(a, b) {
if (a.value.length && b.value.length) {
return +a.value + +b.value;
} else {
return +a.value || +b.value;
}
})
out.value = sum || this.value;
} else {
out.value = "";
}
}
inpt.forEach(function(el) {
el.addEventListener('input', onInput, false)
})
<input class="attendance" type="text" name="attendance_1" value="" /> <span>+</span>
<input class="attendance" type="text" name="attendance_2" value="" />
<br><br>
<input id="attendance_output" type="text" value="" disabled />

Related

jquery put value to input box

I have this script
<script>
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
$('#touch').value('passed');
}
}
</script>
here is the html
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
i need a value to be displayed everytime the value of the xcoord and ycoord suits the condition, but no value is printed even the condition is true.
You have mixed plain JavaScriptwith JQuery.
Put value to input box with JavaScript
box.value = 'passed';
CodeSnippet
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
box.value = 'passed';
}
}
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
Put value to input box with JQuery
$('#touch').val('passed'); //Although you already have the box variable
CodeSnippet
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
$('#touch').val('passed');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
tl;dr;
Since you started code with plain JavaScriptyou confused how to change the value with jQuerysyntax.
JavaScript box.value = 'passed';
jQuery $('#touch').val('passed');
You are using the jQuery Library. Use better than jQuery methods.
$("#xcoord , #ycoord").on("keyup", function(){
var x = $('#xcoord').val();
var y = $('#ycoord').val();
$('#touch').val((x >= 325 || x <= 300) && (y >= 55 || y <= 25)?'passed':'');
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input required type="number" id="xcoord" name="xcoord" value="0">
<input required type="number" id="ycoord" name="ycoord" value="0">
<input required type="text" id="touch" name="touch">
it should be
$('#touch').val('passed');

How to disable non-integer input in the rightmost text box?

I am writing one JavaScript code
Please see the images. There are 4 text boxes where only one character can be entered .
The rightmost field's id is first and the leftmost id is fourth
4 conditions are to be fulfilled
The last text box - the rightmost/first textbox will be input first, then the second one will be filled, then the third and at last the fourth
Then the rightmost/first textbox value will shift (left shift) to the second and in this way values will shift until all 4 fields are filled - See screenshot Insert
If we place the cursor on any other element except the first/rightmost it will move the cursor to the rightmost because we will only enter input in the rightmost
There will be backspace function which will delete the rightmost/first , ie. the the first field will be deleted the fourth field value will move to third, third to second, like this, a right shift will occur in this way all elements are to be deleted - see Screenshot Delete
https://i.stack.imgur.com/w8eUg.jpg -- Screenshot Insert
https://i.stack.imgur.com/fl8Gg.jpg -- Screenshot Delete
The entire solution should be in JavaScript, no jQuery can be used
<form>
<input type="text" id="fourth" size="1" maxlength="1" />
<input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />
<html>
<head>
</head>
<body>
<form>
<input type="text" id="fourth" size="1" maxlength="1" />
<input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />
</form>
<script>
var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener("click", function() {
document.getElementById("first").focus();
})
}
myEditable.addEventListener("keypress", function(evt) {
if (evt.which >= 48 && evt.which <= 57) {
// Here, we have a number. Everything gets shifted to the LEFT
if (myInputs[0].value == "") {
for (var i = 0; i < myInputs.length - 1; i++) {
myInputs[i].value = myInputs[i + 1].value;
}
myEditable.value = String.fromCharCode(evt.which);
}
} else {
evt.preventDefault(); // newly added to prevent non integer inputs in rightmost field
console.log("Sorry");
}
})
myEditable.addEventListener("keyup", function(evt) {
if (evt.which == 8) {
//myEditable.blur();
for (var i = myInputs.length - 1; i >= 1; i--) {
myInputs[i].value = myInputs[i - 1].value;
}
myInputs[0].value = "";
}
});
</script>
</body>
</html>
I am facing only one problem - non Integer input to be disabled, no JavaScript alert, simply it will not accept any non integer input.
In my code I can enter non integer in the first/rightmost field, not in others but I have to disable non integer input in first/rightmost field.
you never called preventDefault() on the event.
Notice the preventDefault in the else where you do console.log("sorry");
https://jsfiddle.net/jmuc36hs/
var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener("click", function() {
document.getElementById("first").focus();
})
}
myEditable.addEventListener("keypress", function(evt) {
if (evt.which >= 48 && evt.which <= 57) {
// Here, we have a number. Everything gets shifted to the LEFT
if (myInputs[0].value == "") {
for (var i = 0; i < myInputs.length - 1; i++) {
myInputs[i].value = myInputs[i + 1].value;
}
myEditable.value = String.fromCharCode(evt.which);
}
} else {
evt.preventDefault();
console.log("Sorry");
}
});
myEditable.addEventListener("keyup", function(evt) {
if (evt.which == 8) {
//myEditable.blur();
for (var i = myInputs.length - 1; i >= 1; i--) {
myInputs[i].value = myInputs[i - 1].value;
}
myInputs[0].value = "";
}
});

Add slashes (' / ') in date field using javascript in php

I have this textbox:
<td width="10%"><input name="date" type="text" size=11 maxlength=10 /></td>
when typing date in the field it must add a forward slash in it like 09/02/2016
You can do the same functionality in PHP using JS OR jQuery.
Replace
<input name="date" type="text" size=11 maxlength=10 />
To
<!-- SET type="date" -->
<input type="date" name="date">
jQuery Code:-
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="date"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
Hope it will help you :)
This one was very ticky! This is how I got it working, though it's not complete as you will need to check for when a number is deleted
<input type="hidden" id='counter' value='0'>
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="doDate()"/>
<script>
function doDate(){
var dateSoFar = document.getElementById("date");
var counter = parseInt(document.getElementById("counter").value);
counter = counter+1;
document.getElementById("counter").value = counter;
if(counter == 3 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>
Try this,
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="updateDate()"/>
<script>
function updateDate(){
var dateSoFar = document.getElementById("date");
var counter = dateSoFar.value.length;
if(counter == 2 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>

How to check value in input using loop for with onchange using javascript?

How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>

Javascript calculation returns NaN, when only first 2 sum inserted

function kanded_arvutus()
{
var deebet1 = document.getElementById("deebet1").value;
var kreedit1 = document.getElementById("kreedit1").value;
var deebet2 = document.getElementById("deebet2").value;
var kreedit2 = document.getElementById("kreedit2").value;
var kokku_deebet = parseFloat(deebet1)+parseFloat(deebet2);
document.getElementById("kokku_deebet").value = kokku_deebet.toFixed(2);
var kokku_kreedit = parseFloat(kreedit1)+parseFloat(kreedit2);
document.getElementById("kokku_kreedit").value = kokku_kreedit.toFixed(2);
}
and this is html
<input onClick="kanded_arvutus();" onChange="kanded_arvutus();" type="text" class="form-control" name="deebet'.$i.'" id="deebet'.$i.'" placeholder="0" value="">
<input value="" onClick="kanded_arvutus();" onChange="kanded_arvutus();" type="text" class="form-control" name="kreedit'.$i.'" id="kreedit'.$i.'" placeholder="0">
<input type="text" class="form-control field" name="kokku_deebet" value="" id="kokku_deebet" placeholder="0">
<input type="text" class="form-control field" name="kokku_kreedit" value="" placeholder="0" id="kokku_kreedit">
and if i insert only kreedit1 and deebet1 values, then jquery returns NAN , but if i insert deebet2 and kreedit2 also, then working.
someone maybe see, what wrong here ?
Thanks in advance, aimar.
Please check the variables are not null or notdefined as below, before the addition,
if (typeof(deebet1) != 'undefined' && deebet1 != null && typeof(deebet2) != 'undefined' && deebet2 != null)
{
var kokku_deebet = parseFloat(deebet1)+parseFloat(deebet2);
document.getElementById("kokku_deebet").value = kokku_deebet.toFixed(2);
}
if (typeof(kreedit1) != 'undefined' && kreedit1 != null && typeof(kreedit2) != 'undefined' && deebet2 != null)
{
var kokku_deebet = parseFloat(kreedit1)+parseFloat(kreedit2);
document.getElementById("kokku_kreedit").value = kokku_deebet.toFixed(2);
}
As John suggested you can just use the following, which will check whether the variables has any real values.
if (deebet1 && deebet2)
{
var kokku_deebet = parseFloat(deebet1)+parseFloat(deebet2);
document.getElementById("kokku_deebet").value = kokku_deebet.toFixed(2);
}
if (kreedit1 && kreedit2)
{
var kokku_deebet = parseFloat(kreedit1)+parseFloat(kreedit2);
document.getElementById("kokku_kreedit").value = kokku_deebet.toFixed(2);
}
You're reading a empty string from the input values and trying to parse it as a number. That's why it is Nan. You need to check if it is not empty (and if it's empty set a default value, maybe 0).
if(deebet1 != "") {
}
and so forth..

Categories