I was messing around with a previously existing snippet and ran into an issue.
Whenever I try to enter an input that doesn't apply the to If statement it always gives me the If output. Also I was looking to, instead of saying approved, have you sent to a URL, like Google for example, and I'm not sure about a solution for either of the two.
function myFunction() {
var a = document.getElementById("text_a").value;
if (a == "02035", "02048", "02067") {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML = "Our service currently isn't available in your area! Try again soon!";
}
}
<p>Enter Zip Code </p>
<input id="text_a" type="text" />
<p id="answer"></p>
<button onclick="myFunction()">Check</button>
May be you need to change the condition in if statement:
if (a == "02035" || a == "02048" || a == "02067"){
document.getElementById("answer").innerHTML="Approved";
}
else{
document.getElementById("answer").innerHTML="Our service currently isn't available in your area! Try again soon!";
}
if (a=="02035","02048","02067")
You can't do like this.
There are many ways to check it. You could do like this
function myFunction() {
var a = document.getElementById("text_a").value;
var list = ["02035", "02048", "02067"];
console.log(a)
if ((list.indexOf(a) > -1)) {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML =
"Our service currently isn't available in your area! Try again soon!";
}
}
I made a sample: https://codepen.io/anon/pen/bWBvMj?editors=1011
Related
So I am making a game and I need to check if these two HTML <input> fields have some data before I do an alert(); saying that they won. Unfortunately, I don't know how to implement this and I have been stuck at it for hours, please do help, attaching a screenshot for assistance.
In the image, I want to constantly monitor the 2 empty <input> fields and once there is data IN BOTH, then I want to throw up an alert();
Here's what I tried:
var firstLetterField = document.querySelectorAll("input")[0].value.length;
var secondLetterField = document.querySelectorAll("input")[1].value.length;
if (!firstLetterField && !secondLetterField) {
console.log("Please ignore this message: NOT_FILLED...");
} else {
alert("That's right! The word was " + spellingOfWord.join("").toUpperCase() + "! Thanks for playing!");
window.location.href = "/";
}
How about just adding a common class to your user input and use querySelectorAll to perform your check ?
eg
<html>
<body id="game">
<input data-expected="m" class="user-input" />
<input data-expected="a" class="user-input" />
<div id="keyboard">
<button>d</button>
<button>c</button>
<button>b</button>
<button>a</button>
<button>d</button>
<button>m</button>
<button>e</button>
</div>
</body>
<script>
const inputs = document.querySelectorAll(".user-input");
const keyboard = document
.querySelector("#keyboard")
.querySelectorAll("button");
let inputPosition = 0;
function nextInput() {
inputPosition += 1;
if (inputPosition === inputs.length) {
alert("you won");
}
}
function handleClick(event) {
const input = inputs.item(inputPosition);
const submittedValue = event.target.innerHTML;
if (input.dataset.expected === submittedValue) {
input.value = submittedValue;
setTimeout(nextInput);
}
}
keyboard.forEach((button) => button.addEventListener("click", handleClick));
</script>
</html>
You could register an event-listener and check if your condition is met:
var firstLetterField = document.querySelectorAll("input")[0];
var secondLetterField = document.querySelectorAll("input")[1];
// Function to call when both inputs contain values
function bothReady() {
console.log("bothReady", firstLetterField.value, secondLetterField.value);
}
document.addEventListener("keyup", function (e) {
// Wait for both fields to have values
if (firstLetterField.value.length > 0 && secondLetterField.value.length > 0) {
bothReady();
}
});
Your code just works fine. There were just some mistakes that I noticed.
You tried to use the length to detect if it is empty. You could instead compare it with an empty string.
You reversed the boolean value using else. It looks that does the opposite of what you want.
In the code you showed you didn't actually defined spellingOfWord. So I did it for you.
The location "/" is not compatible in every server. So I would recomment replacing it by "index.html".
Here is the code that I just created
function input_inputEvent() {
var firstLetterField = document.querySelectorAll("input")[0].value;
var secondLetterField = document.querySelectorAll("input")[1].value;
var thirdLetterField = document.querySelectorAll("input")[2].value;
if (firstLetterField.length != "" && secondLetterField != "") {
alert(
"That's right! The word was " +
[firstLetterField,secondLetterField,thirdLetterField].join("").toUpperCase() +
"! Thanks for playing!"
);
window.location.href = "index.html";
}
}
I am working on some basic JavaScript.
I have a muse website and I'm using this script so users can enter a specific password and be redirected to a page, I need to be able to change this so I can do this multiple times, so: multiple passwords going multiple places.
For example, when users click a button they are asked for a password, when they enter CUSTOMPASSWORD1 they will be redirected to mywebsite.com/custompassword1.html how would I edit this script so that they could also type in CUSTOMPASSWORD2 and be redirected to mywebsite.com/custompassword2.html?
Script below:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter Store Code Here',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "CUSTOMPASSWORD1234") {
alert('You are being redirected!');
window.open('CUSTOMPASSWORD1234.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Store Code Not Recognised, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Store Code" onClick="passWord()">
</FORM>
</CENTER>
I believe what you are trying to do is simply redirect the user to whichever url they enter in the prompt.
To achieve that, we can use a similar approach:
function redirect() {
var pass1 = prompt('Enter Store Code Here', ' ');
if (!pass1) {
history.go(-1);
} else {
alert('You are being redirected!');
window.open(pass1 + '.html');
}
}
<center>
<form>
<input type="button" value="Enter Store Code" onClick="redirect()">
</form>
</center>
I'm not sure I entirely understand the question, I think you could just do this:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter Store Code Here',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toUpperCase() == "CUSTOMPASSWORD1234") {
alert('You are being redirected!');
window.open('CUSTOMPASSWORD1234.html');
break;
}
else if (pass1.toUpperCase() == "CUSTOMPASSWORD2"){
window.open('CUSTOMPASSWORD2.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Store Code Not Recognised, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Store Code" onClick="passWord()">
</FORM>
</CENTER>
You also have what I assume is an error with
(pass1.toLowerCase() == "CUSTOMPASSWORD1234")
since this will never evaluate to true since CUSTOMPASSWORD1234 is upper case. Also you don't have an evaluation for CUSTOMPASSWORD1.
It seems like you're lacking in basic JS and programming knowledge so I'd recommend reading some basic tutorial in programming concepts before you start building stuff. Just hacking together tutorials will make spaghetti code and you won't learn.
Trent's answer is better design which you should use, this answer is just how to specifically implement what you are asking for.
I've created a basic form validation script that I want to return an error messages as a light box, rather than using an alert() message. I like the look of featherlight.js, but I can't figure out how to return it from a function? Any other suggestions would be greatly appropriated. Thanks in advance.
The featherlight.js repo
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
alert('Please enter your first name');
return false;
}
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>
I know this is a bit late, but I think I know what you're after. I've just done a similar thing myself, so I'll put it here incase it helps anyone.
I created a function so you can re-use it elsewhere along with an OK button to close the light box.
function customAlert(message = '') {
var alertBox = $(document.createElement('div'));
alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
$.featherlight(alertBox);
}
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
customAlert('Please enter your first name');
return false;
}
}
Basically, you cannot "return" it. What you can do is you can trigger a lightbox event when your conditions are match, like this:
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
$.featherlight($content, $configuration); // Lightbox for wrong validation
return false;
} else {
$.featherlight($content, $configuration); // Lightbox for successful validation
return true;
}
}
And of course, you will need to modify $content and $configuration variables as you want as explained here:
https://github.com/noelboss/featherlight/
Hi I am looking for guidance on how I can change the interest rate value based on what type of account a customer chooses from the drop down.
Form:
<form id="account" action="" method="post">
<select id = "acc_type">
<option value="current">Current</option>
<option value="savings">Savings</option>
</select>
<input type="text" id="interest" value="">
</form>
<script>
$("#account").change(function() {
var rate = "0.6%";
if $(#acc_type).val == ("current") {
rate = "0.6%");
} else if $(#acc_type).val == ("savings") {
rate = "0.8%");
}
$(#interest).val = rate;
</script>
http://jsfiddle.net/rmjKV/
Can I have some explanation of why this does not work?
It does not work since that is not valid JavaScript. Use a tool like JSLInt to check your code to see the errors.
You are missing many ( and ) in that code.
Look at the if statements on MDN
if (cipher_char == from_char) {
result = result + to_char;
x++;
} else {
result = result + clear_char;
}
Do you see what you are missing? The ( and ) around the check.
Now jQuery val is a method, you are not calling a method. You need (). You can not set .val either.
The docs for jQuery val()
Your selector is also wrong, you are missing quotes.
Learn to use your console! It will show you the errors.
You have a lot of syntax errors and improper way of using jQuery functions and selectors
$("#account").change(function() {
var rate = "0.6%";
if($('#acc_type').val() == "current")
{
rate = "0.6%";
}
else if ($('#acc_type').val() == "savings")
{
rate = "0.8%";
}
$('#interest').val(rate);
});
You need to read more about JS syntax and jQuery selectors and functions use
Check the fiddle update
http://jsfiddle.net/sedz/rmjKV/2/
Stuff like this
$(#acc_type)
should be
$('#acc_type')
You've got numerous errors in your code. I think I've fixed most of them below.
I've also wrapped you code in jquery's ready function, so the the script doesn't try and add the event before the page is fully loaded etc.
$(document).ready(function() {
$('#account').change(function() {
var rate = "0.6%";
if ($('#acc_type').val() == "current") {
rate = "0.6%";
} else if ($('#acc_type').val() == "savings") {
rate = "0.8%";
}
$('#interest').val(rate);
})
})
JSHint doesn't validate your code. Aside that, it looks like you are binding to the form change not the acc_type change.
$("#acc_type").change(function() {
}
Valid JS Code:
$("#acc_type").change(function()
{
var rate = "0.6%";
if ($("#acc_type").val() == "current")
{
rate = "0.6%";
} else if ($("#acc_type").val() == "savings")
{
rate = "0.8%";
}
$("#interest").val(rate);
});
http://jsfiddle.net/rmjKV/5/
$("#acc_type").change(function() {
var rate = "0.6%";
if ($('#acc_type').val() == "current") {rate = "0.6%";}
else if ($('#acc_type').val() == "savings") {rate = "0.8%";}
$('#interest').val(rate);
});
Find here http://jsfiddle.net/rmjKV/8/ your jsFiddle working, your old code was full of typos
I am trying to create a text-based adventure game. I managed to figure out how to make text output in html's textarea through simple onclick button, but now I am trying to do something new. I am having trouble with doing same thing but with input text where users can write anything in the box and then click on the button. Right now, I am trying to make this program to check the user input against some flag (in this case, I set my flag equal to 'pizza') before it does something. Unfortunately, my code doesn't work at all. I think I don't completely understand how the input is being passed around in JavaScript's functions.
The JavaScript part:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
if (fileName == "pizza") {
var obj=document.getElementById(test);
obj.value="is this showing up in the textarea???";
}
else {obj.value="wrong password!"; }
}
The html part:
<input name="filename" id="filename" type="text">
<a id="record_button" onclick="record('textarea1');" href="javascript:void(0);" title="Record">Perform Action</a>
<textarea wrap="virtual" cols="73" rows="10" id="textarea1"></textarea>
The problem is this block with your else statement, obj isn't declared. Because you have obj defined in the if statement above it is exclusive to that scope. Just define obj right above the if block.
--
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj=document.getElementById(test);
if (fileName == "pizza") {
obj.value="is this showing up in the textarea???";
}
else {
obj.value="wrong password!";
}
}
Add an event listener using JS:
document.getElementById('record_button').onclick=function(){
record('textarea1');
}
Also, there were a couple things wrong with your function. Here it is with corrections:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj = document.getElementById(test);
if (fileName == "pizza") {
obj.value = "is this showing up in the textarea???";
}
else {
obj.value = "wrong password!";
}
}
You were using document.getElementByID on the second line, which is incorrect capitalisation
You were only defining obj conditionally, so the else clause always threw an exception.
Here is a demonstration: http://jsfiddle.net/uQpp7/1/