I would like to have a text field that a user can enter a number and if the number is correct it the displays "image a" and if incorrect displays "image b" below the text field i want them to have as many tries as they like to get it correct. The only thing i have found so far is this?
sorry about the lack of experience guys :(
var my_string = prompt("Please enter a number","");
document.write(my_string)
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}
The user will enter characters, so you'll have to compare strings. You can use the === operator which checks equality; you'll have to check against the string "25".
Then, to display the image, you'll have to give the images in HTML an ID. After doing so, you can fetch the element in JavaScript using document.getElementById("some_id"). Showing/hiding is done using element.style.display = "block" vs "none".
Heres code sniplet:
<script type="text/javascript">
function check_number()
{
var num = document.getElementById('input_number').value;
var img = num == '25' ? 'good.png' : 'bad.png';
document.getElementById('result_image').src = img;
document.getElementById('result').style.display = 'block';
}
</script>
<input type="text" id="input_number"
<input type="submit" onclick="check_number();return false;">
<div id="result" style="display:none;">
<img src="blank.png" alt="" id="result_image">
</div>
This will get you started
var my_string = prompt("Please enter a number","");
document.write(my_string);
if(my_string === '25'){
document.write('Yesss');
} else {
document.write('Wrong');
}
Related
Im trying to display an error message in RED beside the input field to let the user know, however I dont know why my error message is not working. The requirement for the input is starting with a capital letter, followed by non special characters (any alphabets) please help me see what is wrong with my code
I am still new to HTML and I know many people said about regex but im not sure i have not learn that
<html>
<script>
function validateForm() {
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
</script>
<style>
#errorName
{
color:red;
}
</style>
<form action="handleServer.php" method="get" onSubmit="return validateForm()">
<body>
<!-- starting with first name-->
First name: </br>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName"></br>
<input type="submit" value="Submit">
</body>
</form>
</html>
I see your if statements are not closed properly and also the input box.
Please find codepan
function validateForm() {
console.log(1);
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
}
}
When i tend to use regex i store it in its own value like this:
const patternName = /[0-9]|[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/|#]/;
let resultName = patternName.test(name.value);
The code above checks if the name contains anything from the regex above and if it does resultName will return true.
Next we can do the following:
If name is empty you get an error and it contains anything from the regex above we. In this case we show the error
If resultName is true we know that name contains something from the regex, so that it's not a valid name.
If not we show success message
if (name.value === "" || resultName) {
showErrorName();
} else {
showSuccessName();
}`
I'm trying to search a particular word on the input field and perform if/else condition accordantly. for an example input field can be "iPhone 6" or "Apple iPhone 5" or " Samsung A7" o "S9 Samsung" etc. Please help me find word "iPhone" or "Samsung" from the input field apply if/ else condition.
<input type="text" id="ModelNo" />
<script>
var Model_Validation = document.getElementById("ModelNo").value;
var Model_1 = "iPhone";
var Model_2 = "Samsung";
function test() {
if (Model_Validation == Model_1) {
} else if (Model_Validation == Model_2) {
} else {}
}
</script>
I doubt which logic to use in if condition as well. hope my question is clear.
You can use the includes method on your input's text.
let input = document.getElementById("ModelNo").value;
if(input.includes(Model_1)){/* do something*/}
else (input.includes(Model_2)){/* do something else*/}
Or you can use a regular expression but includes should be more efficient and simple for what you want to do.
This could be achieved with JQuery:
<input id="search" type="input" value="type here"/>
<div id="result"></div>
$(document).ready(function(){
$("#search").on('input',function(){
var userinput = $(this)[0].value;
if(userinput == 'samsung'){
$("#result").html('user inserted "samsung"');
}
else{
$("#result").html(userinput);
}
})
});
Working example here
This is my first time posting here since I haven't been able to find a specific answer for my question anywhere so apologies if I'm doing something wrong.
Anyway, I wanted to know if there was a way to convert text from a form input to a string and grab a substring of that text?
For example if I have a form input like this:
<form onsubmit="return formValidation()">
<input type="text" name="foo">
</form>
Can I grab whatever is typed into that input like so?
function myFunction() {
var string = document.getElementByName('foo').value;
// Code converting the selected element to a string
var index = string.substring(0, 2);
// Rest of code
}
I have little experience in JavaScript so I'm confused on how to convert an element to string. jQuery solutions are welcome.
I wanted to do this for an ID number validation on a form, which basically checks the first two indexes of an 8-digit ID number to see if it's a known ID number in my school district.
Thanks!
EDIT:
Okay so since people actually saw this, could anyone tell me what's wrong with this code? It's returning false even for numbers starting with the numbers here.
function formValidation() {
var idInput = document.getElementsByName('idNumber')[0].value;
var idNumber = idInput.substring(0, 2);
if(idNumber === "71" || idNumber === "81" || idNumber === "53") {
alert("Your form has been submitted. You will now be redirected to a confirmation page.");
return true;
} else {
alert("Please input a valid ID number. If the first two integers of your ID do not match the school district standard, contact a club leader.");
return false;
}
}
Is the method I'm using to compare strings wrong?
Problem is: document.getElementByName('foo').value, you have missed s
document.getElementsByName('foo')
^
document.getElementsByName('foo') gives you NodeList, not just a single HtmlElement,
Use instead:
document.getElementsByName('foo')[0].value;
Edited: Have a look at below functional code.
function formValidation() {
var idInput = document.getElementsByName('idNumber')[0].value;
var idNumber = idInput.substring(0, 2);
if (idNumber === "71" || idNumber === "81" || idNumber === "53") {
alert("Your form has been submitted. You will now be redirected to a confirmation page.");
return true;
} else {
alert("Please input a valid ID number. If the first two integers of your ID do not match the school district standard, contact a club leader.");
return false;
}
}
<form onsubmit="return formValidation();">
<input type="text" name="idNumber" autofocus="" value="71456" maxlength="8" />
</form>
Edit: |SOLVED| user Jaromanda X's solution worked perfectly. Thank you
My goal is to have the user enter a bit of text into the textbox and submit it. I want to check and see if the textbox is empty and, if so, it should alert the user that a name needs to be entered. If it is not empty I want it to display the text they had entered.
The issue is this: Every time I hit submit it takes the value of the textbox - empty or not - and displays it without ever alerting the user of an empty text field. I feel like I'm missing something very basic. Thank you for your help!
HTML File
<body>
<div id="statusBar">
<h1 id="playerName"></h1>
<h2 id="playerHP"></h2>
</div>
<div id="gameWindow">
Player Name: <input id="inputName" type="text" name="Player Name">
<br>
<input type="button" value="submit" onclick="getStats()";>
</div>
<script src="script.js"></script>
</body>
JS File
function getStats(){
if(document.getElementById("inputName").len === " "){
alert('You must enter a name!');
} else {
var playerHP = 10;
var playerName = document.getElementById('inputName').value;
//Display player name on screen
document.getElementById('playerName').innerHTML = playerName;
//remove the value placed in the text box
document.getElementById('inputName').value = "";
//Display the player's HP
document.getElementById('playerHP').innerHTML = playerHP;
}
};
Change your if statement to:
if (document.getElementById("inputName").value.length === 0) {
Right now you're trying to get a property len of your <input> element, which doesn't exist. You should first be getting the value of the input, and checking if its length is zero. Hence, .value.length.
It should be:
if (document.getElementById("inputName").value === "") {
// do something
}
You're not using the right conditional.
Replace the
document.getElementById("inputName").len
with
document.getElementById("inputName").value.length === 0.
i keep trying everything to get these alerts to pop up correctly. i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. here is the entire code that doesnt do anything:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- VARIABLE DECLARATION -->
f1.city.focus();
function check_form()
{
at_sign = email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
}
else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
}
else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
}
else if((at_sign<1) || (email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" action="smartform.html">
<b>City</b>
<input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
<b>State</b>
<input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
</form>
</BODY>
</HTML>
edit: nothing seems to be working that everyone says.. here is my new code:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
f1.city.focus();
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
if(f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
return false;
}
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
return false;
}
else if((at_sign<1) || (f1.email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
return false;
}
else
{
//document.write("Form completed");
}
return false;
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" onSubmit="return check_form(this)">
<b>City</b>
<input type = "text" name = "city" size = "18" value="">
<b>State</b>
<input type = "text" name = "state" size = "4" value="">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="">
<input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
</form>
<b>hi</b>
</BODY>
</HTML>
still get no alerts... i put that hi up and got that.. but no alerts......
alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. I simplified it to this:
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function check_form()
{
document.write("Form started");
var at_sign = document.f1.email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
document.f1.city.focus();
//return false;
}
else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
document.f1.state.focus();
//return false;
}
else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
{
alert('Please enter a 5 digit zip code');
document.f1.zip.focus();
//return false;
}
else if((at_sign<1) || (document.f1.email.value.length<3))
{
alert('Please enter a valid email address');
document.f1.email.focus();
//return false;
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY onLoad= "javascript:document.f1.city.focus();">
<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
<b>City</b>
<input type = "text" name = "city" size = "18">
<b>State</b>
<input type = "text" name = "state" size = "4">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5">
<b>Email</b>
<input type = "text" name = "email" size = "18">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>
</BODY>
</HTML>
I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. but my question is, why doesnt an alert happen along the way to this result? it seems like even if the page got overwritten, it should still pop up. also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement?
update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error?
also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? I'm attempting this as i type.
You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, e.g.
<form onsubmit="return check_form(this);" ...>
You should reference the controls as properties of form using their name, don't use the name as a global variable. And declare all variables.
So the function looks like:
function check_form(form) {
var at_sign = email.search(/#/);
if (form.city.value.length < 1) {
alert('Please enter a city');
f1.city.focus();
// cancel submit by returning false
return false;
} else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
...
}
You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt.
Using document.write after the page has finished loading (e.g. when submitting the form) will erase the entire content of the page before writing the new content.
Edit
Here's what's wrong with your new code:
<SCRIPT LANGUAGE="JavaScript">
Get rid of the language attribute. It's not harmful (well, in a very specific case it might be).
f1.city.focus();
f1 has no been defined or initialised (see comments above about element names and global variables)
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
f1.email is an input element, it has no search property, you can't call it. It does have a value property that is a string, perhaps you meant:
var at_sign = f1.email.value.search(/#/);
Then there is:
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. You want:
else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))
Note that this requires users to enter the state in capital letters, it might help to tell them about that.
Then there is:
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))
isNaN is a global variable, not a method of strings. If no value has been entered, then the value is the empty string and isNaN('') returns false. If you want to test that 5 digits have been entered then use:
else if (!/^\d{5}$/test(f1.zip.value))
There is no need to test against true, just use it, nor is there a need to group simple expressions:
else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))
Then finally, if all the test pass:
return false;
that stops the form from submitting. You can omit this return statement, returning undefined will let the form submit. Or return true if you really want.
Ok I want to answer your question but first things first lets walk through your
code and clean it up.
Use this as a template of properly formated code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Form</title>
</head>
<body>
<!-- Code goes here -->
<script type="text/javascript">
</script>
</body>
</html>
Tags & attributes don't need to be capitalized. Javascript comments are like this:
/** Comment. */
Html comments are like this:
<!-- Comment. -->
Also nitpick: attributes should be followed by an equal sign not a space. i.e.
<form name="f1" id="smartForm" action="smartform.html"> ... </form>
Next up proper event binding.
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. Open up the developer console. Evergreen browsers (Chrome, Firefox etc...) have good ones these day. The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. So look up how to open up the developer console in your browser for your platform and type this into your console:
1+1
Should evaluate to: 2.
Next type: document
If you click around you can see that you can walk through the dom a little bit.
Next load up your smartForm app with my changes above and type:
document.getElementById('smartForm')
You should see your element. This is how to properly query objects in the dom.
You'll notice that if you type document.smartForm doesn't work. You should get null, this should tell you that there should be a way to get the element from the document. Hint, it's getElementById. So if you put id's on all your inputs then you can make a list of all the document objects you can query:
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
Next you can start querying the values and such like you were doing:
cityElement.value.length != 2
A cleaned up version would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Smart form</title>
</head>
<body>
<form id='smartForm' action='smartform.html'>
<b>City</b>
<input type="text" id="city" size="18">
<b>State</b>
<input type="text" id="state" size="4">
<b>Zip Code</b>
<input type="text" id="zip" size="5">
<b>Email</b>
<input type="text" id="email" size="18">
<input type="submit" value="done">
</form>
<script type="text/javascript">
var validateForm = function(evt) {
var error = false;
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
if (cityElement.value.length != 2 ||
!(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
error = true;
alert('oops');
cityElement.focus();
}
// etc..
if (error) {
evt.preventDefault();
}
};
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
</script>
</body>
</html>
Ok a couple more things I noticed. charCodeAt is for strings only. "hi".chatCodeAt not element.charCodeAt. Also you have this random variable at_sign.
You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console
Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. Trust me, let debugging tutorials be your bread at butter!
Full working example of your code:
http://codepen.io/JAStanton/pen/tjFHn?editors=101
A little less verbose version:
http://codepen.io/JAStanton/pen/iBJAk?editors=101
onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p
<form onsubmit="return check_form();" ...
There are several mishaps in your code that might also cause errors and prevent that from working
Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen)