I am trying to code this web app to have the user input important information about their device, then place it in the relevant spots in javascript. Here is my code so far.
<script type="text/javascript">
function update() {
var key = document.getElementById("key").value;
if (input.length < 40) {
alert("Please enter a valid input");
return;
}
document.getElementById("access key").innerHTML;
}
</script>
<script type="text/javascript">
function update() {
var device_id = document.getElementById("device_id").value;
if (input.length < 24) {
alert("please enter a valit input");
return;
}
document.getElementById("device_id").innerHTML;
}
</script>
<p><input type="text" id="key" autofocus placeholder = "Enter product key here" /></p>
<p><input type="text" id="device_id" autofocus placeholder = "Enter device ID here" /></p>
<p><input type="submit" value="Submit" onclick="update()"/></p>
<h1>Rotary Gate Systems</h1>
<article>
Open
</article>
<article>
Close
</article>
<article>
<p class="status_closed status_button">CLOSED</p>
<p class="status_open status_button">OPEN</p>
<p class="status_none status_button">NO CONNECTION</p>
</article>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js'></script>
<script>/*jslint browser: true*/
/*global $, jQuery*/
/*jshint strict: true */
/*EDIT THESE VARIABLES*/
//key is the same as your 'access token'
var key = "key"
//device_id is the same as the 'core id'
var device_id = "device_id"
I think I may be missing something in the submit button, or what I'm trying to do may not be possible with this attribute. Can someone take a look at this and let me know where I may be messing up?
You need to change your conditional statements to,
if (key.length < 40) {
and
if (device_id.length < 40) {
since input is not defined inside your update() functions.
And additionally, you should consider combining the two update() functions into one so as to conduct the validity checks on key and device_id together whenever the form is submitted.
Based on your comments, it sounds like you're trying to update the key and device_id variables with the values from the two <input> elements.
You should learn about variable scope in JavaScript to be sure you can access those variables.
If the key and device_id variables are in scope when your function runs, you can just assign them values directly. Don't precede the assignments with the var keyword, or you'll be defining new locally-scoped variables instead of updating the existing variables from the outer scope.
You also cannot have two functions with the same name (in this case, update) defined within the same scope; only the most recently defined function will work.
var key = "key";
var device_id = "device_id";
function update() {
var tempkey = document.getElementById("key").value;
if (tempkey.length < 40) {
alert("Please enter a valid key.");
return;
}else{
key = tempkey;
}
tempdevice_id = document.getElementById("device_id ").value;
if (tempdevice_id.length < 24) {
alert("please enter a valid device ID.");
return;
}else{
device_id = tempdevice_id;
}
}
<p>
<input type="text" id="key" autofocus placeholder="Enter product key here" />
</p>
<p>
<input type="text" id="device_id" autofocus placeholder="Enter device ID here" />
</p>
<p>
<input type="submit" value="Submit" onclick="update()" />
</p>
<h1>Rotary Gate Systems</h1>
<article>
Open
</article>
<article>
Close
</article>
<article>
<p class="status_closed status_button">CLOSED</p>
<p class="status_open status_button">OPEN</p>
<p class="status_none status_button">NO CONNECTION</p>
</article>
Related
Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>
I need help understanding how to fix this.
<p> Enter a number in the box. </p>
<div>
<label for ="numberSubmitted"> Number: </label>
<input type="text" class="numberSubmitted">
<input type = "submit" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
var numberSubmitted = Number(numberSubmitted.value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
What's happening is that "You Lose!" is being printed out if I leave the variable as
var numberSubmitted = Number()
If change it to
var numberSubmitted = Number(numberSubmitted.value)
the code just doesn't work.
I don't see online any guide to tell you how to use Number() with classes.
Can anyone please point me in right direction on when to include class when defining the Number method?
So there are a few things:
The "for" in label needs to point to an id, not a class.
Your problem with it not working when you try to put numberSubmitted.value into Number() is that numberSubmitted is undefined, to fix this you need to get the html element of your input box and do .value on that.
You need to put your JavaScript in a script tag.
Try the following:
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type = "submit" value="Submit" onclick="submit()">
</div>
<div>
<p class="message"></p>
</div>
<script>
function submit() {
var numberSubmitted = Number(document.getElementById('numberSubmitted').value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
</script>
Here's another option, using an event listener instead of the inline function call:
JS Fiddle Demo here.
HTML
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type="button" id="myBtn" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
JS
//bind the listener to the button
document.getElementById('myBtn').addEventListener('click', myFunction);
//get the input element
var el = document.getElementById('numberSubmitted');
function myFunction() {
var numberSubmitted = Number(el.value);
//for debug
console.log(numberSubmitted);
var message = document.querySelector(".message");
if (isNaN(numberSubmitted)) {
message.textContent = "That isn't a number.";
return;
}
if (numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
As mentioned in my comments earlier, you need to wrap your JS in script tags. I've made other comments in the code segments above. You'll notice that wrapping your original JS in script tags isn't enough -- there is still an 'undefined' error pertaining to the numberSubmitted element. This is because JS has no idea what numberSubmitted is -- you need to find the element in the DOM and assign it to a variable. I've shown you how to do that above.
Im working on a small form and using js to validate if the fields are empty or not. I have a span class next to the name field "name" "email".
For the "name" field, i have a span class called "error".
For the "email" field, i have another span class called "error2".
what can i do to only use one class to display the "error message", because of course i will have more field and I don't want to keep adding more classes. error3, error4
HTML:
<form action="#i" name="myForm" onsubmit="return(validate());">
Name: <span id="error"></span><br>
<input type="text" name="Name" /><br><br>
EMail: <span id="error2"></span><br>
<input type="text" name="EMail" /><br> <br>
<input type="submit" value="Submit" /> <br>
</form>
JS:
function validate()
{
var t = 0;
if( document.myForm.Name.value == "" )
{
document.getElementById('error').innerHTML = "<br>Empty";
t = 1;
}
if( document.myForm.EMail.value == "" )
{
document.getElementById('error2').innerHTML = "<br>Empty";
t = 1;
}
if(t == 1)
{
return false;
}
else
return true;
}
Instead of giving the spans the attribute of Id, use classes instead. So for example, you can define ALL your spans as follows:
<span class="error"> ... </span>
Then, in your validate function, you can obtain these spans through:
document.getElementsByClassName('error');
Keep in mind though, this returns an array, which would actually be perfect for your function. This way, you can write a basic for-loop to go through each span and make sure each field is filled in correctly.
I need to make an array of passwords looping for the user to be redirected to another site. After 3 mistakes the user cannot try again. This is what I have so far, but it doesn't work.
<form>
<label>Please enter Password</label>
<input type="text" id="Pass" />
<input type="button" value="go" onClick="check()" />
</form>
<script type="text/javascript">
function check()
{
var password = ["123","456","789"]
for(a=0;a=password.length;a++)
{
if (user="password")
{
document.location.href="http://yahoo.com";
}
else
{
alert("wrong password");
}
}
}
</script>
As you are calling a function check from the onclick event, you need a function by that name in your code.
When calling the check function you can pass along the value from the text box, so that the function can use it to check against the items in the array.
In your code the condition for the loop is wrong. Using a=password.length means that the loop won't run at all. The loop runs as long as the condition is true, it's not used to mark the end of the loop.
Use the == operator to check if two values are equal (the = operator is for assignment). Use password[a] to get the item from the array which has the index from the variable a.
In the loop you should only check for when the strings are equal. If you have an else case there, it will tell you that the password is wrong for every password that didn't match. Use return to exit from the function when you have set the location.
After the loop you know that none of the password matches, so then you know that the password was wrong.
<body>
<form>
<label>Please enter Password</label>
<input type="text" name="Pass" />
<input type="button" value="go" onclick="check(this.form.Pass.value)"/>
</form>
<script type="text/javascript">
var password = ["123","456","789"];
function check(pass) {
for(a = 0; a < password.length; a++) {
if (pass == password[a]) {
document.location.href="http://yahoo.com";
return;
}
}
alert("wrong password");
}
</script>
</body>
For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/