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

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;
}
}

Related

problem with showing values of my array with document.write (using HTML 5 QR Code Scanner)

I am trying to work with HTML 5 QR Code scanner foran attendance system.
Well I got that far, that I can scan QR Codes and push them into an array.
I can see the values of the array in the console.
Now I want that this array is shown below the QR Code Reader in my browser view.
I then want a form to submit my javascript array values to a PHP Code to use it with mysql
(Don`t know how to do that right know... :) )
My first problem: my html page is not showing anything.. it is supposed to show the values of my Code array:
<script>
var codeslz = [];
function onScanSuccess(decodedText, decodedResult) {
// handle the scanned code as you like, for example:
//console.log(`Code matched = ${decodedText}`, decodedResult);
if(codeslz.indexOf(decodedText) !== -1){
} else{
codeslz.push (decodedText);
}
console.log (codeslz);
return codeslz;
}
function onScanFailure(error) {
// handle scan failure, usually better to ignore and keep scanning.
// for example:
//console.warn(`Code scan error = ${error}`);
}
let html5QrcodeScanner = new Html5QrcodeScanner(
"reader",
{ fps: 10, qrbox: {width: 350, height: 350} },
/* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess, onScanFailure);
for(var i = 0; i < codeslz.length; i++){
document.write(codeslz[i] + "<br>");
}
</script>
Later I want to automatically let the shwoing of my array be reloaded, so the user can always see the actual values of the complete array codeslz.
I think there must be sth wrong with my array codeslz.
When I fill the array like this, it works without any problems:
<html>
<head>
</head>
<body>
<script>
var codeslz = ["This", "is","a", "Test"];
for(var i = 0; i < codeslz.length; i++){
document.write(codeslz[i] + "<br>");
}
</script>
</body>
</html>
I hope someone can help me. Thanks!!!!
Kind regards
Dan

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

Jquery adding items to a list without reloading page

I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.
Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/
Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);
Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/
It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/

Unable to retrieve values from eBay API response using Javascript

I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.

Javascript no jquery - How do I add this function to existing javascript that is triggered by onload / onpaste?

This is an add-on to my previously answered question.
question 8423472
I have tried to implement a validate function to this wonderful code to no avail.
Looks like I need more hand holding here.
This script is a slightly modified version of the quite excellent answer I received from #Martin Jespersen.
The script takes a single column list of emails and breaks it up into textareas containing single row comma delimited lists of no more than 150 addresses. Nice.
Below works great but, I need to add a basic validation function.
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
document.getElementById('t').onpaste = onpaste;
}
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
HOWEVER, the guy I made it for (actually #Martin made it) is not real meticulous about what he pastes into the textarea.
So, I am trying to implement a function that will reduce invalid emails / bad input.
I tried several ways including changing the onload event to a button in the page with onclick event.
I thought I was learning here but, I just can't wrap my brain around what I am doing wrong.
So, how can I insert this function, or just its' "validation" routine into one of the above functions?
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
Useage of findEmailAddresses function:
<textarea name=t rows=10 cols=50 onBlur="this.form.email.value=findEmailAddresses(this.value);"></textarea>
I tried calling the function individually in the functions above and even tried removing the function just inserting the code using "emails" instead of "this.value" in both cases. I even tried a two page approach. For some reason, I just can't implement this code into the working splitter. My results are either no effect or I break the thing.
Basically I tried many variations of inserting. Like below:
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
//
findEmailAddresses(emails);
// also tried inserting code from function. ///
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
// tried to trigger it here as well and even added a new split //
document.getElementById('t').onpaste = onpaste;
}
/////
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
////////
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
Much thanks to anyone who can assist.
Try putting return true; after your inline javascript.

Categories