I'm adding interactivity to a form.
Here is a snippet of the HTML:
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
There is a button at the bottom of the form, 'Register'. If the button is pressed and the Name field is empty, I want to add an alert message, reminding the user to enter their name. I want to do this by amending the label.
I am having trouble trying to select the inputted text of the text-field. Seeing as it's not value or innerHTML? How do I select it?
This is the code I have so far:
// Form validation. Display error messages and don't let the user submit the form if any of these validation errors exist:
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
Use .value to get the value of input field and put css value red in inverted comma as nameLabel.style.color = "red"; Also since you have a
<button type ="submit">submit</button>
you need to stop you page from refreshing. Use e.preventDefault(); for this in your event handler
The flash of error that you get while in console is that red is not defined which it isn't since its a string and you need to give it in "".
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
console.log("\"" + nameInput.value + "\"");
if(nameInput.value.length == 0) {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>
Related
I have an email input and I'm trying to read the input value but It doen't return a value when It is filled.
<input id="email" name="email" required="" type="email" value=" " class="form-control" />
This is the function I'm trying to execute, saving the Value on a variable to use it later.
var email = document.getElementById("email").value;
I have already tried
var email = document.getElementById("email"); console.log(email.value);
But have no luck
In this snippet, you can see how you can get the value of the input field as it changes. My suspicion is that you are trying to get the input's value before the user has filled it in (it's a common mistake)
//var ch = 0;
var in1 = document.querySelector("input");
var in2 = document.querySelector("input:last-of-type");
in1.addEventListener("change", function(e) {
// ch++;
console.log("changed: " + in1.value);
});
in2.addEventListener("keyup", function(e) {
console.log("changed: " + in2.value);
});
<input type="email" />
<input type="email" />
I'm new to js and today i was writing a simple script to check placeholder of the input text, if input text is clicked it removes placeholder, and if user leaves input empty, it turns placeholder back. problem is can't find an eventlistener when user leaves the input. how can i check when user leaves input?
let element = document.getElementById("username");
const x = () => {
element.setAttribute("placeholder"," ");
}
element.addEventListener("click",x);
const y = () => {
if(element.value === ""){
element.setAttribute("placeholder", "USERNAME");
}
}
<input type="text" placeholder="USERNAME" name="username" id="username">
You can create an eventListener with focusout event, and then set the value of your placeholder as you wish.
let element = document.getElementById("username");
const x = () => {
element.setAttribute("placeholder"," ");
}
element.addEventListener("click",x);
const y = () => {
if(element.value === ""){
element.setAttribute("placeholder", "USERNAME");
}
}
element.addEventListener("mouseout", function(){
element.placeholder = "new placeholder";
})
<input type="text" placeholder="USERNAME" name="username" id="username">
you can check when user focuses out of the input by putting eventlistener focusout :
element.addEventListener("focusout", y);
just add this at bottom of your codes and it'll work fine.
Basic form validation
In this question, you’re going to make sure a text box isn’t empty. Complete the following steps:
Create a text input box.
Write a function that turns the text box’s border red if the box is empty.
(It’s empty if the value equals "").
The border should go back to normal if the value is not empty.
When the user releases a key (onkeyup), run the function you just created.
please correct my code where I'm coding wrong?
let form = document.getElementById("form_Text").value;
document.getElementById("form_Text").onfocus = function() {
if (form == "") {
document.getElementById("form_Text").style.backgroundColor = "red";
document.getElementById("showText").innerHTML = "Form is empty";
} else {}
document.getElementById("form_Text").onkeyup = function() {
document.getElementById("form_Text").style.backgroundColor = "white";
document.getElementById("showText").innerHTML =
"Form is not Empty, No red Background";
};
};
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
You are trying to get the input value with let form = document.getElementById("form_Text").value; right after the js is loaded. Therefore it will always be empty. You need to call it inside the event listener.
document.getElementById("form_Text").onfocus = function() {
let form = document.getElementById("form_Text").value;
...
}
But instead of writing two separate event listeners, you can use input event instead of focus and keyup
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.addEventListener('input', function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
})
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
UPDATE
You can find the other way of binding below. Instead of using two separate events (keyup and focus), you can use oninput event listener.
Here's a SO thread comparing keyup and input events: https://stackoverflow.com/a/38502715/1331040
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.oninput = function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
}
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
I'm trying to set a password input as required in JavaScript.
I have learnt from this post how to do it but it doesn't seem to work with my password input.
<div class = "login">
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</div>
var p = document.querySelector(".enterPassword");
p.required = true;
p.style.backgroundColor = "gray";
var s = document.querySelector(".submit");
s.addEventListener("click", clickHandler.bind(p));
function clickHandler() {
console.log("Password: " + this.value);
}
jsfiddle
Although I do,
var p = document.querySelector(".enterPassword");
p.required = true;
as you can see, there is no required popup when a user fails to enter a password. Does anyone know why not?
Wrap the elements in a form
<form>
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</form>
You can also check it without using form
document.querySelector(".enterPassword").validity.valid
this will return a Boolean value , but you wont see the error pop up
JSFIDDLE
function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.