I have two inputs i want if one of them is equal to the other the button will be enabled else it's disabled.
I managed to do it in Ajax, but i need to do it in Javascript
$(':password').keyup(function() {
if($('#pass').val() == $('#pass1').val() && $('#pass').val()!=='') {
$('#go').removeAttr('disabled');
} else {
$('#go').attr('disabled', true);
}
});
This should work. It's your script "translated" to vanilla JavaScript.
document.querySelector(':password').addEventListener('keypress', function() {
if (document.querySelector('#pass').value == document.querySelector('#pass1').value && document.querySelector('#pass').value !== '') {
document.querySelector('#go').disabled = false;
} else {
document.querySelector('#go').disabled = true;
}
});
I created a JSFiddle for you, implementing that functionality in plain JS: https://jsfiddle.net/3m9g4p0h/4/
JS:
var pw1 = document.getElementById('pw1');
var pw2 = document.getElementById('pw2');
var button = document.getElementById('button');
function compare() {
button.disabled = pw1.value !== pw2.value || pw1 === '';
}
pw1.addEventListener('keyup', compare);
pw2.addEventListener('keyup', compare);
HTML:
<input type="password" id="pw1" />
<input type="password" id="pw2" />
<button id="button" disabled="true">
Click me
</button>
You are looking for form validation functionality.
There are a lot of plugins and libs for this kind of task.
but there is a simple example
function getElements(){
return {
password: document.querySelector('input[name="password"]'),
confirm: document.querySelector('input[name="passwordConfirm"]'),
button: document.querySelector('button'),
}
}
function validate(){
let els = getElements();
els.button.disabled = els.password.value !== els.confirm.value;
}
let elements = getElements();
elements.password.addEventListener('input', validate);
elements.confirm.addEventListener('input', validate);
validate();
<input name="password" type="password" placeholder="password...">
<input name="passwordConfirm" type="password" placeholder="password confirm...">
<button type="submit">submit</button>
and jQuery variant
function validate(event){
let $frm = $(event.target).closest('form');
let pas = $frm.find('input[name="password"]');
let conf = $frm.find('input[name="passwordConfirm"]');
let btn = $frm.find('button');
btn.prop('disabled', pas.val() !== conf.val());
}
let $frm = $('form');
$frm.on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form>
<input name="password" type="password" placeholder="password...">
<input name="passwordConfirm" type="password" placeholder="password confirm...">
<button type="submit">submit</button>
</form>
Related
I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
i've some trouble with this event listener. I'm tryng to add an event listener in the submit button, but it doesn't work. I don't know what I'm doing wrong!
This is my work:
const form = document.getElementById("form");
form.addEventListener('submit', (e) =>{
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
});
function valida() {
var nome = document.getElementById("nome");
const nomeVal = nome.value;
var cognome = document.getElementById("cognome");
const cVal = cognome.value;
let valida = true;
valida = nomeVal.length < 8 ? setError(nome, "devi inserire nome"): setSuccess(nome);
if (cVal.length < 8) {
valida = setError(cognome, "devi inserire cognome");
}
return valida;
}
function setError(input, m) {
input.className = "error"
const ciao = input.nextElementSibling;
ciao.innerText = m;
return false;
}
function setSuccess(input) {
input.className = 'success';
const error = input.nextElementSibling;
error.innerText = '';
return true;
}
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" type="submit">Submit</button>
</form>
I pasted your code into js fiddle.
There was a \u200b hidden character at the end of the 2nd line. Once I removed that it looks like it worked.
https://jsfiddle.net/mightypie/b1dmgtw2/9/
form.addEventListener('submit', (e) => {
Hi have you tried using onclick event handler?
Place the onlclick event in your submit button
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" onclick="test()" type="submit">Submit</button>
</form>
then on your js you can use the below code:
function test() {
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
};
I want this to just check if it is correct or not, I am not to smart about HTML so I really would like if someone could explain like im a little kid so I can understand.
Here is the code:
<input type="text" id="user" value="">
<input type="password" id="pass" value="">
<button type="button" id="btn" onclick="func()">Login</button>
<h1 id="txt"></h1>
<script>
var userstate = "false";
var passstate = "false";
function func() {
var utxt = document.getElementById("user").value;
var ptxt = document.getElementById("pass").value;
if (utxt == "david")
userstate = "true";
if (ptxt == "lol123")
passstate = "true";
if (userstate == "true" && passstate == "true")
var txt = "Login succesfully";
else
var txt = "Login not succesfull";
}
</script>
You should put your login message in the div with the id txt using:
document.getElementById('txt').innerHtml = "the text";
<!DOCTYPE html>
<html>
<body>
<input type="text" id="user" value="">
<input type="password" id="pass" value="">
<button type="button" id="btn" onclick="func()">Login</button>
<h1 id="txt"></h1>
<script>
var userstate="false";
var passstate="false";
function func()
{
var utxt = document.getElementById("user").value;
var ptxt = document.getElementById("pass").value;
if (utxt == "david")
userstate = "true";
if (ptxt == "lol123")
passstate = "true";
if (userstate == "true" && passstate == "true")
document.getElementById('txt').innerHTML = "Login succesfully";
else
document.getElementById('txt').innerHTML = "Login not succesfull";
}
</script>
</body>
</html>
Also
Boolean (true | false) do not require quotes:
You can simply use:
userstate = true;
Or
userstate = fale;
and check them as:
if(userstate == false){}
Several issues
remove the quotes from false and true or use a direct assignment and a ternary like I do below
put the initialisation of the states INSIDE the function, otherwise I can change the names after entering ok names.
output the txt variable
NEVER have password testing in client JS - but I guess you are just playing
<input type="text" id="user" value="">
<input type="password" id="pass" value="">
<button type="button" id="btn" onclick="func()">Login</button>
<h1 id="txt"></h1>
<script>
function func() {
var utxt = document.getElementById("user").value;
var ptxt = document.getElementById("pass").value;
var userstate = utxt == "david";
var passstate = ptxt == "lol123";
document.getElementById("txt").innerHTML=(userstate && passstate)?"Login successful": "Login not successful";
}
</script>
Using profiles AGAIN: Do NOT use client based password validations except to keep your kid sister from entering a page.
<input type="text" id="user" value="">
<input type="password" id="pass" value="">
<button type="button" id="btn" onclick="func()">Login</button>
<h1 id="txt"></h1>
<script>
var profiles={ "david":"lol123", "fred":"xdf456"};
function func() {
var utxt = document.getElementById("user").value;
var ptxt = document.getElementById("pass").value;
var success= profiles[utxt] && profiles[utxt]==ptxt; // the name exists and matches the password
document.getElementById("txt").innerHTML=(success)?"Login successful": "Login not successful";
}
</script>
I have a problem with my code, namely: If in input #search_code I introduce letter 'm' and in #insert_code input I introduce letter "M", function returns "is not ok". I tried to make uppercase inputs with CSS text-transform: uppercase; but it does not work. What can we do to make input fields case insensitive?
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
...
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Convert those values to be compared to lowercase so that case sensitivity is no longer an issue.
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value.toLowerCase() == insert_code.value.toLowerCase()) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value.toLowerCase() !== insert_code.value.toLowerCase()) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
$(document).ready(function() {
$('#search_code').bind("cut copy paste", function(e) {
e.preventDefault();
});
});
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value="" /><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value="" /><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
<div id="result"></div>
You should be checking the variables for quality by first converting them into either upper or lower case. You can use String's "toLowerCase()" before comparisions.(If you need case insensitive comparision)
search_code.value.toLowerCase() == insert_code.value.toLowerCase()
Modify your condition check to as below
if (search_code.value.toLowerCase() == insert_code.value.toLowerCase()) {
That should make it run with no issues
I want to create password toggle function when clicked on the eye icon using Javascript only. I have written code for it but it works only to show the password text and not the other way round. Can someone see the logic error in the code below.
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
function showHide() {
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function() {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShow = 0;
hide();
}
}, false);
}
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" onclick="showHide()" id="eye">
<img src="eye.png" alt="eye"/>
</button>
You are binding click event every time you click a button. You don't want multiple event handlers. Plus you are redefining var pwShown = 0 on every click so you can never revert input state (pwShown stays the same).
Remove onclick attribute and bind click event with addEventListener:
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function () {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShown = 0;
hide();
}
}, false);
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>
The easiest way is using a button with an onclick attribute that toggles the type of the input.
<input type="password" id="password" value="myPassword"/>
<button onclick="if (password.type == 'text') password.type = 'password';
else password.type = 'text';">toggle</button>
You don't need to maintain one extra "pwShown" variable to decide whether to show text or hide it. All you need to do is to examine "type" attribute of "pwd" element as below :
Working Example
JavaScript :
document.getElementById("eye").addEventListener("click", function(e){
var pwd = document.getElementById("pwd");
if(pwd.getAttribute("type")=="password"){
pwd.setAttribute("type","text");
} else {
pwd.setAttribute("type","password");
}
});
HTML :
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
<img src="eye.png" alt="eye"/>
</button>
Follow these steps:
Download the images given below. Make a folder. Add your html file and the images in the same folder. Replace the value of "b.src" in javascript as well as in your html code accordingly.
Images :
function show() {
var a = document.getElementById("pwd");
var b = document.getElementById("EYE");
if (a.type == "password") {
a.type = "text";
b.src = "https://i.stack.imgur.com/waw4z.png";
} else {
a.type = "password";
b.src = "https://i.stack.imgur.com/Oyk1g.png";
}
}
<input type="password" id="pwd">
<button onclick="show()"><img src="https://i.stack.imgur.com/Oyk1g.png" id="EYE"></button>
This is an improvement upon Tunaki's answer. We don't even care to check which state the form field is in already, because this will be entirely determined by the state of the mouse. This allows the password to be only momentarily viewed (only as long as the mouse button is held down over the button.)
<html>
<head>
<title>Visible Password Test</title>
</head>
<body>
Password : <input type="password" name="password" id="password" />
<button type="button" id="eye" title="Did you enter your password correctly?"
onmousedown="password.type='text';"
onmouseup="password.type='password';"
onmouseout="password.type='password';">Peek at Password</button>
</body>
</html>
Based on what you wrote, you are adding the event both in html and in javascript (inside showHide function). May be you can change your js code from what you have, to:
function showHide()
{
var input = document.getElementById("pwd");
if (input.getAttribute("type") === "password") {
show();
} else {
hide();
}
}
The variable "pwShown" is misspelled (as "pwShow") in the else section of your Javascript code. Therefore, pwShown never gets reset to 0.
JQuery solution from my code: (just change the IDs).
$(document).ready(function () {
$("#eye").click(function () {
if ($("#password").attr("type") === "password") {
$("#password").attr("type", "text");
} else {
$("#password").attr("type", "password");
}
});
});
function action() {
var my_pass = document.getElementById("pass");
if (my_pass.type === "password") {
my_pass.type = "text";
} else {
my_pass.type = "password";
}
}
<input type="checkbox" onclick="action()">Show <input type="password" id="pass" value="my-secret">
We can get by using onclick event, let's see example.It is very easy
HTML
<span>
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" onclick="showHide()" id="eye" />
</span>
Javascript
function showHide() {
if (pwd.type == 'text') {
pwd.type = 'password';
}
else {
pwd.type = 'text';
}
}
Simple inline solution:
<input type="password" id="myInput" name="myInput">
<button onclick="myInput.type = (myInput.type=='text') ? 'password' : 'text'; return false;"></button>
In your code everytime when you call showHide() function, pwShown variable is set to 0.
You need to declare pwShown variable as global one.
var pwShown = 0;
function showHide()
{
...
}
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
see also https://www.w3schools.com/howto/howto_js_toggle_password.asp
Dump the eye image and instead use a button showing "Show" or "Hide" according to its state.
Then you just click on the text of the button.
You can stylize the button to be borderless and initially with the same background as its surrounds. Highlight the button by setting .show:hover to either brighten the background of the button or else to brighten the color of the Show/Hide text.
By putting the input and button into the same span, you will have them both inline ( CSS - span{display: inline-block;} ) and vertically align off the same bottom.
Use an ordinary text input just below the span for space to display the validation error alerts. Make sure its tab index is -1 and its background color & border is the same as its surrounding.
.
.
.
<span class="pwSpan">
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" onblur="return checkPassword();"/>
<button type="button" class="show" id="show" value="Show" onclick="showHide()" tabIndex="-1" autocomplete="off" >
</button>
</span>
<input type="text" class="error" name="pwErr" value="" tabIndex="-1" />
.
.
.
function showHide()
{
const pwField = document.getElementById("pwd");
const showHideValue = document.getElementById("show").value;
if(showHideValue.trim() === "Show")
{
showHideValue = "Hide";
pwField.setAttribute('type', 'text');
}
else
{
showHideValue = "Show";
pwField.setAttribute('type', 'password');
}
}