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>
Related
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>
I'm a beginner in javascript. I ask a question on how to store the even numbers and display all the input even numbers into a <p> tag. For example, I input 4 so that the <p> displays 4. Then if I input again for example 6 so that <p> will become 4,6.
Is it possible to do it?
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
var numbers=[];
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
Your problem is that you are re-initialising your numbers array in every call to the number function. You can fix that by making it a property of the function and only initialising it if it is undefined. Then you can use join to convert the array into a comma separated list (although this is not strictly necessary as array to string conversion will do that for you anyway):
function number() {
this.numbers = this.numbers || [];
var number = document.getElementById("number").value;
if (number % 2 === 0) {
// alert("Your number is Even");
numbers.push(number);
document.getElementById("display_even").innerHTML = numbers.join(',');
}
else {
alert("Please Insert Even number");
}
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
It is a very simple thing. Each time when a user is entering a number and running the function, the number of values inside the array is set to 0. The simplest solution is to declare the array outside of the function:
var numbers=[];
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
function number(){
var number = document.getElementById("number").value;
if(number%2===0){
alert("Your number is Even");
var num = document.getElementById("display_even").textContent;
var numbers=[];
if(num){
numbers.push(num);
}
numbers.push(number);
document.getElementById("display_even").innerHTML=numbers;
}
else
alert("Please Insert Even number");
}
<input type="text" name="" id="number">
<button type="submit" onclick="number()">Click</button>
<p id="display_even"></p>
I create a multiphase form (wizards from) and I want to show in the last step all Information in input text (you can modify it) before validate
I try a lot but without any result, how can I do it ?
My code
var fname, lname, age;
function _(x) {
return document.getElementById(x);
}
function processPhase1(){
fname = _("firstname").value;
lname = _("lastname").value;
if(fname.length > 2 && lname.length > 2){
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
else {alert("Please Enter All Information");}
}
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
}
else {alert("Please Enter All Information");}
}
<body>
<div id="phase1">
First Name : <input id="firstname" name="firstname"><br>
Last Name : <input id="lastname" name="lastname"><br>
<button onclick="processPhase1()">Next</button>
</div>
<div id="phase2">
Age : <input id="age" name="age"><br>
<button onclick="processPhase2()">Next</button>
</div>
<div id="show_info">
First Name : <input id="firstname" name="firstname" value = ""><br>
Last Name : <input id="lastname" name="lastname" value = ""><br>
Age : <input id="age" name="age" value = ""><br>
<button onclick="submit()">submit</button>
</div>
I try this but it's just for showing Information, but you can't modify it, I need to show it in input text
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
_("display_fname").innerHTML = fname;
_("display_lname").innerHTML = lname;
_("display_age").innerHTML = age;
}
else {alert("Please Enter All Information");}
}
<div id="show_info">
First Name : <span id="display_fname"></span><br>
Last Name : <span id="display_lname"></span><br>
Age : <span id="display_age"></span><br>
<button onclick="submit()">submit</button>
</div>
I would have done this completely different, but this is how you would do it based on what you've already written. When you click the next button in each function, you want to grab that value of (fname, lname, or age) and set the value of that to the value of the last set of inputs. I've altered your code a bit and made you a JS BIN http://jsbin.com/sopikuzuri/edit?html,output
In simple terms
Each time you call a new phase function (processPhase1), you want to grab the values of what the user just entered.
Then, you want to set those values to the proper <input />
So, the simplest example I can give is this:
Below, the user will enter some data into the field. When they click the submit phase 1 button we will grab the value of what they just entered and set that value to the last input (for them to see/edit)
<input type="text" id="firstName"/>
<button id="submit">Submit Phase 1</button>
<input type="text" id="displayInput"/>
<script>
$("#submit").click(function() {
// getting the value of what the user typed in
var fname = $("#firstName").value;
// setting the value of the final box to the var above
$("#displayInput").val(fname);
});
</script>
New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.
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>