First of all, please help me figure this purely in JavaScript. No jQuery or any plugins. I'm trying to code this to work in Cordova/PhoneGap. I'm teaching myself JavaScript at the same time as I'm playing with Cordova/PhoneGap so please be gentle.
I've got a textbox with buttons on either side, right for adding 1 to the textbox value (+ on it) and left for minusing 1 from the text box (- on it). My purpose is to have the page/app load for the first time showing a 0 value in the text box. As soon as someone presses the + button, the textbox should increment from 0 to 1 and by a further 1 with every click of the +. If the app is closed and re-opened, it should remember the last number that was in the textbox before the app was closed.
It works in browser testing, it causes PhoneGap's iPhone app to no longer recognize PhoneGap gestures of resetting the app and such, pressing the +/- button increments/decrements the textbox too slowly, and it can go negative despite setting min="0". What am I doing wrong? (I know localStorage can't be done in the code snippet due to sandboxing so if you'd rather I put up a JSFiddle or something, just tell me what to do.)
window.onload = function(){
var CapsNum = localStorage.getItem("CapsNum");
if(CapsNum == null) {
CapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}}
window.onbeforeunload = function(){
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value++);
}
function MinusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value--);
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="MinusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="PlusCaps()" />
So it seems like you are changing and persisting the value into local storage. This won't update the value on the page. I create a small function by modifying your example that can update the state in localstorage and it updates the value in the textbox at the same time.
window.onload = function() {
//var CapsNum = localStorage.getItem("CapsNum");
if (CapsNum == null) {
CapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}
}
window.onbeforeunload = function() {
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) + 1;
setNextValue(nextValue);
}
function MinusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) - 1;
setNextValue(nextValue);
}
function setNextValue(nextValue) {
//localStorage.setItem("CapsNum", nextValue);
document.getElementById("caps").value = nextValue;
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="PlusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="MinusCaps()" />
Related
I just want to show the result in this div ,i tried to use nodeValue instead value and call the finalCalc fun in js file but it show nothing when i click on the button.
var billValue=document.getElementById("dollars").value,
peopleValue=document.getElementById("people").value,
theResult=document.getElementById("result"),
calculateButton=document.getElementById("calculateButton");
function calculateTip(x,y){
var reso=x*y;
theResult.innerHTML=reso;
}
function finalCalc() {
calculateTip(billValue,peopleValue);
}
<form>
<label>how much was your bill?</label>
<label for ="dollars">$</label>
<input value ="0" type="text" id="dollars" placeholder="Bill Amount ">
<br>
<label for="people">How many people are sharing the bill?</label>
<input value ="0" type="text" id="people">
<button type="button" id="calculateButton" onclick()="finalCalc()">CALCULATE</button>
<div id="result"></div>
</form>
onClick is written as onClick="" instead of onclick()="", reworked your code a little, hope this helps.
var billValue = document.getElementById("dollars").value,
peopleValue = document.getElementById("people").value,
theResult = document.getElementById("result"),
calculateButton = document.getElementById("calculateButton");
function calculateTip(x, y) {
return x * y;
}
function finalCalc() {
theResult.innerHTML = calculateTip(billValue, peopleValue);
}
<button type="button" id="calculateButton" onClick="finalCalc()">CALCULATE</button>
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.
This is what I have tried to do but it gives me NaN
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(this.value)">
<input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Your code is not working because in your #button1 you wrote:
onclick="temperatureConverter(this.value)"
where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".
To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".
Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.
Generally, it is not encouraged to use the same function to perform completely different actions.
function temperatureConverter(){
var input = document.getElementById('inputFahrenheit');
var value = input.value;
value = parseFloat(value);
var output = document.getElementById('outputCelcius');
output.innerHTML = (value - 32)/1.8;
}
function resetTemperature(){
/* clear the temperature */
console.log('clear');
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter()">
<input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">
<input id= "reset1" type= "reset" value= "Clear">
</p>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:
// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
function updateOutput(value) {
// make sure you do some checking to avoid XSS attacks.
document.querySelector('#output').innerHTML = value;
}
// keeps the form from submitting since we don't have an actual form handler and this is all front-end
document.querySelector('#converterForm').addEventListener('submit',(e)=>{
e.preventDefault();
});
document.querySelector('#convert').addEventListener('click', () => {
updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
});
});
function convertToCelsius(f) {
if(typeof f == 'string') f = parseFloat(f, 10);
if(isNaN(f)) {
throw new Error('Invalid parameter passed to function convertToCelsius');
}
return (f-32) * 5 / 9;
}
<form id="converterForm" action="/">
<input type="number" id="fahrenheit" placeholder="Fahrenheit value">
<input type="button" id="convert" value="Convert to Celsius">
<input type="reset" value="Clear">
<div id="output">
</div>
</form>
Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).
can't see you using any form.
your function,
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
then,
<form id="tempConverter">
Convert: <input type="text" id="unit" name="converter" />
<input
type="button"
value="Submit"
onclick="temperatureConverter(document.getElementById('unit').value);"
/>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.
I am trying to create a page that lets the user enter three numbers, and have the max and min values printed below from the input. I've used both the Math.max/min functions and also tried an if statement but When I click submit nothing shows up. Some insight would be greatly appreciated, thanks!
function max() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var z = document.getElementById("num3").value;
var maximum = Math.max(parseInt(x), parseInt(y), parseInt(z));
document.getElementById("max").innerHTML= maximum;
}
function min() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = parseInt(document.getElementById("num3").value);
document.getElementById("min").innerHTML = Math.min(x,y,z);
}
And here is my html
<p>Enter First Number:</p>
<input type="text" name = "number1" id="num1"><br>
<p>Enter Second Number</p>
<input type="text" name = "number2" id="num2"><br>
<p>Enter third number</p>
<input type="text" name = "number3" id="num3"><br>
<input type="submit" value="Submit" onclick="max(); min(); "><br />
<p>Max =</p><p id ="max"></p><br />
<p>Min =</p><p id ="min"></p><br />
replace <input type="submit"/> to <button type="submit" value="" onclick="minmax();">Submit</button>
and add JS function:
function minmax() {
min();
max();
}
Your problem seems related to how you are attaching your event.
It works OK when I use:
document.querySelector( '[type="submit"]' ).addEventListener( 'click', function() {
max();
min();
}, false );
http://jsfiddle.net/yemxrmqq/
You just need to change the tag related to the button, instead of:
<input type="submit" value="Submit" onclick="max(); min(); "><br />
just put:
<button type="submit" value="Submit" onclick="max(); min()">Click</button><br />
None of the answers here tell you why your code didn't work.
Identifiers in inline listeners are first resolved as properties of the element on which they are placed. Input elements have a default max attribute, so within an inline listener, the identifier max will reference the input's max property. Hence in any document:
<input onclick="console.log(max)">
shows '' (i.e. empty string).
So you can either change the names of the functions to something more meaningful, or change the context from which they are called so that the identifiers aren't resolved on the element, and the OP code works. e.g.
<input type="submit" value="Submit" onclick="callBoth()">
and
function callBoth() {
max();
min();
}
Incidentally, an input type submit outside a form is just a button, so you should use:
<input type="button" ...>
On my original post I wasn't for sure on the amount of depth I should go to. Here is what I have been working on since the jQuery answer was posted:
I am attempting to execute a task which requires the user to choose and click one html button out of a series of buttons and then be required to choose another html button out of a series of buttons.
Essentially I would like the value of the first button selection to be passed as a parameter to a function that will run when the user clicks the second button. I'm just learning javascript and I'm lost.
Thank you
HTML:
<form id="scoreboard">
<div>
<input type="text" name="homeTeam" value="00" size="2" "readonly" id="homeTeamScore"/>
<input type="button" value="+1" name="add1" id="homeAdd1" class="homeScore" onClick="calcScore(1)"/>
<input type="button" value="-1" name="neg1" id="homeNeg1" class="homeScore" onClick="calcScore(4)"/>
</div>
<div>
<input type="button" name="homeP1" id="homeP1" class="player" value="24" style="text-align:center;"/>
<input type="text" name="homeP1Score" value="0" size="2" style="text-align:center;"/>
</div>
<div>
<input type="button" name="homeP2" id="homeP2" class="player" value="44" style="text-align:center;"/>
<input type="text" name="homeP2Score" value="0" size="2" style="text-align:center;"/>
</div>
</form>
Javascript:
function calcScore(amount) {
if(amount==1) {scoreboard.homeP1Score.value++;scoreboard.homeTeam.value++;}
else if(amount==4) {scoreboard.homeP1Score.value--;scoreboard.homeTeam.value--;}
}
$('.player').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('.homeScore').click(function() {
function addHomeScore(data)
});
});
Using jQuery:
$('#buttonId').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('#button2Id').click(function() {
yourFunction(data);
});
});
This method is better because it uses JavaScript scoping to avoid globals. Since JavaScript (especially with jQuery) sometimes has multiple threads/functions executing at the same time, it's very easy to run into problems with globals. They're also very hard to test and unsafe.
In raw JavaScript:
HTML:
<button class="button1" onclick="saveValue()" />
<button class="button2" onclick="callMethod()" />
JavaScript:
myGlobalVariable = null;
function saveValue(){
myGlobalVariable = "Value That Was Selected";
}
function callMethod(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
}
In jQuery:
HTML:
<button class="button1" />
<button class="button2" />
JavaScript:
myGlobalVariable = null;
$('button.button1').click(function(){
myGlobalVariable = "Value That Was Selected";
});
$('button.button2').click(function(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
});
setup some global variable in js. then on each button setup some onClick events that go and change the global var. then the next button click can check to see the value in the global var
<button onclick="myFunction()">Click me</button>
I'm having trouble in doing a javascript that will do the following:
Increase/decrease number inside textbox when image clicked.
setting a limit for that textbox (not below zero, not above x)
please know i have many text boxes in the same page, so how can this issue be fixed?
You don't need to (and shouldn't) set ids for each and every image and input field. You will need to set name attributes for each input field though (so your server code can tell them apart - but not for JS).
If the "add" section for each row looks like:
<div>
<img src='minus.png' onclick="increment(this.parentNode.getElementsByTagName('input')[0]);" />
<input type='text' name='product_1010101011' />
<img src='plus.png' onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);" />
</div>
use this javascript:
function increment(myInput) {
// use Mike Samuel's code here
myInput.value = (+myInput.value + 1) || 0;
}
function decrement(myInput) {
// use Mike Samuel's code here
myInput.value = (myInput.value - 1) || 0;
}
I think this should get you going:
<form>
<input type="button" id="minus" value="-"
onClick="textb.value = (textb.value-1)">
<input type="text" id="textb" name="name" value="1" />
<input type="button" value="+"
onClick="textb.value = (+textb.value+1)">
</form>
Live example here
To increment
myInput.value = (+myInput.value + 1) || 0;
To decrement
myInput.value = (myInput.value - 1) || 0;
The || 0 will reset any value that doesn't parse as an integer to a default value, 0.