All I have to do is to show a number in a textbox and a button which add 10 every time I press it, here's my code (it doesn't work).
<head>
<script type="text/javascript">
var n=parseInt(ocument.forms["formNum"]["numero"].value);
document.getElementById("numero").value=n;
function sumar() {
n=document.forms["formNum"]["numero"].value+10;
document.forms["formNum"]["numero"].value=n;
}
function inicializar() {
n=document.forms["formNum"]["numero"].value=0;
}
</script>
</head>
<body>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" />
</p>
<p>
<input type="button" name="sumar" value="Sumar" onclick="sumar()" />
<input type="button" name="inicializar" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
<body>
<script type="text/javascript">
function sumar(){
document.getElementById("numero").value = parseInt(document.getElementById("numero").value)+10;
}
function inicializar(){
document.getElementById("numero").value=0;
}
</script>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" value="0" />
</p>
<p>
<input type="button" value="Sumar" onclick="sumar()" />
<input type="button" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
Five suggestions.
It is always better to give unique ids to your html elements.
Never name your HTML elements and javascript functions the same.
If you want to access the html element from javascript, if you know the id, use getElementById.
Use Firebug or Developer tools from the browser, to debug.
If you want to access your elements with the hierarchy, use elements in the form like this document.forms["formNum"].elements["numero"].value. Check this example
Demo: http://jsfiddle.net/DPJCR/
This code should work:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
See: Set the value of an input field
Maybe you are getting an exception from the parseInt that prevents the value from changing.
If it is an option to use jQuery, try this:
function sumar(){
$("#numero").attr("value", parseInt($("#numero").attr("value"), 10)+10);
}
Try this this will help you
var count=10;
$('#btnSumar').click(function(){
if($('#numero').val()=='')
{
$('#numero').val(count);
}else
$('#numero').val(eval($('#numero').val())+count);
});
$('#btnInc').click(function(){
$('#numero').val('');});
Fiddle here
Related
I have a small project I'm working on, and for some reason chrome says that the code below is undefined.
HTML:
<input type="reset" onclick="cleartxt()" class="rset" value="Clear Text"></input>
Javascript:
var cleartxt = function() {
document.getElementById("text").value = "";
};
Can someone help me figure out why this is functioning this way?
Your code is working fine. Here is the working snippet.
var cleartxt = function() {
alert('reset working');
document.getElementById("text").value = "";
};
<input type="text" id="text" />
<input type="reset" onclick="cleartxt()" class="rset" value="Clear Text"/>
Once you use onclick and call function directly in the dom, you must define a global function and define it before the document fully loaded, eg: put the function definition in the <head>.
The correct way to write an input is
<input type="reset" onclick="cleartxt()" class="rset" value="Clear Text">
without closing tag.
You have to declare the function in the head of your html, and you have tu put the input with the "text" id.
First <input> doesn't have a closing tag. Second if you want to use input type="reset" no need for javascript but they must be inside a form.. See the snippet below..
var cleartxt = function() {
document.getElementById("text").value = "";
};
<input type="button" onclick ="cleartxt()" class="rset" value="Clear Text" >
<input type="text" id="text" >
<br />
<br />
<p>With form</p>
<form>
<input type="reset" class="rset" value="Clear Text" >
<input type="text" id="text" >
</form>
<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onClick="add()" />
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?
Two things wrong here...
1)
<input type="button" value="Add" /> change it to
<input type="button" value="Add" onclick="add()" />
Also,
2)
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
to
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
PS : This is not a assignment solving website :P
First, You Should Change
document.getElementById("result").value = value1 + value2
To This:
document.getElementById("result").innerHTML = n1 + n2
Because value stands for the attribute value for < input >, not the text written
in the tag.
Second, Change The Button Code To:
<input type="button"value="Add"onclick="add()">
This "onclick" is something called event in javascript,
It means at clicking on the button "Add" it performs the funtion called "add()".
If You Are New To Javascript You Will Know Everything.
Just Be Patient.
It worked with the following changes
-> calling add function with onclick event
-> using innerhtml in place of value
<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
console.log(value1,value2)
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()"/>
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
Hope this helps
Its better to put the js at the end of the document - also as noted the onclick handler needs to call the function. I also tidied up the code a little.
<html>
<head>
<title>JavaScript - using function</title>
<style>label{display:block}</style>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()">
<p>Result = <span id="result" ></span></p>
<script>
function add(){
var value1=parseFloat(document.getElementById("n1").value);
var value2=parseFloat(document.getElementById("n2").value);
var total= value1 + value2;
document.getElementById("result").innerText=total;
}
</script>
</body>
</html>
Do you guys know whyn when I place this varables outside the functions, the result is "Not a Number"?.
Dont variables should become "Global" when placed ouside a function?
<html>
<head>
<script type="text/javascript">
// V-LOXY > Variaveis Calculo de Frete
var Comp = document.getElementById('ComprimenTo').value;
var Larg = document.getElementById('Largura').value;
var Alt = document.getElementById('Altura').value;
var TxCubagem = 300
function PesoCubado(){
document.getElementById('PesoCub').innerHTML = ((Comp/100)*(Larg/100)*(Alt/100)*TxCubagem).toFixed(1)+' kg';
}
</script>
</head>
<body>
<label>Comprimento [cm]:
<input id='ComprimenTo' type="number" width="15"/></label><br />
<p></p>
<label>Largura [cm]:
<input id='Largura' type="number" width="15"/></label><br />
<p></p>
<label>Altura [cm]:
<input id='Altura' type="number" width="15"/></label><br />
<p></p>
<input type='button' onclick='PesoCubado()' value="Calcular" >
<p></p>
<p>Peso Cubado: <b id='PesoCub'></b> </p>
</body>
</html>
You need to do 2 things: move your script to below your elements that you are trying to do work on (right before end of body closing), and grab the value of the inputs during the PesoCubado() function invocation:
<html>
<head></head>
<body>
<label>Comprimento [cm]:
<input id='ComprimenTo' type="number" width="15"/></label><br />
<p></p>
<label>Largura [cm]:
<input id='Largura' type="number" width="15"/></label><br />
<p></p>
<label>Altura [cm]:
<input id='Altura' type="number" width="15"/></label><br />
<p></p>
<input type='button' onclick='PesoCubado()' value="Calcular" >
<p></p>
<p>Peso Cubado: <b id='PesoCub'></b> </p>
<script type="text/javascript">
var CompElem = document.getElementById('ComprimenTo');
var LargElem = document.getElementById('Largura');
var AltElem = document.getElementById('Altura');
var PesoCubElem = document.getElementById('PesoCub');
var TxCubagem = 300
function PesoCubado(){
PesoCubElem.innerHTML = ((CompElem.value/100)*(LargElem.value/100)*(AltElem.value/100)*TxCubagem).toFixed(1)+' kg';
}
</script>
</body>
</html>
You've got several problems with your script, which are:
your variables point to the initial value of the text fields, and as such, won't be using the latest value. You should get the values of each field within your PesoCubado function.
Values returned from inputs are always strings and as such, you'll have to convert them to a number using the Number function.
You'd be best wrapping your code in a load event listener on the window to ensure your page is loaded fully.
Hopefully this helps.
Tom
so I have a project now, as an addition to my company's website, we want to show our clients how much they can save on gas by buying one of our electric cars, I'm responsible for making it happen, I don't know how to approach this using javascript, can you guys give me a hand? our marketing guy got the idea from this website, that is basically what we want, but I was hoping i could make it a little better on some aspects:
1st-the client wouldn't have to press submit to see the results, as they fill the last field, the calculated part is populated automatically, for this i've been fiddling with the onChange event, unsuccessfully though xD
here's what I have so far, it is not working, at least on dreamweaver's live mode, haven't tested it online yet as I was hoping to develop the whole thing offline:
<script type="text/javascript">
function calc(){
var km=document.getElementById(km).value;
var euro=document.getElementById(euro).value;
var consumo=document.getElementById(consumo).value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
return fossil_day;
}
</script>
<form name="calc" id="calc" >
<p>
Km/dia
<input type="text" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="text" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="text" onChange="calc()" name="consumo" id="consumo" value="" />
</p>
<input type="button" onClick="calc()" name="submit" id="submit" value="Calcular" />
<script type="text/javascript">
var fossil_day = calc();
document.write('<p>'+fossil_day+'</p>');
</script>
</form>
Please note that although I have this already, I wouldnt mind not doing this at all and using another solution, even if it doesnt use forms, I'm just showing what i have already so you can tell me how I'm wrong and how I can have a better approach at it
there are many errors inside your code
document.getElementById() needs the element id in brackets ''
you can't create a element with the same name,id as a function calc else it will throw an error as it's an object and not a function.
your executing the function onload... but you want it to be executed when the button is clicked & onchange.
you don't need to add value if empty and name if you use getElementById
return false in the function on buttons inside form else it could send the form and so refresh the page.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>calc</title>
<script>
function calc(){
var km=document.getElementById('km').value;
var euro=document.getElementById('euro').value;
var consumo=document.getElementById('consumo').value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
document.getElementById('result').innerHTML=fossil_day;
return false
}
</script>
</head>
<body>
<form>
<p>Km/dia<input type="text" id="km"/></p>
<p>€/Litro<input type="text" id="euro" /></p>
<p>Litros/100km<input type="text" onChange="calc()" id="consumo" /></p>
<input type="button" onClick="calc()" value="Calcular" />
</form>
<div id="result"></div>
</body>
</html>
Useing jQuery (and html5 type="number" form fields):
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<p>
Km/dia
<input type="number" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="number" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="number" name="consumo" id="consumo" value="" />
</p>
<div id="fossil-day"></div>
</form>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function calculate(){
var km = $('#km').val();
var euro = $('#euro').val();
var consumo = $('#consumo').val();
var cem_km = consumo*euro;
var fossil_day = (cem_km*km)/100;
$('#fossil-day').html(fossil_day);
}
$(function() {
/*when #consumo input loses focus, as per original question*/
$('#consumo').blur(function(){
calculate();
});
});
</script>
</body>
</html>
Suppose I have the following HTML code, how can I pass the user's input to execute(str) JavaScript function as an argument?
<body>
<input name="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(//send the user's input in textbox1 to this function//)" type="button" value="Execute" />
</body>
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:
var text = document.getElementsByName("textbox1").value;
You could just get the input value in the onclick-event like so:
onclick="execute(document.getElementById('textbox1').value);"
You would of course have to add an id to your textbox
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
if I have understood correct the question :
<!DOCTYPE HTML>
<HEAD>
<TITLE>Passing values</TITLE>
<style>
</style>
</HEAD>
Give a number :<input type="number" id="num"><br>
<button onclick="MyFunction(num.value)">Press button...</button>
<script>
function MyFunction(num) {
document.write("<h1>You gave "+num+"</h1>");
}
</script>
</BODY>
</HTML>
document.getElementById('textbox1').value
You can get textbox value and Id by the following simple example in dotNet programming
<html>
<head>
<script type="text/javascript">
function GetTextboxId_Value(textBox)
{
alert(textBox.value); // To get Text Box Value(Text)
alert(textBox.id); // To get Text Box Id like txtSearch
}
</script>
</head>
<body>
<input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" /> </body>
</html>