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: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.
Related
I am using the same JavaScript that works flawlessly in one page in a second page, but I am getting an error in the second page. I didn't write the JavaScript and can't change it, so please help me figure out what is causing the error.
I tried moving the line of code that calls the JavaScript around, but that doesn't help. I checked the first page against the second page, but don't see anything that would make it stop working.
Calling the JavaScript here:
<script type="text/javascript" src="<?php echo base_url(); ?>js/rating.min.js"></script>
The JavaScript code is:
!function(){
"use strict";
function t(t,i,n,e){
function r(t,i){
for(var n=0;n<t.length;n++){
var e=t[n];i(e,n)
}
}
function a(t){
s(t),o(t),u(t)
}
function s(t){
t.addEventListener("mouseover",function(i){
r(f,function(i,n){
n<=parseInt(t.getAttribute("data-index"))?i.classList.add("is-active"):i.classList.remove("is-active")
})
})
}
function o(t){
t.addEventListener("mouseout",function(t){
-1===f.indexOf(t.relatedTarget)&&c(null,!1)
})
}
function u(t){
t.addEventListener("click",function(i){
i.preventDefault(),c(parseInt(t.getAttribute("data-index"))+1,!0)
})
}
function c(t,a){
t&&0>t||t>n||(void 0===a&&(a=!0),i=t||i,r(f,function(t,n){
i>n?t.classList.add("is-active"):t.classList.remove("is-active")
}),e&&a&&e(d()))
}
function d(){
return i
}
var f=[];
return function(){
if(!t)throw Error("No element supplied.");
if(!n)throw Error("No max rating supplied.");
if(i||(i=0),0>i||i>n)throw Error("Current rating is out of bounds.");
for(var e=0;n>e;e++){
var r=document.createElement("li");
r.classList.add("c-rating__item"),r.setAttribute("data-index",e),i>e&&r.classList.add("is-active"),t.appendChild(r),f.push(r),a(r)
}
}(),{
setRating:c,getRating:d
}
}
window.rating=t}();
The error I am getting is: 'Uncaught TypeError: t.appendChild is not a function.
The code in the page:
echo 'Please rate the quality of this transcript:<br/>';
echo '<div style="height: 44px; padding: 5px;text-align: center;">';
echo '<span id="qualitystars" style="vertical-align: sub;"><li class="c-rating__item" data-index="0"></li><li class="c-rating__item" data-index="1"></li><li class="c-rating__item" data-index="2"></li><li class="c-rating__item" data-index="3"></li><li class="c-rating__item" data-index="4"></li> </span>';
echo '</div><input type="hidden" name="quality" id="quality">';
The original page didn't have the <li> hard coded, but for some reason I have to put those in or they don't show. Maybe that's somehow related to the error I'm getting?
What should appear is 5 outlines of stars and when a user hovers their mouse above a star, that star and those leading up to it from the left should be solid. The user can then click on a star to submit the rating. Right now I see the outlines, but when I hover, only the star that I'm hovering over is solid.
Thanks in advance for any help.
EDIT: Here is where I call the rating:
let q_curr = 1;
let q_el = $('qualitystars');
let q_cb_rating = function (rating) {
$('quality').value = rating;
};
let q_rating = rating(q_el, q_curr, 5, q_cb_rating);
It is calling the JavaScript file, which is rating.min.js.
It turns out that the first page uses MooTools and the second page uses jQuery, which don't work together. I am rewriting the function for the second page using jQuery.
Thank you to everyone who responded.
I am using this codepen https://codepen.io/ravitadi/pen/CsIFL and I would like to add another field for the user to input a title for the note.
I am a javascript noobie and I can't seem to get it right. This is the function for adding notes. The full script is in the codepen.
function addNote(){
var usrInput = $('.txtBox').val();
//console.log(usrInput);
if(usrInput.length > 0){
console.log($(this));
$('#').removeClass('ntActv');
addtoSticky(usrInput);
cnclOvrly();
//console.log(notes);
}else{
}
}
function addtoSticky(note){
if(note.length > 0){
console.log(note);
createSticky(note);
localStorage.setItem('note_'+note.length, note);
}
}
function createSticky(text){
$('#stkyNts').append('<li class="box">'+text+'</li>');
}
Any help is highly appreciated.
Codepen
I tried to update following your requirement.
You should change way to save object and load object from localstorage.
storedNotes = JSON.parse(localStorage.getItem("notes"));
if(current == null) current = [];
current.push(JSON.stringify(note));
localStorage.setItem('notes', JSON.stringify(current));
https://codepen.io/viethien/pen/RdqKxM
In the modal, add another text box for title before the textarea.
<!-- add this -->
<input type="text" id="title" />
<!-- /add this -->
<textarea class="txtBox"></textarea>
Now you have to grab the value from the title. In the createSticky() function:
function createSticky(text) {
var heading = $("#title").val();
$('#stkyNts').append('<li class="box"><h3>' + heading + '</h3>'+text+'</li>');
}
And there you go:
For the extended functionality, try to change the way, heading is included in the local storage while setting and getting it. For doing so, you need to include the heading in the functions addtoSticky() and getStoredNotes().
//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>
Okay, so here's my problem, there's a webpage on our intranet that I must login to in order to gain access through one of our firewalls. I require this access the entire time I'm working but it automatically logs off every 60 minutes so I have to stop what I'm doing, go back to the page, enter my username & password & log in again. This repeats itself for about 9 hours or until I get off work.
I've been working on a VBScript that I could schedule to run every 60 minutes for me. Currently I'm able to do this via this basic script...
Const strID = "username"
Const strPswd = "password"
Set oShell = CreateObject("WScript.Shell")
oShell.Run("""https://00.0.00.00:0000/php/uid.phpvsys=1&url=http://www.yyy.net%2f""")
WScript.Sleep 3000
oShell.SendKeys strID
oShell.SendKeys "{TAB}"
wScript.Sleep 1000
oShell.SendKeys strPswd
WScript.Sleep 1000
OShell.SendKeys "{TAB}"
OShell.SendKeys "{ENTER}"
WScript.Sleep 1500
Set IE = CreateObject("Shell.Application")
Set windows = IE.Windows()
For Each window In IE.windows
If left(window.LocationUrl, 5) <> "file:" Then
If InStr(window.locationUrl, "http://www.yyy.net/") Then window.Quit()
If UCase(window.locationUrl) = UCase("about:tabs") Then window.Quit()
End If
Next
The above script works of course & I'm currently using it; however, the problem is, if/when the script runs before you're logged out then you receive an error from the script & obviously it won't run again for another hour. This inspired me to dive deeper into scripting. I began searching around for similar topics/methods, examining others codes, etc. just to get some ideas. My first attempt was to accomplish the same thing as the above script except completely hidden & without the use of 'SendKeys'. My goal was to put together a script like this...
Navigate to the page & then check the "heading" string...if it's = 'xxxx' then you're logged out so set the values for the username & password elements & submit them...otherwise, if it's = 'yyyy' then you're still logged in so Sleep for 10sec., reload & check again. I was almost certain this would work but with this script, no matter WHAT I looked for with document.getElementById("zzz"), I ALWAYS get the "null" error. It's as if no elements even exist & I've used every single Name= & ID= I can find in the source. (If interested, I can post this script as well but I ended up moving on to a completely different approach)
After the above issues I started reading about XMLHttp & sending the data this way instead. Using Fiddler I logged into the webpage like normal & was able to find the string with the username+password which get's sent to the server & tried writing a script to accomplish it. This is what I now have...
Call Main
Function Main ()
User = "myusername"
Pass = "mypassword"
'This is the string Fiddler revealed is being sent to server at login...
'"inputStr=&escapeUser=user&user=user&passwd=passwd&ok=Login"
'So I create this string with my information instead of elements values...
Credentials = ("inputStr=&escapeUser=" & User & "&user=" & User & "&passwd=" & Pass & "&ok=Login")
Set objXML = CreateObject("Msxml2.XMLHttp.6.0")
objXML.Open "POST", "https://00.0.00.00:0000/php/uid.php?vsys=1&url=http://www.yyy.net%2f", False
objXML.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXML.Send Credentials
End Function
Using the above method, it shouldn't matter if I was or wasn't logged in, the data would still be sent & no errors would be raised. But this script does nothing, it runs, I don't get any errors, I'm still not logged in & Fiddler doesn't even show any requests having been sent or received after I run it. However, if I enter the appropriate information into Fiddler & then execute it, boom, I'm logged in. This is the information I entered & executed & successfully logs me in via Fiddlers Composer under the Parsed tab...
With "POST" selected / The login pages URL / "HTTP/1.1" selected...
Referer: https://00.0.00.00:0000/php/uid.php?vsys=1&url=http://www.yyy.net%2f
Content-Type: application/x-www-form-urlencoded
Host: 00.0.00.00:0000
Content-Length: 68
Then in the "Requested Body" section I input...
inputStr=&escapeUser=myusername&user=myusername&passwd=mypassword&ok=Login
When I hit execute, you can see the request go through & the response come back & when I check on my end I'm logged in.
Hopefully I'm missing something simple that one of you guru's can easily point out or maybe someone has a better approach, I'm open to all ideas & suggestions because after 2 full days, I've gotten no where.
BTW, in case someone is just curious, or it's needed, or whatever, the relevant portion of the source from the login pages is below...
<body onload="loadPage();">
<table id="formtable">
<tr><td>
<div id="activearea">
<div id="logo"><img src="http://xxxxx.xxxx.net/xxx.png" data alt="Logo" width="100"/></div>
<div id="heading">Firewall Access</div>
<div id="desc">Please enter your credentials.</div>
<div id="formdiv">
<script>
function loadPage() {
if (document.login.user.value == '')
document.login.user.focus();
var errMsg = "";
var respStatus = "Success";
var respMsg = "";
if (respStatus == "Error") {
if (errMsg != "")
errMsg += "<br><br>";
errMsg += "<li>"+respMsg;
} else if (respStatus == "Challenge") {
var divUserName = document.getElementById("dUserName");
divUserName.style.display = "none";
var passwdTitle = document.getElementById("passwdTitle");
passwdTitle.innerHTML = "";
var divInputStr = document.getElementById("dInputStr");
divInputStr.style.display = "block";
divInputStr.innerHTML = respMsg;
}
if (errMsg != "") {
var divObj = document.getElementById("dError");
divObj.style.display = "block";
divObj.innerHTML = errMsg;
}
}
function submitClicked() {
var thisForm = document.getElementById("login_form");
// hide the error div, just incase it was showing.
var divObj = document.getElementById("dError");
divObj.style.display = "none";
divObj.innerHTML = "";
var divTaLogin = document.getElementById("taLogin");
divTaLogin.style.display = "none";
thisForm.inputStr.value = "";
thisForm.escapeUser.value = thisForm.user.value.replace(/\\/g, "\\\\");
}
function onClickHandler() {
submitClicked();
}
</script>
<form name="login" id="login_form" method="post">
<input type='hidden' name="inputStr" value="">
<input type='hidden' name="escapeUser" value="">
<div id="taLogin">
<table>
<tr id="dUserName">
<td><span id="userTitle">User</span></td>
<td><input type="text" id="user" name="user" size="19"></td>
</tr>
<tr>
<td><span id="passwdTitle">Password</span></td>
<td>
<div id="dInputStr" style="display:none"><br></div>
<input type="password" maxlength="40" size="19" name="passwd">
</td>
</tr>
<tr>
<td> </td>
<td><input class="buttonFixed" type="submit" id="submit"
name="ok" value="Login" onClick="submitClicked()"></td>
</tr>
</table>
</div>
</form>
<div id="dError" class="msg" style="display:none"></div>
</div>
</div>
</td></tr>
</table>
</body>
</html>
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;
}
}