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
Related
I'm writing a piece of HTML and JavaScript code and I need to check if inputs have been filled before clicking the button. However, when I leave them blank, it proceeds to the php page passing the variables empty.
I have made some tests and I've concluded it does not load the onClick function at all.
This is the code (without all the CSS stuff):
<div class = "register">
<form action = "register.php" method = "post" name = "reg1" id = "register" onClick = "return validateForm();">
<input type = "text" class = "reg" id = "name" name = "name"/>
<div class = "alert" id = "inserthere1"> </div>
<input type = "text" class = "reg" id = "surname" name = "surname"/> <div class = "alert" id = "inserthere2"></div>
<input type = "text" class = "reg" id = "mail" name = "mail" /><div class = "alert" id = "inserthere3"></div>
<input type = "submit" value = "Join!" >
</form>
</div>
<script language = "JavaScript">
function validateForm() {
var n = document.getElementById("name").value;
var c = document.getElementById("surname").value;
var m = document.getElementById("mail").value;
alert("Nome:"+n+"Cognome:"+c+"Mail:"+m);
document.getElementById("inserthere1").innerHTML = (n===null || n==="" ? '<i> This cannot be left empty. </i>' : '');
document.getElementById("inserthere2").innerHTML = (c===null || c==="" ? '<i> This cannot be left empty. </i>' : '');
document.getElementById("inserthere3").innerHTML = (m===null || m==="" ? '<i> This cannot be left empty. </i>' : '');
if ( n===null || c===null || n==="" || c==="" || m===null || m==="" )
return false;
}
return true;
}
So you want to make sure the fields are filled in before proceeding? You can use:
<input required="">
This way the user has to fill out the fields with required="", or their browser won't let them submit the form.
You have to use the preventDefault on the submit event or use a button instead a input, after that you have to use the onclick event on the button, not into the form that will validate if the inputs has been filled or not.
After you validate the form you can use this for submit your form
document.getElementById("myForm").submit();
That will send the form data to the action script.
Ref: preventDefault Documentation | W3CSchools
Ref2: Form Submit method | W3CSchools
try using
<form>..</form>
document.addEventListener('click', validateForm, false);
<script language = "JavaScript">
function validateForm() {
..
</script>
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>
I've looked up a few other questions on the site, but am still at a loss. I wanted to use Javascript (no JQuery) to take the form below:
<!doctype html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Account Sign-Up</title>
</head>
<body>
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<div id = "div1" style = "display:none">Enter your first name</div>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<div id = "div2" style = "display:none">Enter your last name</div>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<div id = "div3" style = "display:none">Enter E-Mail</div>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<div id = "div4" style = "display:none">Enter your desired screen name</div>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<div id = "div5" style = "display:none">Enter the password you will use to log into your account in the future</div>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<div id = "div6" style = "display:none">Type your password again</div>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<script src = "Q10.js"></script>
</body>
</html>
and apply the following script to display some hidden text whenever the text boxes gain focus. I don't wish to go beyond the scope of what is described. So no, I can't use pop-up tooltips or text in a single div element in a footer, etc. I'm also unconcerned with data injections or the vulnerability/security of the code, as I am not using it for anything practical.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
//
I'm currently running into a hiccup because I can't get the events to run scripts on focus, and don't know where else to turn. Please help ><
I'm not sure whether this is the way you want it, check the snippet. If not i will close down this answer. what i did is to add/change some code in showText(). and i think it would be better to show those divs you used on hiding texts to span(or <p>)tag as well. i added css for hiding texts class named description. you can remove other codes that you made which is not useful.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function(numb) {
var desc = document.getElementsByClassName("description");
for (var i = 0; i < desc.length; i++) {
desc[i].style.display ="none";
}
document.getElementById("div" + numb).style.display = "inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
.description:before {
content: '*';
}
.description {
display: none;
color: red;
}
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<span id="div1" class="description">Enter your first name</span>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<span id="div2" class="description">Enter your last name</span>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<span id="div3" class="description">Enter E-Mail</span>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<span id="div4" class="description">Enter your desired screen name</span>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<span id="div5" class="description">Enter the password you will use to log into your account in the future</span>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<span id="div6" class="description">Type your password again</span>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<!-- <script src = "Q10.js"></script> -->
It should work fine but there could be possible Problems:
1.If you are running this on JSFiddle then you can try. window.showText. Working fiddle: https://jsfiddle.net/24sck8rs/5/
window.showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
2.Possible cause of hoisting. I have declared function variable at the top and removed var. Working fiddle: https://jsfiddle.net/24sck8rs/6/
3.Declare your script in head before function call
My code has two sections: a section to input new items, and a section to interact with them. I'm trying to update the dropdown list every time a new item is added with jQuery, but my current method does nothing. By nothing, I mean that the dropdown list would remain empty. I've tried previous answers to this question, but none worked. (I'm pretty new to Javascript, so me just being a noob is completely possible).
Here's the html:
<!DOCTYPE html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "deletion.css"></link>
<script src = 'chemical.js'></script>
</head>
<body>
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button id = "newChemicalButton" onclick = "addChemical()" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
</body>
And the Javascript:
chemicals = [];
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append('<option value = "' + chemical.name + '"> ' + chemical.name + '</option> \n');
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
There are a couple of things going on. First of all, When you press the submit button it tries to submit the first form. Second: It seems like the onclick event is not binding to the method which should add the item to the dropdownlist.
I've updated a couple of things:
Added $(document).ready(...); as it is best practice.
I've removed the inline onclick and bind the click event via jQuery.
JSFiddle here...
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button type="button" id = "newChemicalButton" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
and the JS:
$(document).ready(function(){
var chemicals = [];
$("#newChemicalButton").on("click",function(){
addChemical();
});
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append("<option value=" + chemical.name + ">" + chemical.name + "</option>");
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
});
Possible the "\n" behind the append code make this not working. Try to remove it.
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.