check if javascript var is equal to string - javascript

I have a php page the verifies the username users type in, and echo's back "available!" if its available into a div called "feedback". now I have this JavaScript that I want to check to see if the "feedback" div says "available! and echo "username good" into the "check" div if it is. but it doesn't work and i don't know why.
<script type='text/javascript'>
function check_info(){
var username_good = document.getElementById('feedback').value;
if(username_good == "available!"){
document.getElementById("check").innerHTML = "username good";
}
else{
document.getElementById("check").innerHTML = "bad";
}
}
</script>

A div doesn't have a value property, you need to use innerHTML:
var username_good = document.getElementById('feedback').innerHTML;

Fiddle for the same added.
<div id="feedback">test</div>
<div id="check"></div>
<input type="button" onclick="javascript:check_info()" value="Validate">
function check_info(){
var username_good = document.getElementById('feedback').innerHTML;
if(username_good !== ""){
document.getElementById("check").innerHTML = "username good";
}
else{
document.getElementById("check").innerHTML = "bad";
}
}

Related

How to use RegExp in Javascript

I want to use RegExp in else if(){} statements. How is it done?
I want to do:
If the user's value (prompt) is equal to "javascript" or "JaVaScRipT" then let the else if statement work.
<body>
<button onclick="javascript:notfic();">Click</button>
<p id="result"></p>
<script>
"use strict"
function notfic(){
let message="", result, del;
result = document.querySelector('#result');
del = prompt("Please, enter your answer");
if (del == null || del==""){
message = "You must write answer";
}else if(del == /javascript/i){
message = "You enter correct answer. Your answer is: <br> " + del;
}else{
message = "Sorry, your answer is wrong. Your answer is: <br>" + del;
}
result.innerHTML = message;
}
</script>
</body>
Your you need to call the test method:
else if(/javascript/i.test(del))
Read this for more info

Why is nothing happening when I click on onclick button?

*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.

Resolve the error: Cannot read property 'style' of null" with a better approach?

I have a common js file for 2 different pages. In Page 1, I just want to show the text2 field when the LName input has any value. Otherwise, I want it to be hidden. So I created an if condition to see whether there is any value for the LName input and if there is no value, I kept the display: none;.
In Page 2, I don't need the div for id="text2", so dropped it. As a result, whenever I give an input, it returns an error as there is no div with id="text2".
I need a single js file, at the same time, I need to show the text2 div in Page 1 but I don't want to keep the <div id="text2" class="display: none;"></div> in the Page 2 as I don't need it there. How can I solve this problem? Is there any better approach I could take?
This is the working Page 1 in jsfiddle.
And this is the Page 2 in the snippet, that returns an error:
$(document).ready(function() {
$(document).on("keyup change", "#FName, #LName", function() {
var FName = $('#FName').val();
var LName = $('#LName').val();
var listP = document.getElementById('list');
if ($('#FName').val() == "") {
listP.style.display = 'none';
} else {
listP.style.display = 'block';
}
var text2P = document.getElementById('text2');
if ($('#LName').val() == "") {
text2P.style.display = 'none';
} else {
text2P.style.display = 'block';
}
$('#text1').html('<li>This is text 1</li>');
$('#text2').html('<li>This is text 2</li>');
$('#text3').html('<li>This is text 3</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
FName: <input name="FName" id="FName"><br> LName: <input name="LName" id="LName"><br>
<div id="list">
<div id="text1"></div>
<div id="text3"></div>
</div>
Check if text2P is not falsy:
var text2P = document.getElementById('text2');
if (text2P) {
if ($('#LName').val() == "") {
text2P.style.display = 'none';
} else {
text2P.style.display = 'block';
}
}
Doc
MDN web docs: Falsy

javascript- resetting a variable

I am trying to make a basic program to run on a html page. It gives you an answer after clicking a button and inputing something and looks like:
<button type="button" onclick="whatsong()">Click to enter a song</button>
<p id="result"></p>
<script>
function whatsong() {
var song = prompt("please enter a song");
if (song = "example") {
document.getElementById("result").innerHTML = "yes";
}
if (song = "example2") {
document.getElementById("result").innerHTML = "no";
}
</script>
I want the variable song to reset so that the user could enter a song that prints no onto the webpage, then press the button again and enter a song that would yield a yes, without it still displaying no', like it does at the moment, and instead printing yes.
UPDATE: http://istyjorapping.atwebpages.com/ is the actual webpage, and it has multiple options per if (e.g.
if (song == "heavydirtysoul", "ode to sleep", "fake you out", "forest")
{ document.getElementById("result").innerHTML = "yes";
}), and any suggestions i have tried so far have made it give some strange results that the debugger i normally use can't work out.
You need to use ==(Equality) or ===(Identity) operator instead of =(assignment)operator
function whatsong() {
var song = prompt("please enter a song");
if (song == "example"){
document.getElementById("result").innerHTML = "yes";
}
if (song == "example2"){
document.getElementById("result").innerHTML = "no";
}
}
A good read Which equals operator (== vs ===) should be used in JavaScript comparisons?
<button type="button" onclick="whatsong()">Click to enter a song</button>
<p id="result"></p>
<script>
function whatsong() {
var song = prompt("please enter a song");
if (song == "example") {
document.getElementById("result").innerHTML = "yes";
}
if (song == "example2") {
document.getElementById("result").innerHTML = "no";
}
}
</script>
So as i have understood, on the click of a button you want to take a user input and based on the user input you want to display a particular text.
Below is the sample code for that
HTML
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<p id="result"></p>
JS will be
function myFunction() {
var song = prompt("please enter a song");
if(song==='example'){
document.getElementById("result").innerHTML = "yes";
}
if(song==='example2'){
document.getElementById("result").innerHTML = "no";
}
}
I HOPE THIS HELPED. LET me know if you liked the solution. There can be many multiple ways too.

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Categories

Resources