I've written a program that should display an image of a beverage or an alert window depending on the user's age input. The problem is that regardless of what value is submitted it only executes the 'if' portion of the statement. None of the other conditions are being checked prior to execution. I have tried using getElementById with the element id in place of querySelector but the program did not run at at all. I have tried querySelector with the button tag as well as trying the input tag. That also did not work.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.querySelector('age');
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'images/cola.jpg';
} else if (patronAge >= 21) {
primaryImg.src = 'images/tallboy.jpg';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (patronAge == NaN) {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src="images/bar&grill.png" alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
Instead of writing this:
let patronAge = document.querySelector('age');
you should write the following:
let patronAge = parseInt(document.querySelector('#age').value);
There are a few problems with your approach.
querySelector('age') looks for an element with tag age, this does not exist. Since you're using querySelector you need to specify a # symbol to search for an id.
You need to access the value of the HTMLElement
You need to parse the value as a number
couple of minor problems. They are pretty easy to spot. Look over the snippet and let me know if you don't understand anything.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.getElementById('age').value;
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'https://via.placeholder.com/120';
} else if (patronAge >= 21) {
primaryImg.src = 'https://via.placeholder.com/150';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (typeof(patronAge) == 'string') {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src='https://via.placeholder.com/100' alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
Related
I use the following code to validate a password in a form. If the password is correct - Move the user to site X. If it's incorrect (after 3 tries), move the user to site Y.
For some reason, it works only for site Y.
My code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I tried doing:
Checking for syntax errors all over the code.
Changing === to == (I thought, maybe due to it being a string, the quote marks counted as well, of course I was mistaken).
window.location.href = 'http://maariv.co.il', true;
Adding return false right under window.location.href
As a beginner I ask, why would the condition works only in a half? That is, the positive part (than) doesn't work but the negative part (else) does work.
Update:
This is just an exercise. Indeed. This isn't going to production. In production I should store and request the password from a database.
Put the following line let passwordValue = document.querySelector('#user').value; inside onclick of "mybutton".
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
Use return :
if (password === passwordValue) {
return window.location.href = 'http://maariv.co.il';
}
Otherwise, the function will execute to the end, and you will reach the second redirection, that will then override the first one.
I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}
I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>
I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>
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" />