How can i save a value in the textbox to a variable - javascript

I want to store the value given in the text box in a variable. I am beginner to javascript. Please help me out. Here s my code.
<!DOCTYPE html>
<html>
<body>
Days of Journey: <input type="text" id="doj" name="daysofjourney">
<input type="button" value="submit" onclick="dayscounter()">
<script language="javascript" type="text/javascript">
var travel = document.getElementById("doj").value;
function dayscounter() {
var days;
for(days = 1; days <= travel; days++) {
document.write(days);
}
}
</script>
</body>
</html>

You nearly had it already...
function dayscounter() {
var travel = document.getElementById("doj").value;
var days;
for(days=1;days<=travel;days++)
{
document.write(days);
}
}
The problem was, that your first assignment of the variable travel is made as soon as the HTML code is loaded. The user can't have made an input yet at that time, thus the variable stays empty. If you include document.getElementById("doj").value inside the function, you will get the value at that specific time you launch the function.

Just parse value to int
var travel = +(document.getElementById("doj").value;);

You can use 'value' attribute of an text input to set it's value like:
<input type="text" id="textid" value="value content" />
and you can do your function like this:
<script language="javascript" type="text/javascript">
function dayscounter()
{
var travel = document.getElementById("doj").value;
var days;
var result = "";
for (days = 1; days <= parseInt(travel); ++days)
{
document.getElementById("result").value += " " + days;
}
}
</script>
Days of Journey:
<input type="text" id="doj" name="daysofjourney" />
<input type="button" value="submit" onclick="dayscounter()" />
<p>
<input type="text" id="result" />
</p>

Related

Javascript - increment and double a value

I want to write my first code. I made this, but it still needs a change.
There is shown a value and this value can be changed with 2 buttons. When the buttons Increment is pushed, the value has to go with one higher. If the button Double is pressed, then the value has to be double (e.g. going from 3 to 6). Now it is coded like a decrement, but this needs to be changed.
var x = 0
var element = document.getElementById("value");
element.innerHTML = x;
function button1() {
element.innerHTML = ++x;
}
function button2() {
element.innerHTML = --x;
}
<html>
<body>
<title> First code </title>
<body>
<div id="value"></div>
<input type=button value="Increment" onclick="button1()" />
<input type=button value="Double" onclick="button2()" />
</body>
</html>
You need to multiply by 2 rather than subtract 1.
There's no need for the x variable, you can operate directly on the innerHTML. JavaScript's type juggling will automatically convert it to a number when you use these arithmetic operators on it.
var element = document.getElementById("value");
element.innerHTML = '0';
function button1() {
element.innerHTML++;
}
function button2() {
element.innerHTML *= 2;
}
<html>
<body>
<title> First code </title>
<body>
<div id="value"></div>
<input type=button value="Increment" onclick="button1()" />
<input type=button value="Double" onclick="button2()" />
</body>
</html>

I can't seem to define variables in my code, because document.getElementById( ) won't insert the value in it [duplicate]

This question already has an answer here:
The values for document.getElementById().value are null
(1 answer)
Closed 10 months ago.
I am trying JavaScript and HTML with a little CSS (that is not required), and I can't seem to define this variable.
I have the element id with this HTML code:
<p class="margin"><b>Got </b>
</p><input type="text" class="margin" id="iGotThis">
<p class="margin"><b> out of </b></p>
<input type="text" class="margin" id="outOfThis">
and get it into a variable with js and this code:
var made = document.getElementById("iGotThis").value;
var total = document.getElementById("outOfThis").value;
var perMade = made / total;
and I am trying to alert the result with an alert function:
document.getElementById("submit").click();
}
});
function perFunction() {
alert(total);
};
Here is the full code:
<!DOCTYPE html>
<html>
<head>
<style>
.margin {
margin-left: 80px;
}
</style>
</head>
<body>
<br>
<br>
<p class="margin"><b>Got </b></p><input type="number" class="margin" id="iGotThis"><p class="margin"><b> out of </b></p><input type="number" class="margin" id="outOfThis">
<br>
<br>
<input type="submit" id="submit" class="margin" onclick="perFunction()">
<script>
var iGotThis = document.getElementById("iGotThis").value;
let outOfThis = document.getElementById("outOfThis").value;
var perMade = iGotThis / outOfThis;
// This entire portion has no use for the variables
var input = document.getElementById("outOfThis");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
// This is where the useless section ends
function perFunction() {
alert(iGotThis.value);
};
</script>
</body>
</html>
I have tried just alerting the variable made or total but just comes up blank. I can't think of a solution so I am hoping someone can help. I am still pretty new to this stuff and can't so everything.
there is no ID as "total" in the HTML code. Please check that
Input type=textbox is wrong. You can use type=text. Maybe the browser doesn't understand textbox's value, because textbox isn't an official HTML type value. You see an textbox, because the browser doesn't know what IT should use.

Pass a Value from Button to Text Field in JavaScript

I'm trying to pass a number to a text field on button click. User hits "add to cart" and the 2499 is added to the total already in the text field.
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
<button id="scart" value="Add to Cart" onclick="addCart()" +='2499'"/>
<script type="text/javascript">
var total=""
function addCart(){
document.getElementById('scart').value;
total+= document.getElementById('display').value;
console.log(total);
}
</script>
When learning, I feel that I understand the logic, but don't know the syntax.
I think this is what you want. I made a codepen for you: https://codepen.io/NeilGBK/pen/boGadz?editors=1111
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
</form>
<button id="scart" onclick="addCart(2499)">Add To Cart</button>
<script>
function addCart(v){
document.getElementById('display').value = v
console.log(v);
return false;
}
</script>
I'm passing the number to the function and simply using that to change the value of the input. I'm also logging it to the console
You have some errors, your quotes are not matching and you don't have closing button tag. Also, why don't you add 2499 in the code?
How about this:
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
<button id="scart" value="Add to Cart" onclick="addCart()" >
</button>
<script type="text/javascript">
var total=""
function addCart(){
document.getElementById('scart').value;
total+= document.getElementById('display').value + 2499;
console.log(total);
}
</script>
</form>
It's not clear what you are trying to do so I made the beginning of a "cart" button where the input is the quantity you want to add to cart.
I then print out the number typed in and the total if you pressed the button more than once.
<input id="display" type="text" name="output" size="6" placeholder="0000" />
<button id="scart" type="button">Add to cart</button>
<script type="text/javascript">
var total = 0;
var display = document.querySelector('#display');
var scart = document.querySelector('#scart');
scart.addEventListener('click', function() {
var str = display.value;
var num = parseInt(str, 10);
console.log('You entered the number: ', num);
if (!isNaN(num)) {
total += num;
}
console.log('The total is now: ', total);
});
</script>
There are many things that is wrong here:
First, replace + with a good indicator data-value or whatever
<button id="scart" value="Add to Cart" onclick="addCart()" data-value="2499"/>
Second, In your script you should make var total a number not string.
var total = 0;
Finally, your addCart() function.
function addCart() {
// I see you are trying to get the value of the clicked button so you need to store it as this does not do anything
// document.getElementById('scart').value;
var value = document.getElementById('scart').value;
// Add it to total var;, you need to parseInt it as .value returns string
total += parseInt(value);
// put it on display
document.getElementById('display').value = total;
}
Hope that helps.

having trouble with javascript

Beginer to javasctipt. I am trying to write a simple calculation that will display some text if the time since oil change is past 6 months, the amount of oil left in the car is less then it started and finally display if everything is ok.
Thanks for the help
JavaScript
function oil(){
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.oil.result.write(aa);
}else{
document.oil.result.write("Everything Is all good");
}
}
HTML
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick = oil()>
<input name=result readonly>
</form>
There are a couple of problems with your code
Missing Form close tag
Your controls don't have IDs
missing quotes on the result input
Don't need to use a submit input when you're not submitting to a form. Try button
Not sure what document.oil.result.write(aa); will do. I think the correct process is to get the input using document.getElementById and then set the value of the control
I will try to answer your question with the least number of line changes. This is not the optimal answer. Comments have been added to help you understand required changes. Your HTML and JavaScript are invalid, so it was a surprise to me how they both ran on Chrome.
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function _oil(){ // oil() conflicts with your form's name
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.write(aa); // you can't .write() to an element
}else{
document.write("Everything Is all good");
}
window.event.preventDefault(); // so your window does not load the same page when you submit
return false;
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick ="_oil()"> <!-- you must enclose the onclick attribute, even if both work -->
<input name=result readonly>
</body>
</html>
May be like this:
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function oil(){
var start = document.getElementsByName("start")[0].value;
var lastOilChange = document.getElementsByName("time")[0].value;
var totalOil = document.getElementsByName("amount")[0].value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.getElementsByName("result")[0].value = aa;
}else{
document.getElementsByName("result")[0].value = "Everything Is all good";
}
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="thisform">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="button" value="go" onclick = oil()>
<input name=result readonly>
</form>
</body>
</html>
!!! The form name can not use oil
What you want is to set the value of the form field rather than trying to use write:
if( lastOilChange > 6 || start < totalOil){
document.oil.result.value = aa;
} else {
document.oil.result.value = "Everything Is all good";
}
As pointed out in other answers, though, you also need to prevent the form from trying to submit information to the server and reload the page. There are several ways of doing this (see e.g. JavaScript code to stop form submission). One is to replace the submit button with an ordinary button (<input type="button" value="Calculate" />).
Another is to attach your function to the form as an event handler, and return false at the end of it.
document.oil.onsubmit = function () {
...
return false;
}
(JSFiddle)

insert text to selected Textbox use Javascript

I have 2 textBox and 1 button!
I want to insert text to one of these textboxs. When I click to textbox_1 and click button, mytext will appear at textbox_1. When I click to textbox_2 and click button, mytext will appear at textbox_2.
How can I do this by using JavaScript?
Please help me! I'm new on JavaScript!
put id's of the two textboxes as textbox_1 and textbox_2 and put onclick='onCLickButton();' on the <button> tag
and write the following code in the script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies actually I am used to use these functions as I have my own js file having these functions.
please add onfocus='onFocusInput(this);' in the <input> tags and add the following code in the script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
Take a look at the onFocus() attribute for the INPUT tag - and think about keeping track of what was last given the focus. I'm being a little vague as this sounds a lot like homework.
It isn't the prettiest / most delicate solution, but it works and you can build off it to fulfill your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a form such as
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>

Categories