unable to get input value from <input> - javascript

I can't seem to get the input value for "name", I have tried using .value in JS but when I run the code I get undefined.
HTML code
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div
JS code
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
name = document.getElementById("fname");
message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}

Just use var for create variable and all work.
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
var name = document.getElementById("fname");
var message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div>
I suggest you to see this post:
Is var necessary when declaring Javascript variables?

you can simply do .value in the same line and get the value of the element
name = document.getElementById("fname").value;
console.log(name)

You must put all your codes into window.onload. This method running your code when all elements in page loaded. And this will solve your problem.
window.onload = () => {
//some js codes
}

Related

How do I use a JavaScript function inside my HTML to get input and provide output?

I am using BootStrap 4.
I have the following function:
function AcceptInput(text){does stuff}
I have a form that contains 1 button and a textarea:
<form action="" class="container p-3 my-3 bg-dark text-white">
<div class="form-group">
<label for="comment">Your Text:</label>
<textarea class="form-control" rows="5" id="comment" name="text"></textarea>
</div>
<button onclick="" type="button" class="btn btn-primary">Submit</button>
</form>
I want to use my AcceptInput function in this form when the button is pressed. The text from the text-box needs to be passed as the AcceptInput function's text variable, then, when the function returns a string value, that string needs to be written into another text box as output. How do I do get the strings from the text-box and use the return value in HTML?
When your AcceptInput function is called, you can use
document.getElementsByClassName("form-control")[0].value;
to get the value inside the textarea.
You can change the type of button from "button" to "submit" - this will emit submit event on the form.
Then you need to add submit event listener for this event - .addEventListener().
You need to ensure that on submisison of form, it does not try browser default behavior to contact server for http request - use e.preventDefault().
then you can take the text, do the transformations using your function and then output the transformed text wherever you want - here I have changed the text to uppercase.
Here is the code:
function AcceptInput(text){
console.log("dbg1 does stuff", text);
// for eg: converting to upper case
return text.toUpperCase();
}
var formElem = document.getElementById("mainForm");
formElem.addEventListener("submit", function(e) {
e.preventDefault();
var textElem = document.getElementById("comment");
var text = textElem.value;
var transformedText = AcceptInput(text);
var outputElem = document.getElementById("output");
outputElem.innerText = transformedText;
})
<html>
<body>
<form id="mainForm" action="" class="container p-3 my-3 bg-dark text-white">
<div class="form-group">
<label for="comment">Your Text:</label>
<textarea class="form-control" rows="5" id="comment" name="text"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<p id="output"></p>
</body>
</html>

In my HTML document, when I tried to log out the input value, it is undefined. Why?

I've been trying to make a simple form validation js project, and my first logic statement itself had an error. When I tried to log out the value of my input it says that it is undefined:
<!--skipped css-->
<html>
<head>
<title>
Form validation
</title>
</head>
<body>
<div class="transparent">
<div class="form">
<h1 class="login"> Login </h1>
<form>
<label for="name" class="LName">Name</label>
<input class="name" id="name" name="name" placeholder="Enter your username"><br>
<label for="email" class="LEmail">E-mail</label>
<input class="email" id="email" name="email" placeholder="Enter your E-mail"> <br>
<label for="password" class="LPassword">Password</label>
<input type="password" class="password" id="password" name="password" placeholder="Enter your password"><br>
</form> <br>
<button class="btn"> Login </button>
<br> <br>
<span> OR </span><br> <hr>
<button class="gbtn"> <i class="fab fa-google"></i> Sign in with Google </button>
</div>
</div>
<script>
var name = document.getElementById('name');
var email = document.querySelector('.email');
var password = document.querySelector('.password');
var btn = document.getElementsByClassName('btn')[0];
btn.onclick = empty;
function empty() {
name = document.getElementById('name');
console.log(name.value);
if(name.value == "") {
name.classList.add('errInp');
}
}
</script>
</body>
</html>
I believe I've assigned all the vars, and I've tried changing it to innerText too, only to get another undefined. Can someone help me out?
I believe your choice of 'name' as the variable name is the problem! By assigning a variable using var name in global scope, you are clashing with window.name. Normally you set the window's name using window.name='some name' (a string). In your case where you try to assign an HTML element to it, JS calls .toString() under the hood, so the window name is actually "[object HTMLInputElement]", which has no value property.
You can solve it by changing the variable name to something else, or getting rid of the first var name = altogether and inside empty using const name = document.getElementById('name'); instead of name =....
In addition to see sharper's explanation, since the introduction of ES6, there are only few cases where declaring variables with var is a good choice. A rule of thumb is to declare a variable as const (a constant reference to a value, but not immutable) at first and change it to let later on if you need to reassign its value. Refer to this answer for a more detailed explanation.
const validateForm = () => {
const name = document.querySelector('#name').value
const password = document.querySelector('#pwd').value
if (!name || !password){
alert('invalid input')
}
else{
alert(`form is submitted for name ${name} with the password ${password}`)
}
}
Name: <input type="text" id="name">
Password: <input type="password" id="pwd">
<button onClick="validateForm()">Login</button>

Unable to store form data into session storage

I just started to learn JavaScript and I was trying to let user input form data and store them into session storage but I can't seem to do so. Please shed some light on this, thank you.
JavaScript
$(function() {
$("formset").submit(function (event) {
event.preventDefault();
var name = $("#fullname").val();
var email = $("#email").val();
var phonenumber = $("#phonenumber").val();
var message = $("#message").val();
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("Fullname", name);
sessionStorage.setItem("E-mail", email);
sessionStorage.setItem("Phoneno", phonenumber);
sessionStorage.setItem("Msg", message);
}
});
});
HTML
<form id="formset" class="main_form">
<div class="row">
<div class="col-md-12 ">
<input class="contactus" placeholder="Full Name" type="text" id="fullname" required>
</div>
<div class="col-md-7">
<input class="contactus" placeholder="Email" type="tel" id="email" required>
</div>
<div class="col-md-7">
<input class="contactus" placeholder="Phone Number" type="text" id="phonenumber" required>
</div>
<div class="col-md-12">
<textarea class="contactus1" placeholder="Message" type="text" id="message" required></textarea>
</div>
<div class="col-md-12">
<button class="send_btn" type="submit" id="submitform">Send</button>
</div>
</div>
</form>
Alright, you made a very small typo in your form ID attribute that you try to call from Javascript.
If $ is not undefined in your browser inspector, you should be able to select the form by $('#formset') instead of $('formset'). Let me know if that worked. I got it working on my machine with that adjustment :-)
Another good practice to learn Javascript is to write
console.log("Script entered this <FUNCTION_NAME>");
So I solved your problem in three seconds by doing this:
$(function() {
console.log("Script finished jQuery initialization.")
$("formset").submit(function (event) {
console.log("Script entered submit event.");
event.preventDefault();
var name = $("#fullname").val();
var email = $("#email").val();
var phonenumber = $("#phonenumber").val();
var message = $("#message").val();
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("Fullname", name);
sessionStorage.setItem("E-mail", email);
sessionStorage.setItem("Phoneno", phonenumber);
sessionStorage.setItem("Msg", message);
}
});
});
With the option 'Preserve Log' on in your inspector, you see the actual submit message in the console. Else you would be redirected after the form sumbit action and your console gets cleared.
And that's how I easily discovered the mistake. I never got the "Script entered submit event." message.

copy text from divs with same id to input onclick

So today i have decided to learn javascript and try something that seem simple. . But i'm stuck and can't work out why this don't work.
I'm trying to copy the text from divs with same ids onclick to an input but it always copy's the first divs text into the input and not the div i clicked.
Any ideas how i could fix this?
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Never use same id for elements instead use same class
. You can pass the whole element in the onclick function and get its text in the function
function copyToInput(elementId) {
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = elementId.innerText;
}
<div class="hud-chat-message message" onclick="copyToInput(this);"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message message" onclick="copyToInput(this);"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message message" onclick="copyToInput(this);"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Two div's can not share an id. You can share class', however, but id's are unique identifiers.
https://www.w3schools.com/tags/att_id.asp
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
Try This:
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message" onclick="copyToInput('message');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message2" onclick="copyToInput('message2');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message1" onclick="copyToInput('message1');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
Use the following code. All your elements must have unique ID's. In your code, the only reason it uses the first one is because the first one it the one it would use (since you can only have 1 ID, and the code assumes you only have 1 ID). Just give the 3 elements different IDs.
function copyToInput(elementId) {
var getText = document.getElementById(elementId).innerText;
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = getText;
}
<div class="hud-chat-message" id="message1" onclick="copyToInput('message1');"> SOME TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message2" onclick="copyToInput('message2');"> SOME MORE TEXT HERE </div>
<hr>
<div class="hud-chat-message" id="message3" onclick="copyToInput('message3');"> EVEN MORE TEXT HERE </div>
<hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">
ID must be unique, in your case id is not unique so when document.getElementById(elementId) see first id that matchs message , takes it and does not continue to search( so get first div always).
your code does not require a ID, use of this. this refer to div that click on it.
function copyToInput(elementId) {
var chatHudInput = document.getElementsByClassName('hud-chat-input')[0];
chatHudInput.value = elementId.innerText ;
}
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> SOME TEXT HERE </div><hr>
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> SOME MORE TEXT HERE </div><hr>
<div class="hud-chat-message" id="message" onclick="copyToInput(this);"> EVEN MORE TEXT HERE </div><hr>
<input type="text" name="message" class="hud-chat-input" placeholder="Enter your chat message..." maxlength="140">

HTML/JavaScript - Value of Input doesn't update (Element.value = Null)

Hello I just started today so im pretty new.
I have to get a string, which a user can enter on the website into my JavaScript file. I found out that I should use document.getElementById("myID").value to get the value of an input field on the html site. Here is my problem: I can't use the brackets arround my input and button because a submit will force a reload of the site and my functions wont have any affect.
So I have to get the string on the fly into my JavaScript file.
This is all I have at the moment:
<div id="searchDiv">
<input type="text" id="searchInput" placeholder="Search for Gifs..." value="" />
<input type="button" id="searchButton" value="Search"></button>
</div>
And my JavaScript file:
var searchButton = document.getElementById("searchButton");
var searchInput = document.getElementById("searchInput").value;
searchButton.addEventListener("click",
function() {
function(parameter)
}
)...
So document.getElementById("searchInput").value; give back null even if the input field has been edited.
I hope you can help me.
It is because your are storing the searchInput value even before the button is clicked,so the value would be empty irrespective of anything that you enter as input
Try accessing on the click event of the button
check this snippet
var searchButton =document.getElementById("searchButton");
var searchInput=document.getElementById("searchInput");
window.onload=function(){
searchButton.addEventListener("click",
function() {
alert(searchInput.value);
}
)
}
<div id="searchDiv">
<input type="text" id="searchInput" placeholder="Search for Gifs..." value="" />
<input type="button" id="searchButton" value="Search">
</div>
Hope it helps
You should use
<button></button>
Instead of
<input></button>
What I did was
<div id="searchDiv">
<input type="text" id="searchInput" placeholder="Search for Gifs...">
<button id="searchButton">Search</button>
</div>
<script type="text/javascript">
document.getElementById("searchButton").onclick = function(){
alert(document.getElementById("searchInput").value);
}
</script>

Categories