Javascript incrementing by more than one - javascript

var x1 = document.getElementById("x1");
var x2 = document.getElementById("x2");
function ThisEvent(){// needs a lot of work done to it
if (x1.value==1) {
x2.value--;
} else if (x1.value==2) {
x2.value++;
} else if (x1.value==3) {
x2.value+=5;
}
}
<input type="text" value="0" id="x1" onblur="ThisEvent()"> x1 </br>
<input type="text" value="0" id="x2"> x2
what is happening now is the digit is being added instead of incrementing when 3 is the input if x1. how do you make it increment by more than just one, without it being added it as a digit?

if (x1.value == 3) {
x2.value = parseInt(x2.value) + 5;
}
It's interpreting it as a string. You can parseInt the x2.value in the calculation.

The value of the input is a String, you need to convert it to a Number in order to perfom an addition on it.
You could do it like this:
function ThisEvent() { // needs a lot of work done to it
var valX1 = Number(x1.value);
var valX2 = Number(x2.value);
if (valX1 == 1) {
valX2--;
} else {
if (valX1 == 2) {
valX2++;
} else {
if (valX1 == 3) {
valX2 += 5;
}
}
}
x2.value = valX2;
}
jsFiddle: https://jsfiddle.net/v1utqv7f/

Related

While Loop Input Issue

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!
You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

jQuery result not displaying in field

For some reason I just can't get this result to display in the field using an id. It worked fine using a class but it just refuses to work using an id.
JSFiddle here http://jsfiddle.net/pbe4b/15/
Works fine:
<input id="button123" placeholder="number here"></input>
<span class="output123"></span>
Doesn't work:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
Would love any help!
use
$('#output123').val()
instead of
$('#output123').html()
input is self closing tag so you should use val() to get value from this .
You have changed spans to inputs, and so .html() is no longer valid. The selector is fine. Change all instances of .html() to .val().
HTML:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
JavaScript:
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
JSFiddle Here.
http://jsfiddle.net/pbe4b/19/
Vals instead of HTML since it is an input
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}`enter code here`
Use $('#output123').val() to set the value.
It has nothing to do with a class/id, it is due to the fact you changed the element.
inputs do not have html(), you use val() to set the value.
Cleaned up code without all the copy and paste:
$('#button123').keyup(function(){
var n = parseInt($(this).val(), 10);
var calc;
if(n <= 35000) {
calc = n/100*70;
} else if(n <= 45000) {
calc = n/100*75;
} else {
calc = n/100*80;
}
var val = numberWithCommas(calc.toFixed(2));
$('#output123').val(val);
});
To set the value of a input use:
JS:
document.getElementById('output123').value = 'my value';
jQuery:
$('#output123').val('my value');
.html is used to replace the inner content of an item, in the case of input you need to change an attribute.

Why do I get the error "Too much recursion"?

I'm working on a small project here and I get this message "too much recursion", when obviously there's not that much.
This is the relevant HTML code
<div id="speed">
<label for="spe">Input speed</label>
<input type="text" id="spe" onkeydown="if (event.keyCode == 13){ javascript:CalcBySpeed(); return false; }" />
<input type="button" name="Sumbit" value="Submit" onclick="javascript:CalcBySpeed()" />
</div>
and a table, generally looking like this:
<tr>
<td id="50">
<p id="117">5</p>
</td>
<td id="51">
<p id="118">20</p>
</td>
<td id="52">
<p id="119">5</p>
</td>
<td id="53">
<p id="120">1,2</p>
</td>
</tr>
And my JavaScript functions are:
function CalcBySpeed() {
var input = "a";
input = parseFloat(document.getElementById("spe").value) * 100;
if (input < 5089) {
getValueBySpeed(input - 3);
} else {
alert("Value undefined!");
}
};
function getValueBySpeed(input) {
if (document.getElementById(input) != null) {
document.getElementById(input).style.backgroundColor = "yellow";
document.getElementById(input + 1).style.backgroundColor = "yellow";
document.getElementById(input + 2).style.backgroundColor = "yellow";
document.getElementById(input + 3).style.backgroundColor = "yellow";
document.getElementById("res1").innerHTML = document.getElementById(input + 3).innerHTML;
document.getElementById("res2").innerHTML = document.getElementById(input + 2).innerHTML;
document.getElementById("res3").innerHTML = document.getElementById(input + 1).innerHTML;
document.getElementById("res4").innerHTML = document.getElementById(input).innerHTML;
} else {
getValueBySpeed(input++);
}
}
So if I decide to input in my input field:
1.2, js highlights this particular row successfully
1.19 js highlights the very same row successfully
0.97 js highlights the same row successfully
However when I input:
1.1 it logs in the console too much recursion
I believe when I input 0.97 there is much more recursion, still the problem is when I input numbers between 1.09 and 1.16.
Outside this range there seems to be no problem.
when obviously there's not that much.
obviously there is ;)
There is probably a mistake in your code:
function getValueBySpeed(input) {
if (document.getElementById(input) != null) {
...
}
else {
getValueBySpeed(input++);
}
}
If document.getElementById(input) != null is false it will likely stay false and the function getValueBySpeed will be called until you get the recursion error.
As a minor note: I don't understand what getValueBySpeed does, the name is weird, the arguments are weird, the implementation is weird.
I would expect perhaps (based on the name):
function getValueBySpeed(speed) {
var value;
value = // get value somehow
return value;
}
The postfix increment returns the original value, so you are calling your function repeatedly with the same value. That said, you don't need recursion, use a loop. Here is a rough attempt, but your code made little sense to me, so I may have gotten it wrong...
function CalcBySpeed()
{
var input = "a";
input = parseFloat(document.getElementById("spe").value)*100;
if (input < 5089) {
getValueBySpeed(input-3);
} else {
alert("Value undefined!");
}
};
function getValueBySpeed(input) {
while (document.getElementById(input) == null)
input++;
document.getElementById(input).style.backgroundColor = "yellow";
document.getElementById(input + 1).style.backgroundColor = "yellow";
document.getElementById(input + 2).style.backgroundColor = "yellow";
document.getElementById(input + 3).style.backgroundColor = "yellow";
document.getElementById("res1").innerHTML = document.getElementById(input + 3).innerHTML;
document.getElementById("res2").innerHTML = document.getElementById(input + 2).innerHTML;
document.getElementById("res3").innerHTML = document.getElementById(input + 1).innerHTML;
document.getElementById("res4").innerHTML = document.getElementById(input).innerHTML;
}
This is a rounding problem. 1.1 * 100 = 110.00000000000001. Then when you're adding 1 for each call the number will never be an integer. An element with the id xxxx.00000000000001 will never be found. 
The root of the problem is that 1.1 cannot be represented accurately with double precision floating point numbers.
The solution is the convert the number to an integer. I.e disregard the decimal value.

JS for each replacement of manual copy function

I am looking for way to automate this selection.
For example, I will have 10 double inputs (20 inputs total) and I don't want to write JS script for each inputs, but simply use each() function (I am open to different ways) and declare only selectors.
JsFiddle: http://jsfiddle.net/vs7fa/
Idea:
var SELECTORS_H = array();
$.each(SELECTORS_H){
$('SELECTOR_H').keyup(function () {
// do magic
$('SELECTOR_V').val(num);
});
$('SELECTOR_V').keyup(function () {
// do magic
$('SELECTOR_H').val(num);
});
}
HTML:
<label for="h_one">H_ONE:</label>
<input type="text" name="h_one">
<label for="v_one">V_ONE:</label>
<input type="text" name="v_one">
There will be more of inputs. Pattern is:
h_one, v_one
h_two, v_two
h_something, v_something
...
JS:
$(function() {
$('input[name="h_one"]').keyup(function() {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
}
else {
var num = Math.abs(one) * 1;
}
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function() {
var two = $(this).val();
if (two > 0) {
var num = Math.abs(two) * -1;
}
else {
var num = Math.abs(two) * 1;
}
$('input[name="h_one"]').val(num);
});
});
You can handle this using a selector with a common class for all your element and data-attributes to know the element and the linked elements.
HTML:
<label>H_ONE:</label>
<input type="text" class="handler" data-id="h1" data-link="v1" />
<br>
<label>V_ONE:</label>
<input type="text" class="handler" data-id="v1" data-link="h1" />
Code:
$(function () {
$('.handler').keyup(function () {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
$('input[data-id=' + $(this).attr("data-link")+']').val(num);
});
});
Demo: http://jsfiddle.net/8KgTk/
may be this...
Jsfiddle: http://jsfiddle.net/vs7fa/3/
$('input[name="h_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="h_one"]').val(num);
});
function DoMagic(element) {
var one = $(element).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
return num;
}
You should be able to perform the .each function by using jQuery and making the items the same class.
such as:
<label class="forElement" for="h_one">H_ONE:</label>
<input class="inputElement" type="text" name="h_one">
<label class="forElement"for="v_one">V_ONE:</label>
<input class="inputElement" type="text" name="v_one">
$('.forElement').each( function() {
//some code
}
You can do this without adding extra attributes if you want.
$(function () {
$('input[name^="h_"], input[name^="v_"]').keyup(function () {
var one = $(this).val();
var num = - one;
var inputType = $(this).attr("name").substr(0,1);
var inputNumber = $(this).attr("name").substr(2);
$('input[name="'+(inputType == 'v' ? 'h' : 'v')+'_' + inputNumber + '"]').val(num);
});
});
However Irvin Dominin aka Edward's solution is quite good.
Here's a sollution that doesn't require extra markup, and doesn't use string concatenation for logic. It uses $.proxy() to get correct scoping.
Fiddle

Why cant i enter decimal values in input in the following case

Before anything you need to see the effect:
jsFiddle
As you can see it is a calculator where you can put a value anywhere and covert it to other values, but the problem is that i cant enter decimal int values like 0.3 or 0.999. What is the cause of this?
var id = {
mm: 1,
cm: 10,
m: 1000,
km: 1000000
};
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseInt(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(v / id[pp] * i);
} else {
$(".bx").val('');
}
}
});
<input type='text' class='bx' id='mm'> Milimeter<br>
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br>
parseInt is the "problem" since it returns integer - decimal values are not integer but floats. If you want that you must replace it with parseFloat.
1.First you need to use parseFloat because int cant have decimals.
2.Second i would use onChange.
http://jsfiddle.net/Kfkjy/10/
a working fiddle here
you have to use parseFloat and dont try to set the current focused element value cause you are over riding it while typing.
this example is working fine
http://jsfiddle.net/Mohamed_aboelenen/D6T7j/1/
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseFloat(t, 10);
var a = $(this).attr("id"); // the textbox you write in
for (pp in id) {
if (t !== '' ) {
if(a != pp){ // make changes to any textbox except the one you write in
$("#" + pp).val(v / id[pp] * i);
}
} else {
$(".bx").val('');
}
}
});
$('input.bx').on('blur', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = Number(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(parseFloat(v / id[pp] * i));
} else {
$(".bx").val('');
}
}
});

Categories

Resources