Trying to get user input to print in a P element - javascript

I would like to be able to take user input of a first and last name and upon clicking a submit button update a P element with that first and last name. almost like "Hello firstname lastname!"
The code I've provided is what my click function currently looks like.
function newName(){
var Name = input.value;
if (Name==""){
document.getElementById("hello").innerHTML="Hello" + Name;
}
};

You need to use the trim() to remove blank spaces and then check the condition.
var firstName = document.querySelector('#firstName');
var lastName = document.querySelector('#lastName');
function updateName() {
if (firstName.value.trim() && lastName.value.trim()) {
document.getElementById("hello").textContent = `Hello ${firstName.value} ${lastName.value}`;
}
};
<input type="text" placeholder="Firstname" id="firstName" />
<input type="text" placeholder="Firstname" id="lastName" />
<button onclick="updateName()">Click</button>
<p id="hello">
</p>

function getName(){
let name = input.value;
if (name != ""){
document.getElementById("name").textContent = Hi ${name};
}
}

This would be the most concise way to do it. Since this is simple test function.
function newName(){
if(input.value !== undefined || ""){
document.getElementById("hello").innerHTML= 'Hello '+ input.value }
};

Your code should look like below. JS Fiddle here for quick reference: https://jsfiddle.net/sagarag05/5nteLzm6/3/
function newName(){
let fullName = input.value;
if (fullName != ""){
document.getElementById("fullName2").textContent = `Hello ${name}`;
}
}

Related

Revert innerHTML to default after javascript event

I have an event listener that takes input from the user and replaces the default text "Your Username" with the user input.
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {username.innerHTML = `${this.value}`}
</script>
If the user backspaces all input, I want the innerHTML of the div to revert to the default (i.e. "Your Username"). How can I do this?
Store the original HTML in initialization, then use it in the change listener if valye is an empty string:
var search = document.querySelector('.search');
var originalHTML = username.innerHTML;
search.addEventListener('input', changeText);
function changeText() {
username.innerHTML = this.value !== '' ? this.value : originalHTML;
}
You need to add a conditional on your eventListener, if input value is null, something like this can do the trick:
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {
if(input.value == "") {
username.innerHTML = "Your Username";
} else {
username.innerHTML = `${this.value}`
}
}
</script>
You can add your default text with || operator.
function changeText() {username.innerHTML = `${this.value || 'Your default value'}`}
This will set the text to the default value if this.value is null or undefined or empty.

How to store user input as a variable?

I am trying to design a simple companion interface for a board game I am creating. How do you request user input, and then update a variable with the new input and display the new result? ie. "What number did you roll?" -> "You are now on [this] space."
Sorry, I am very new to coding... Here is the closest I've got
<var space = 1>
<button onclick="mySpaceNumber()">Die Roll</button>
<p id="demo"></p>
<script>
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll != null) {
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
function mySpace(){
'space'= 'space'+ 'dieroll'
space
}
}
}
</script>
if (dieroll != null) { - This will always be NOT null if something isn't entered. Reason being is that it is UNDEFINED, rather than NULL. These are two different things. Null is an actual value. When a variable has been declared, but no value has been given to it then it becomes undefined.
With that said, I would make this line if (dieroll !== "undefined)"
Regarding 'space'= 'space'+ 'dieroll'
I would not put any apostraphe's in the variable's NAME, that is something you want to do when you declare a string.
Regarding this: You will want to put your code on one line.
From:
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
To:
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
The variable space is undefined, you have not initialized it or given it a value. To do that we need to add this in var space=0;
Lastly, I don't see your HTML so I'm not sure what element the variable space is supposed to reference. If it's some other box or something you can remove the var space=0; and get the value by selecting the element you need it from. Without knowing what that would be or what your html looks like I can't speculate further.
With all that said, here is where we are.
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
function mySpace(){
var space=0;
space = space + dieroll;
return space
}
}
}
Then onto the HTML
This is not valid.
Code Snippet
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("roll").value = dieroll;
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
}
function mySpace(){
result = getSpace();
return result;
}
function getSpace(){
gs1 = +document.getElementById('quantity').value + +document.getElementById('roll').value
return gs1;
}
document.getElementById('quantity').value = +document.getElementById('quantity').value + +document.getElementById('roll').value
}
function resetSpace(){
document.getElementById('quantity').value = '1';
}
<div>Roll:
<input type="number" id="roll" name="roll" style="width: 50px;" />
Current Space:
<input type="number" id="quantity" name="quantity" value="1" style="width: 50px;" />
</div>
<button onclick="mySpaceNumber()">Die Roll</button>
<button id="reset" onclick="resetSpace()">reset</button>
<div id="demo"></div>

How to clear HTML input tag after alert is generated

I am using the function below to generate an alert when the entered number is not an integer. But I also need to clear the HTML form. I used id.value= ""; but that didn't work. Any suggestions are welcome:
function myFunction(id) {
var x = parseInt(document.getElementById(id).value);
if (!(x === parseInt(x, 10))) {
alert("Empployee ID can be integer numbers only.");
id.value = "";
} else {
}
}
<div class="header1">
<input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" />
</div>
Your id.value is not a HTML element. You are trying to get an access to value property of id variable... Something like this "ename".value
Try this:
document.getElementById(id).value = 'VALUE';
function myFunction(id) {
var x = parseInt(document.getElementById(id).value);
if (!(x === parseInt(x, 10))) {
alert("Empployee ID can be integer numbers only.");
document.getElementById(id).value = "";
}
else {
}
}
<div class="header1">
<input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" />
</div>
You are setting empty string in the value property of id. id is a string. Hence, it won't work you need to put an empty string somewhere in the document where the id attribute is equal to the function argument.
you need to use :
document.getElementById(id).value = "";
You cannot use id.value
because the id passed in you function was a string.
Since you already passed the id then maybe you can use:
document.getElementById(id).value = "";
Answer Explained

getElementById() not returning correct string

I am trying to grab the text from the textarea and it returns something but it returns nothing, no string.. When I enter a string into the textarea and click the button, it still returns nothing.
var name;
name = document.getElementById('username').value;
function action() {
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}
HTML:
<textarea rows="4" cols="50" id="username" placeholder="Enter your username here!"></textarea> <br />
<button id="submit" onClick="action()">Submit</button>
<br />
<img id="theIMG"></img>
You should call getElementById inside the action method - that value won't persist as the textbox changes:
function action() {
var name = document.getElementById('username').value;
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}
At the time of execution of your code, value is "" only. And it will not change irrespective you change the value in html as you are not updating it in your script. Hence, you need to update your code to following
function action() {
var name = document.getElementById('username').value;
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}
You need to define name in the function itself, like this:
var name;
function action() {
name = document.getElementById('username').value;
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

Categories

Resources