Javascript stops working when I change the desired output - javascript

//THIS CODE WORKS PERFECTLY, IT PLACES A RECOMMENDATION IN A DIV (Suggestion) BASED ON LIGHT STATUS
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL=="Flashing/Off"){
document.getElementById("suggestion").innerHTML= "Consider NO Sync";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("suggestion").innerHTML= "Consider NO ROUTE";
} else {
document.getElementById("suggestion").innerHTML="Consider WALLED GARDEN OR CONNECT NO BROWSE";
}
}
// TRYING TO MAKE CORRESPONDING DIV OPEN INSTEAD OF JUST POPULATING THE SUGGESTION DIV- BROKEN, DOES NOT WORK
// "if" works, but not "if else" or "else", even though the logic is the same as above and works there.
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL=="Flashing/Off") {
document.getElementById("noSync").style.display="block";
document.getElementById("noRoute").style.display="none";
document.getElementById("CNB").style.display="none";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("noRoute").style.display="block";
document.getElementById("noSync").style.display="none";
document.getElementById("CNB").style.display="none";
} else {
document.getElementById("CNB").style.display="block";
document.getElementById("noSync").style.display="none";
document.getElementById("noRoute").style.display="none";
}
}
Please let me know if you see what I am missing… I can’t find my error
I did correct the typo in .style.display, but it is still not working.
Thanks for pointing that out, but something is still wrong.

You have a few typos, sytle instead of style

Have you tried using === for your if/else if statements? This link explains the difference between == and ===.
<html>
<body>
<input type="text" id="selIntLght"/>
<input type="text" id="selDSL"/>
<button onclick="getIntLght()">submit</button>
<div id="intLght"></div>
<div id="suggestion"></div>
<div id="noSync" style="display:none">No sync</div>
<div id="noRoute" style="display:none">No Route</div>
<div id="CNB" style="display:none">CNB</div>
<script>
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//hide divs initially
document.getElementById("CNB").style.display="none";
document.getElementById("noSync").style.display="none";
document.getElementById("noRoute").style.display="none";
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL==="Flashing/Off"){
document.getElementById("suggestion").innerHTML= "Consider NO Sync";
document.getElementById("noSync").style.display="block";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("suggestion").innerHTML= "Consider NO ROUTE";
document.getElementById("noRoute").style.display="block";
} else {
document.getElementById("suggestion").innerHTML="Consider WALLED GARDEN OR CONNECT NO BROWSE";
document.getElementById("CNB").style.display="block";
}
}
</script>
<html>

Related

angucomplete undesirable click event fires

Recently, I am implementing autocomplete on my search using angucomplete, now the desired output that I wish to achieve is that whenever I select one of the autocomplete suggestions by clicking the mouse, it would navigate to the desire url or let's say google.com for test purposes. The problem with code below is that when I click the textbox without selecting any suggestions, navToUrlByClick function will fire. Any suggestions and sorry for this kind of question since the writer just started to explore javascript. Thanks in advance!
This is my test.html code:
<div class="padded-row" ng-click="navToUrlByClick('http://www.google.com')">
<div angucomplete-alt id="ex5"
placeholder="Search projects"
pause="50"
selected-object="selectedProject"
remote-url="http://localhost:5000/"
remote-url-request-formatter="remoteUrlRequestFn"
remote-url-data-field="items"
title-field="subs_name"
minlength="1"
input-class="form-control form-control-small"
match-class="highlight">
</div>
</div>
And this is my app.js code:
$scope.navToUrlByClick = function(str){
if ((str != "") || (str != null))
{
console.log(str)
//$window.location.href = str;
}
}
I figure it out by using callback with the few lines of code below and added to my app.js
$scope.selectedProject = function(selected) {
if (selected) {
// window.alert('You have selected ' + selected.title);
$window.location.href = "http://www.google.com";
} else {
console.log('cleared');
}
};
Case closed!

javascript if condition is not working

i'm trying to work the following code of script. but its not working. i don't know what is the problem. the x variable i created contains nothing. but still the if condition is not working. i have tried printing the x variable in an alert box and it prints nothing, which means that it contains nothing. But in its not picking up the condition don't know why. And there are no console errors.
<div id="test">
</div>
<script>
var x = document.getElementById("test").innerHTML;
if(x == '') {
document.getElementById("test").innerHTML = 'There are No friends posts yet my love!!';
}
</script>
Your variable x contains not empty string but some spaces. Try to use trim() function to remove these symbols:
if(x.trim() == ''){
...
}
This will work!
<script>
var x=document.getElementById("test").innerHTML;
if(x.trim() == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my love!!';
}
</script>
use innerText
if(x.innerText === ''){
https://jsfiddle.net/s4aLcfm5/
The issue is that your 'x' variable is not empty. It contains two return characters. Try removing all the white-space between your open and close div statement. Here is the corrected code:
<div id="test"></div>
<script>
var x=document.getElementById("test").innerHTML;
debugger;
if(x == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my love!!';
}
</script>`
Simply add or remove returns within the div statement to see this work or not work.
Your code works. It all comes down to the way that your html is written:
<div id="test">
// This is an unnecessary space that's what is making your condition fail
</div>
<script>
var x=document.getElementById("test").innerHTML;
if(x == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my
love!!';
}
</script>
Clean up your html: <div id="test"></div>
And you don't need anything else

javascript function is adding data to screen but then being overridden by another function

My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}

Trying to add promo code functionality to paypal transaction

I've looked everywhere and sifted through the paypal api but my downfall as a developer is when I look at code that isn't my own, I'm looking at a bunch of hieroglyphics that have absolutely no resonance with me. I've been given the task of adding promo code functionality to a site I had no hand in building
I made some progress on my own from looking at an online example so it shouldn't require a bunch of assistance, the live site is http://alphafreakapparel.com/viewcart.php1 . I have an item in the cart and I enter the promo code which is ALPHAPENCE15 and i get just one console error. The code I added is this script in the head of the html doc
<script language = "javascript">
<!--
function validate(text1,text2) {
var text1;
if (text1 == text2)
{
window.alert("15% discount applied!");
data.cart_total.toFixed(2) = data.cart_total.toFixed(2) * 0.15;
}
if (text1 !== text2)
{
window.alert("Incorrect code");
}
}
function CalculateOrder(form) {
if (form.text1.value == "ALPHAPENCE15")
{
form.discount_rate.value = "15";
form.discount_rate2.value = "15";
form.on3.value = "Coupon Entered";
form.os3.value = "ALPHAPENCE15";
}
}
//-->
</script>
and this code to prompt the code
<!-- Start Coupon Validate -->
Enter Promo Code:
<input type="text" name="text1">
<input type="button" value="Check" name="Submit" onclick=javascript&colon;validate(text1.value,"ALPHAPENCE15") >
<!-- End Coupon Validate -->
the error i got was
Uncaught ReferenceError: text1 is not defined viewcart.php:78onclick
What do you think is causing it? I added the var text1; just for that reason.
Also note, I'm not sure if this was the correct way to do this, but to apply the 15% off, I just put *0.15 in the if statement in the head script so that when the if statement completes, it adjusts the total.

Uncaught typeError undefined is not a function

I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined

Categories