Javascript if else problem - javascript

My if-else is not working, I think that I have a variable issue. When I look at the value of x it is not what is entered in the text field. Any Ideas?
function guess() {
var x = document.getElementById("magic");
var word = "please";
if (x == word) {
alert("You entered the magic word!");
} else {
alert("Please try again!");
}
}
<form>
What is the magic word?<br />
<input type="text" id="magic" onchange="guess()" />
</form>

You're not getting the value. Use this:
var x =document.getElementById("magic").value;

You want:
var x = document.getElementById("magic").value;
Also, onchange won't work, you'll need to use onkeyup, although onblur is probably more sane:
What is the magic word?<br />
<input type="text" id="magic" onblur="guess()" />
function guess() {
var x = document.getElementById("magic").value;
var word = "please";
if (x == word) {
alert("You entered the magic word!");
} else {
alert("Please try again!");
}
}
http://jsfiddle.net/6uAhq/

You need to check against the actual value of the "magic" element, e.g.:
var x = document.getElementById("magic").value;
I'm assuming "magic" is an input.

Related

If statement not working correctly in Javascript

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>

Make alert appear when start typing input

I am trying to make something happen only when a user inputs data into an input element that has been created. However I don't want to validate that data has been inputted or make the user press a button to check if data has been inputted, I want something to happen as soon as the first data value is typed in the input field. I decide to just use a demo of something similar that I want to create - to cut out the clutter:
I have tried:
var input = document.getElementById("input");
if(input == ""){
alert("no value");
}else{
input.style.background = "blue";
}
<input type="text" id="input">
But nothing seems to be working. For what reason is it not working?
So in this example I would only want the background to be blue when the first data value is typed in.
I also tried:
var input = document.getElementById("input");
if(input.length == 0){
alert("no value");
}else{
input.style.background = "blue";
}
and:
var input = document.getElementById("input");
if(input == undefined){
alert("no value");
}else{
input.style.background = "blue";
}
as well as variations using != and !==
Is it something small I'm missing?
You were checking the actual element, not it's value. And, you didn't have any event listener set up for the element. But, it doesn't make much logical sense to check for no value after a value has been entered.
// When data is inputted into the element, trigger a callback function
document.getElementById("input").addEventListener("input", function(){
// Check the value of the element
if(input.value == ""){
alert("no value");
}else{
input.style.background = "blue";
}
});
<input type="text" id="input">
Try this,
jQuery
$('#input').keyup(()=>{
if($('#input').val() == ""){
alert("no value");
} else{
$('#input').css({backgroundColor: 'your-color'});
}
});
Hello you can try this
<input type="text" id="input" onkeyup="inputfun()">
<script type="text/javascript">
function inputfun(){
var input = document.getElementById("input");
if(input.value == ""){
input.style.background = "";
alert("no value");
}else{
input.style.background = "blue";
}
}
</script>
function handleCurrentInput(event) {
const value = event.target.value;
if (!value) {
alert("no value");
} else {
alert("value entered -->", value);
}
}
<input type="text" id="input" onInput="handleCurrentInput(event)">

Javascript - text input to icon

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>

How to check value length with using Javascript?

Hello everyone I would like to ask how to check value's length from textbox ?
Here is my code :
#*<script>
function validateForm() {
var x = document.forms["frm"]["txtCardNumber"].value;
if (x == null || x == "" ) {
alert("First name must be filled out");
return false;
}
}
</script>*#
When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.
You could use x.length to get the length of the string:
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].
So if you have an input field:
<input type="text" id="txtCardNumber" name="txtCardNumber" />
you could retrieve its value from the id:
var x = document.getElementById['txtCardNumber'].value;
Still more better script would be:
<input type="text" name="txtCardNumber" id="txtCardNumber" />
And in the script:
if (document.getElementById(txtCardNumber).value.length < 5) {
alert('please enter at least 5 characters');
return false;
}

Javascript form validation

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}

Categories