JavaScript while loop won't increment properly for HTML document [duplicate] - javascript

Something that has bugged me for a while and always giving me headaches.
I have an input field with a value in numbers
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
I am picking up the value of the input field with
let charlife = document.getElementById('base-life');
I have a number with which i want to increase the value of the base-life input field. This of course changes dynamically based on other stuff but let's say it's 2
let increaseWith = 2;
in an onclick function i want to increase base-life with 2 (base-life + 2) everything it is clicked
function increase() {
charlife.value += increaseWith;
}
Now this only adds 2 to the value of the input field, makes it 202. I know that this happens when one of the numbers are actually strings. Perhaps my charlife. I tried everything and it gets worse. I tried parseInt(charlife.value) - no luck. I tried other methods but it doesn't work. And i only have this problem with input fields. When the element is just a or another simpler html element - it all works easier. Has to do with how JS parses input fields. Can someone shed some light?

let charlife = document.getElementById('base-life');
let increaseWith = 2;
function increase() {
value = parseInt(charlife.value);
value += increaseWith;
charlife.value = value;
}
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button onclick="increase()">Increase</button>

Here is the working snippet with some custom code that is according to your specifications
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button class="add" onclick="let increaseWith = 2;document.getElementById('base-life').value = parseInt(document.getElementById('base-life').value)+increaseWith;">add</button>

Related

Updating form input field value based on other inputs

I am trying to build a calculator of sorts where you an input all but one variable and get the final variable autofilled in the form. I am trying this using a javascript function oninput for the form. However I am not sure how to achieve this. I have written a basic example of what I want below (though this does not work):
<form oninput="thermal()">
<input type="number" name="avgTemp" id="avgTemp" class="five-col">
<input type="number" name="volume" id="volume" class="five-col">
<input type="number" name="deltaTemp" id="deltaTemp" class="five-col">
<input type="number" name="Q" id="Q" class="five-col">
</form>
function thermal(){
var volume = document.getElementById("volume");
var deltaTemp= document.getElementById("deltaTemp");
value = deltaTemp;
}
function thermal(){
let avgTemp = document.getElementById("avgTemp").value;
let volume = document.getElementById("volume").value;
let deltaTemp = document.getElementById("deltaTemp").value;
let q = document.getElementById("Q") // no value here yet; we will make this our total
console.log(avgTemp, volume, deltaTemp, q)
}
Well, let's start with this. This gives you each input value individually - from here, we can implement the pertinent logic to combine input values into one input field. I will make the Q input our "total" just so you can get a picture of how combining may look.
function thermal(){
let avgTemp = document.getElementById("avgTemp").value;
let volume = document.getElementById("volume").value;
let deltaTemp = document.getElementById("deltaTemp").value;
let q = document.getElementById("Q");
let total = Number(avgTemp) + Number(volume) + Number(deltaTemp)
console.log(total)
q.value = total
}
I am not sure what you are looking for but this should give you a decent head start. Fire away if you have any questions.
If you want to play around with it, here is the codepen:
https://codepen.io/Pulse3358/pen/ExPZaVM

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

More than 3-Way Checkbox

I want to implement an country-selection-input. In other words, I've got a form with a 25x25px flag, which I want to be clickable - say, german as default, first click changes it to netherlands, second to swiss or w/e.
The last chosen value needs to be in my POST-Array with the other values of the form.
I've tried to accomplish this using 3-Way checkboxes with javascript, but I'm going to need more than 3 options.
Any idea on how to do this? I've thought about an input select, hiding everything but the current value - but I don't know how to submit this to change to the next value.
Thanks in advance for any input, and please don't judge me for such a question - this is my first js/html/css project. :-)
You can do something like this:
HTML
<form method="POST">
<img src="german.png" onclick="switchCountry(this);"/>
<input id="country" name="country" type="hidden" value="german" />
<input type="submit" value="Submit" />
</form>
JavaScript
var countries = ['german', 'netherlands', 'swiss'];
var switchCountry = function(img) {
var input = document.getElementById('country'),
oldValue = input.getAttribute('value'),
newValue = countries[(countries.indexOf(oldValue) + 1) % countries.length];
// Switch input value that will be posted with form
input.setAttribute('value', newValue);
// Switch graphical representation of country
img.setAttribute('src', newValue + '.png');
};
Example here http://jsbin.com/alasip/1/edit

Change the color of an html 5 output object based on value

I want to change the color of the result of a calculation to red if it is negative. I tried a style sheet, and putting the output into a javascript call, but it did not seem to work. Is there a way to change the color of an html 5 output "o" in the example code below to red if it is negative and green if it is positive?
form oninput="o.value = a.valueAsNumber + b.valueAsNumber"
input name="a" id="a" type="number" step="any" +
input name="b" id="b" type="number" step="any" =
output name="o" for="a b">
/form
Not a big fan of just giving answers when users haven't shown what they've tried first but this was actually a bit fun, I've never seen this type of form before.
Like #feeela said, you can use JS to watch for input changes and validate the output field accordingly. I'm using jQuery to do this as such:
$(document).ready(function() {
$('input').change(
function()
{
$('output').removeAttr('class');
var sum = parseInt($('output').first().html());
if (isNaN(sum))
{
$('output').addClass('error');
}
else if (sum < 0)
{
$('output').addClass('negative');
}
else if (sum > 0)
{
$('output').addClass('positive');
}
}
);
});
Then you can use you style sheet to give the output field a colour depending on its class.
​
You can view a demo here: http://jsfiddle.net/S7cVP/

JavaScript Real Time Calculation

I have built a table with custom inputs numbers with jeditable. The Input type is gone once you put the value
I need to find a JavaScript Real Time Calculation which automatically makes the amount of my values.
I have found 2 interesting examples very suitable for my case but there is the possibility to achieve it the same without using the form and inputs?
First example
Second example
Yes, it is. As you know a div element can be accessed by document.getElementById('div_id') and its value can be accessed by document.getElementById('div_id').value.
So take out the form and insert an id for the div's that you need and access the value and then find the sum and then set the value as the sum to another div. Here is the code
<script>
function calculateBMI() {
var wtStr =document.getElementById('w').value;
if (!wtStr)
wtStr = '0';
var htStr = document.getElementById('h').value;
if (!htStr)
htStr = '0';
var weight = parseFloat(wtStr);
var height = parseFloat(htStr);
document.getElementById("r").value = weight + height;
}
</script>
<input id = "w" type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input id = "h" type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input id = "r" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
​and if you don't want input you can use textarea.

Categories

Resources