JS input value assigning to variable - undefined - javascript

I'm really fresh to JS
Need some help because I don't understand a thing.
If I try to assign the whole line to variable, I can use this variable later, but the outcome of that is blank or undefined, when I'm trying to log this to console, or either alert that
using opera/chrome it's still the same, am I doing something wrong?
HTML
<input type="text" id="name" placeholder="username">
JS
not working
var name = document.getElementById('name').value;
console.log(name);
can't do that either
var name = document.getElementById('name');
console.log(name.value);
innerHTML not working
I can do only that
console.log(document.getElementById('name').value);
UPDATING THE CODE TO FULL EXAMPLE
So I've changed the variable name to nameInp but it isn't working
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<input type="text" id="name" placeholder="podaj imię">
<input type="text" id="name2">
<input type="text" id="name3">
<!--
<input type="password" id="password" placeholder="podaj hasło">
<input type="password" id="confPassword" placeholder="powtórz hasło">
-->
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
<!--
<p id="para"></p>
-->
<div class="center"></div>
<div class="center2"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="main.js"></script>
</body>
</html>
var nameInp = document.getElementById('name').value;
var btn = document.getElementById('submit');
function check(){
console.log(nameInp);
}

Here's your code reduced to the relevant parts:
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
The problem is that var nameInp = document.getElementById('name').value; is executed right when main.js is loaded (which happens as part of the whole page loading). At that point the input field has no value yet, so this is equivalent to var nameInp = "";.
Later, when the user clicks on the submit button, the check function runs, but nothing has changed the nameInp variable. It still contains "", so you get no output.
Here's a clearer demonstration of the problem, where the initial value is not "" but "initial value":
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię" value="initial value">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Every time you click on wyślij, initial value is printed because that's what nameInp was initially set to.
Fix:
var nameInp = document.getElementById('name');
function check() {
console.log(nameInp.value);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Here we only retrieve the .value of the input field at the time check() is run, i.e. when the button is clicked.

You can't see anything in the console because you're outputting the value of the input when the script is called so essentially on page load. At this point the input box hasn't been filled yet. That's the console.log doesn't show anything.
You can, for example, run your function every time the user types inside the input box. For this you will need an event listener:
Select the element you desire to 'watch' and call the addEventListener() method on it. It takes the event type and a callback function as parameters.
Lastly, in the callback function, we get the value of the input box by accessing the target of the event: e.target. e being the event object and e.target the property target of the event.
The code below will call a console.log() every time the user types in the input box:
document.querySelector('#username').addEventListener('keydown', function (e) {
console.log(e.target.value);
});
<input type="text" id="username" placeholder="username">

I have made a script for all three cases, use it according to your need.
<html>
<head>
<script>
function Consolify() {
var firstMethod = document.getElementById('name').value;
console.log('firstMethod = ', firstMethod);
var secondMethod = document.getElementById('name');
console.log('secondMethod = ', secondMethod.value);
console.log('thirdMethod = ', document.getElementById('name').value);
}
</script>
</head>
<body>
<input type="text" id="name" placeholder="username">
<button onclick="Consolify()">Consolify</button>
</body>
</html>

Related

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

Form button 'Cannot set property 'onclick' of null' [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I can't determine what is 'null'. I think it may be the form button, because of the form and button ids aren't the same... The console is saying the problem is on the 'button1.onclick = createParagraph;' line. Please help.
Below is my javascript
//global variables for user input
var noun1;
var noun2;
var adjective1;
var adjective2;
var verb1;
var verb2;
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
//to retrieve values from user input, and write to global variables
function handleSubmit(form) {
noun1 = form.querySelector('input[name=noun1]').value;
noun2 = form.querySelector('input[name=noun2]').value;
adjective1 = form.querySelector('input[name=adjective1]').value;
adjective2 = form.querySelector('input[name=adjective2]').value;
verb1 = form.querySelector('input[name=verb1]').value;
verb2 = form.querySelector('input[name=verb2]').value;
return false;
}
//to write paragraph to the DOM
function createParagraph () {
var element = document.createElement("p");
var content = document.createTextNode("paragraph1");
var location = document.getElementById("placeholder");
element.appendChild(content);
document.body.insertBefore(element,location);
}
//run it all!
button1.onclick = createParagraph;
Below is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="stylesheets/madlib.css">
<script src="randomMad.js"></script>
<title>Mad Libs!</title>
</head>
<header>
</header>
<body>
<form onsubmit="return handleSubmit(this)" id="form1">
<h1>Choose your words!</h1>
<fieldset>
<label>First Noun: <input type="text" name="noun1" ></label><br>
<label>Second Noun: <input type="text" name="noun2"></label><br>
<label>First Adjective: <input type="text" name="adjective1"></label><br>
<label>Second Adjective: <input type="text" name="adjective2"></label><br>
<label>First Verb: <input type="text" name="verb1"></label><br>
<label>Second Verb: <input type="text" name="verb2"></label><br>
</fieldset>
<button type="submit" id="pushMe">Create Mad Lib</button>
</form>
<div id="placeholder">
</div>
</body>
You are missing ; in some of your lines..
See
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
Kindly add a ; at the end of that two lines.
UPDATE
The error may be causing because you are trying to access the element before the DOM has finished loading. Thus to solve that problem, you can just move
<script src="randomMad.js"></script>
to the end of <body> .

Form textbox content with javascript

I would like to know if there is better way to this exercice.
Here it is : Create a form that contain a textbox ;after the user enter the text ,all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form( hint: use change onChange event handler).
I have written this code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event</title>
</head>
<body>
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>
</body>
</html>
Basically i'm replacing the content of the textbox by the formatted
Might be too easy, but setting the text over a style to lowercase transform doesn't allow uppercase :)
function toLower(element) {
if (element && element.value) {
element.value = element.value.toLowerCase();
var target = document.getElementById('realvalue');
target.innerHTML = element.value;
}
}
<input type="text" onblur="toLower(this)" />
<div id="realvalue"></div>
But, if all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form, your code work correctly...
http://jsfiddle.net/b6xwde62/
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>

html5 required attribute custom validation message not working

I have a simple form with two inputs and a submit button. I need to display the message depending on the lang attribute. When I click on submit button it displays the message even though the field is filled with valid data.
<!DOCTYPE html5>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="" method="get">
<input type="text" value="" oninvalid="check(event)" required/>
<input type="text" value="" oninvalid="check(event)" required/>
<input type="submit" value="Save">
</form>
<script type="text/javascript">
function check(e) {
var a=document.documentElement.lang;
var validateMsg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
var input = e.target;
if(input.validity.valid){
return true;
}else{
input.setCustomValidity(validateMsg);
return false;
}
}
</script>
</body>
</html>
check(event) is meaningless. The event parameter is passed internally
checking validity inside the oninvalid handler is useless
If you use only oninvalid, you won't be able to change back the validation message once the user starts filling the field. You should use the change, keyup or keydown event for that, depending on the reactivity you want.
This could work:
<input type="text" value="" onchange="check" required />
// ...
function check(e) {
var input = e.target;
var msg = "";
if(!input.validity.valid) {
var a=document.documentElement.lang;
msg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
}
input.setCustomValidity(msg);
}

Create a "calculation form" in javascript

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>

Categories