How do I compare user input to a variable? - javascript

I don't know how to make this work. Does anyone know how to fix this? I have tried multiple different solutions, but they don't work
function submit() {
var user = "test";
if (document.getElementById('#user').input = user) {
//what I need help on
}
}
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
<button class="open-button" onclick="openForm()">Open Form</button>
<div class="form-popup" id="myForm">
<form action="#" class="form-container">
<h1>Login</h1>
<label for="username"><b>username</b></label>
<input type="text" placeholder="username" id="username" name="username" required>
<button type="submit" onclick="submit()" class="btn">Login</button>
// And here
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>

First, where is user input element, that you mentioned in JavaScript, there is no input with id user, only one input with id username exist, use that and hashtag is not used for ids in document.getElementById
replace
document.getElementById('#user')
to
document.getElementById('username') // use username and remove the hashtag (#)
Secondly, use value instead of input
document.getElementById('username').value
Returns the value (text) of the input element
Lastly, use == or === operators in statements not = in JavaScript.
Example
if (document.getElementById('username').value === user) { // Replaced = with ===
//what I need help on
}
Full JavaScript Code
function submit() {
var user = "test";
if (document.getElementById('username').value === user) {
//what I need help on
}
}
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}

Use this instead
if(document.getElementById('#user').value == user)
I'd suggest you to store the input element in a variable first to dry your code ;)

I see you got the wrong username id, try my code below:
function submit() {
var user = "test";
if (document.getElementById('#username').value == user) {
//what I need help on
}
}

Related

Enable Disabled Button if Input is not empty

I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn.
I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same.
Thanks!
Id propose something like this
Use a block, which encapsulates the names of variables and functions inside the block scope
Make small functions, which do just one thing
Prefer addEventListener over onclick or onanything
There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
I added a check for validity to the email field with checkValidity method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:
/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);

Unable to Returning function to main HTML body javascript

I call the function from a click of the submit button here, and retrieving the entered text works fine.
<button class="btn btnEmail" id="emailBtn" onclick="emailUser.getEmailInput();">Submit</button>
<input type="button" value="submit" onclick="writeMail(this.emailInput)" />
It seems the function is not able to return the value of emailInput to html main body as I cannot use it with my writemail function.
the getEmail function:
let emailUser = {
getEmailInput: function() {
this.emailInput = document.getElementById('emailInput').value;
document.getElementById("emailOutput").innerHTML = this.emailInput;
return(this.emailInput);
}
};
the writeMail function:
function writeMail(email) {
console.log(email);
localStorage.setItem('email',email);
let theEmail = localStorage.getItem('email');
console.log(theEmail);
}
this in onclick="writeMail(this.emailInput)" will refer to the element itself. i:e input with type button.
Instead pass the value of other input using document.getElementById('emailInput').value).
function writeMail(email) {
console.log(email);
localStorage.setItem('email', email);
let theEmail = localStorage.getItem('email');
console.log(theEmail);
}
<input type="email" id="emailInput">
<input type="button" value="submit" onclick="writeMail(document.getElementById('emailInput').value)">

Javascript - enabling button when input is filled

I want to enable my button, when input is filled. I want to do it in pure Javascript.
My code example in HTML:
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name" onkeyup="myFunction()"><br>
<button type="submit" class="button button-dark" id="send">Send message</button>
</form>
And Javascript:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
function myFunction() {
var nameInput = document.getElementById('name').value;
if (!nameInput === "") {
document.getElementById('send').disabled = "false";
}
}
});
I don't know why my button is not changing to enable state after filling something in input. I have tried diffrent ways to do it, but it's still not working.
Please help.
An input element in HTML is enabled only when the disabled attribute is not present.
In your case disabled is always present in your element, it's just that it has a "false" or a "true" value - but this is meaningless according to the specs (http://www.w3schools.com/tags/att_input_disabled.asp)
So you need to remove it altogether:
document.getElementById('send').removeAttribute('disabled')
The problem with your code is that myFunction() isn't available because you defined it in the eventlistener for click.
Complete refactored code answer:
HTML
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name">
<br>
<button type="submit" class="button button-dark" id="send" disabled>Send message</button>
</form>
JS
document.getElementById("name").addEventListener("keyup", function() {
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
document.getElementById('send').removeAttribute("disabled");
} else {
document.getElementById('send').setAttribute("disabled", null);
}
});
Try this one it will work for you
function myFunction() {
document.getElementById('send').disabled = true;
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
alert("Empty");
document.getElementById('send').disabled = false;
}
}
if you want to check the input should not be contain number then we can use isNaN() function, it will return true if number is not number otherwise return false
Your code is almost correct but you have defined myFunction inside a block, so input is not able to find myFunction() inside onkeyup="myFunction()"
so just keep the same outside of DOMContentLoaded event
see working demo
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
});
function myFunction() {
var nameInput = document.getElementById('name').value;
console.log(nameInput);
if (nameInput === "") {
document.getElementById('send').disabled = true;
} else {
document.getElementById('send').disabled = false;
}
}

Show/hide password onClick of button using Javascript only

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');
}
}

Validation stuck at first validation

I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />

Categories