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 = "";
}
});
Related
I have a Rot13 JS function that I am attempting to link to a button. The expected output is meant to be that if I enter 'ABC' and press the Encrypt button, the encrypted text becomes 'NOP'.
The function doesn't currently link up to the buttons in HTML and when I press the encrypt button there is no response. I've included a script tag in the HTML.
EDIT: the encrypter is linked to the button, however it encrypts 'ABC' to 'ABC.
JavaScript:
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
EDIT: corrected the JS.
There are few problems with code:
output.join('') = document.getElementById("box2") will throw error. You should set .value to output.join(''). The left hand side of = should be a variable. output.join('') returns are value and it cannot be assigned to anything.
output + input[i] will do nothing. You should use push() to add values to array.
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>
I have a field that will round up to the nearest .25. This is working fine in Chrome but for some reason it will not allow me to type say 2.25 in IE or Firefox. It ignores that I am typing a dot. Is there something obvious I'm missing here?
Edit One thing I have noticed is that if I change keyup to blur it will work fine. I need this to run on keyup though. It will also accept .25 by itself but not a number then decimal. For example 2.25.
$(document).on('keyup', '.Monday', findTotalMon);
function findTotalMon() {
var arr = document.getElementsByClassName('Monday');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseFloat(arr[i].value)) {
var newValue;
newValue = (.25 * Math.round(4 * arr[i].value));
arr[i].value = newValue;
tot += parseFloat(newValue);
}
}
document.getElementById('totalHoursMon').value = tot;
if (tot === 0) {
document.getElementById('totalHoursMon').value = '';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width Monday" name="monday" id="monday" type="number" step="any" /><br><br>
<input class="form-control full-width totalBox" name="total" id="totalHoursMon" type="text" readonly="readonly"/>
The issue lies in the use of keyup and the overwriting of your fields value with the newly parsed / rounded float.
After typing your decimal separator, the input is parsed and rounded and the separator disappears, because "1." or "1," is parsed to 1.
One way to solve this is to only overwrite your field when the rounded input is different than the original input.
$(document).on('keyup', '.Monday', findTotalMon);
function findTotalMon() {
var arr = document.getElementsByClassName('Monday');
var originalValue, newValue, tot = 0;
for (var i = 0; i < arr.length; i++) {
originalValue = arr[i].value;
if (parseFloat(originalValue)) {
newValue = (.25 * Math.round(4 * arr[i].value));
tot += parseFloat(newValue);
if (newValue != originalValue) {
// we're only overwriting input when the rounded value is different than the original
arr[i].value = newValue;
}
}
}
document.getElementById('totalHoursMon').value = tot;
if (tot === 0) {
document.getElementById('totalHoursMon').value = '';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width Monday" name="monday" id="monday" type="number" step="any" /><br><br>
<input class="form-control full-width totalBox" name="total" id="totalHoursMon" type="text" readonly="readonly"/>
On a side note :
Using keyup and overwriting your user's input is really annoying. For instance, while testing, I realized you can't use backspace to correct your input. I know you said you had to use keyup, but I strongly advise you to use blur or keypress. For your user's sake :)
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 />
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>