Using inputs in HTML to run functions - javascript

so I am working on a stock market simulator using HTML and JS. I have a api here that gets current stock prices. Here is my HTML http://pastebin.com/ymcGKtin Sorry about pastebin not very good at formatting for SO. But in the function add stock I am trying to push the submitted form stockto the array stocks. However I have run into a problem trying to figure out how to get the submitted form stock and push it to the array. If I could get some pointers on how to do this it would be appricated. To be specific I would like help on getting the attribute stock pushed to the array Stocks. Ideas?
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback){
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult){
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult){
console.error(jsonResult);
}
Market.makeRequest = function () {
//Abort any open requests
if (this.xhr) { this.xhr.abort(); }
//Start a new request
this.xhr = $.ajax({
data: { symbol: this.symbol },
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock(){
alert("derp");
// Stocks.push(ele.getAttribute)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit = "addStock()">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
</body>
</html>

With JQuery you could use find on the form-object (this in the onsubmit-handler):
...
function addStock(form){
var value = $(form).find('input[name="stock"]').val();
alert(value);
Stocks.push(value);
//prevents a submit of the form
return false;
}
</SCRIPT>
<form onsubmit = "return addStock(this);">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
...

Changed the addStock() function to use the form element collection method.
function addStock(){
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: "+xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback) {
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult) {
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult) {
console.error(jsonResult);
}
Market.makeRequest = function() {
//Abort any open requests
if (this.xhr) {
this.xhr.abort();
}
//Start a new request
this.xhr = $.ajax({
data: {
symbol: this.symbol
},
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock() {
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: " + xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit="addStock()">
<input type="text" name="stock" value="">
<br>
<br>
<input type="submit" value="Get Price">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
</body>
</html>

Related

Parse file only one time using papaParse

I want to create a web app to make simple actions on a csv. For example, the user would upload a csv file then all columns would show up on a form, the user could select some columns to remove them from the file and finally the user could download the modified file.
I have already done something working but there is definitely room for improvement. The most important one is that in my current solution I have to parse the file two times because Papaparse is asynchronous, one time to get the columns and another time to remove columns from the user input.
Is there a way to parse the file only one time and then use the resulting object through the rest of the code ?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSV Manipulator</title>
<link rel="stylesheet" href="style.css" />
</head>
<script src="script.js"></script>
<script src="papaparse/papaparse.min.js"></script>
<body>
<div id="csv_columns">
<label for="file">choose csv file</label>
<input id="input-file" autocomplete="off" type="file" id="file" name="file">
<input type="button" value="download CSV" onclick="downloadCSV()">
</div>
<div id="schema_select">
<form action="#">
<label for="schema">Schema</label>
<select name="schema" id="schema" multiple>
</select>
<button id="submit-option">Submit</button>
</form>
<input type="text" , autocomplete="off" name="csv-file-name" id="csv-file-name">
</div>
</body>
</html>
window.onload = function () {
inputElement = document.getElementById("input-file")
inputElement.onchange = function (event) {
var fileList = inputElement.files;
parseDatatoGetSchema(fileList[0])
}
var newCsvFileName = document.getElementById("csv-file-name").value
var submitOption = document.getElementById("submit-option");
submitOption.addEventListener("click", function (event) {
var columnsToRemove = handleSubmit(event)
console.log(columnsToRemove)
parseDataRemoveColumns(inputElement.files[0], columnsToRemove, newCsvFileName)
});
}
function removeColumns(parsedCsv, columnsToRemove) {
newParsedCsv = []
for (i = 0; i < parsedCsv.data.length; i++) {
newObj = {}
for (key in parsedCsv.data[i]) {
if (!(columnsToRemove.includes(key))) {
newObj[key] = parsedCsv.data[i][key]
}
}
newParsedCsv.push(newObj)
}
return newParsedCsv
}
function showCsvSchema(results) {
//Data is usable here
var schemaForm = document.getElementById("schema")
// ajoute le nœud texte au nouveau div créé
for (i = 0; i < Object.keys(results.data[0]).length; i++) {
var opt = document.createElement('option');
opt.value = Object.keys(results.data[0])[i];
opt.innerHTML = Object.keys(results.data[0])[i];
schemaForm.appendChild(opt);
}
}
function handleSubmit(event) {
event.preventDefault();
var schemaSelect = document.getElementById("schema")
columnsToRemove = [...schemaSelect.selectedOptions].map(o => o.value)
return columnsToRemove
}
function parseDatatoGetSchema(url) {
csvData = []
Papa.parse(url, {
header: true,
dynamicTyping: true,
complete: function (results) {
showCsvSchema(results)
}
});
}
function parseDataRemoveColumns(url, columnsToRemove, newCsvFileName) {
csvData = []
Papa.parse(url, {
header: true,
dynamicTyping: true,
complete: function (results) {
newParsedCsv = removeColumns(results, columnsToRemove)
unParsedNewCsv = Papa.unparse(newParsedCsv)
downloadCSV(unParsedNewCsv, newCsvFileName)
}
});
}
function downloadCSV(unparse_csv, newCsvFileName) {
var csvData = new Blob([unparse_csv], { type: 'text/csv;charset=utf-8;' });
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, `${newCsvFileName}.csv`);
}
else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', `${newCsvFileName}.csv`);
tempLink.click();
location.reload()
}

my code at first is correct but with this error spread.js.25 I can not see result in the browser

When I inspect the code in the browser this error appears spread.js.25 and I can not find this problem.
I checked the exercise solution, it's the same as my solution ... I don't know much about axios ...
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercício 02</title>
</head>
<body>
<input type="text" name="user">
<button onclick="listRepositories()">Adicionar</button>
<ul></ul>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var listElement = document.querySelector('ul');
var inputElement = document.querySelector('input');
function renderRepositories(repositories) {
for (repo of repositories) {
const textElement = document.createTextNode(repo.name);
const liElement = document.createElement('li');
liElement.appendChild(textElement);
listElement.appendChild(liElement);
}
}
function listRepositories() {
var user = inputElement.value;
if (!user) return;
axios.get('https://api.github.com/users/' + user + '/repos')
.then(function (response) {
renderRepositories(response.data);
})
}
</script>
</body>
</html>
this image is exactly the problem

jQuery to do list done button not removing item

I am creating a simple to do list using jQuery and local storage. I am also trying to add a button for each li I add to clear the item from the list. My list does not stick upon refresh and I can't figure out how to load the button, does the button need to happen on the HTML side?
The adding to the list functions work great its just the storage to local storage that I seem to be missing something.
I created a jsfiddle for this code and the local storage seems to work fine but it will not work on my xampp. Also I can get the done button to appear but it won't removeItem.
https://jsfiddle.net/blen6035/287pc153/7/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task List</title>
<link rel="stylesheet" href="main.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="tasks.js"></script>
</head>
<body>
<aside>
<h2>Add a task</h2>
<label for="task">Task:</label>
<input type="text" id="task" name="task"><br>
<label> </label>
<input type="button" id="add" name="add" value="Add Task">
</aside>
<main>
<h1>Task list</h1>
<ul id="listOfTasks"></ul>
</main>
<footer></footer>
</body>
</html>
"use strict"
$(document).ready(function() {
let listOfTasks = JSON.parse( localStorage.getItem("tasks"));
if( listOfTasks == undefined ){
listOfTasks = [];
}
for( let i = 0; i < listOfTasks.length; i++){
let li = $('<li> Done
</li>').text(listOfTasks[i]);
$('#listOfTasks').append(li);
}
$('#add').click(function(){
let task = $('#task').val();
listOfTasks.push(task);
localStorage.setItem("tasks", JSON.stringify(listOfTasks)
);
let li = $('<li></li>').text(task);
$('#listOfTasks').append('<li>'+ task +'<input type="submit"
class="done" value= "Done">' + '</li>');
$('#task').val(' ').focus();
});
$('.done').on('click', '.delete',function(){
$(this).parent().remove();
});
/*$('#done').click(function(){
localStorage.removeItem;
$('#listOfTasks').html('');
});*/
}); // end ready
Is this what you are trying to do ?
Note that I had to polyfill local storage to make this work in a snippet, replace fakeLocalStorage by localStorage
const listOfTasksElement = $('#listOfTasks')
const taskInputElement = $('#task')
const listOfTasks = JSON.parse(fakeLocalStorage.getItem('tasks')) || []
const updateTasks = () => fakeLocalStorage.setItem('tasks', JSON.stringify(listOfTasks))
const addTask = task => {
const taskElement = $('<li></li>').text(task)
const doneElement = $('<span>Done</span>').click(() => {
const index = listOfTasksElement.find('li').index(taskElement)
taskElement.remove()
listOfTasks.splice(index, 1)
updateTasks()
})
taskElement.append(doneElement)
listOfTasksElement.append(taskElement)
listOfTasks.push(task)
updateTasks()
}
listOfTasks.forEach(addTask)
$('#add').click(() => {
addTask(taskInputElement.val())
taskInputElement.val('').focus()
})
<ul id="listOfTasks"></ul>
<input id="task"><button id="add">Add</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// local storage doesn't work in stack overflow snippets,
// this is just a poor in-memory implementation
const fakeLocalStorage = {
_data: {},
setItem(k, v) { return this._data[k] = v },
getItem(k) { return this._data.hasOwnProperty(k) ? this._data[k] : null }
}
</script>

Retrieving the text input's value which was stored into localStorage

I am trying to parse JSON data from the url (only feeds data from the JSON) and stored the values in localstorage now I am trying to retrieve the values that are stored in the localstorage from one file to another file the stored values is in the from of array objects.while retrieving I am getting only the final object in other file. Can anyone help me how to retrieve all the objects? I am attaching the code below new.html (here I am trying to store the data in localstorage) and new1.html (here I am retrieving the data). Thank you
new.html:
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width ,height=device-height"/>
</head>
<body>
<div id="header">
<h1> Login </h1>
</div>
<div id="section">
<!--script type="text/javascript"
charset="utf-8" src="cordova-1.7.0.js"></script-->
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("#submit").click(insertId);
});
function insertId() {
// Getting the value of your text input
var did = document.getElementById("deviceId").value;
if (did == null || did == "") {
alert("Kindly enter a valid Device ID");
return false;
} else {
console.log("id: ", did);
}
window.alert("DID entered is : " + did);
window.open("new1.html");
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=10",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
}
});
return false;
}
</script>
<form id="insertId">
<br><input type="text" placeholder="DeviceId" id="deviceId" /><br>
<br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</div>
</body>
new1.html:
<html>
<body onload="init();">
<div id="header">
<h1> USER DETAILS </h1>
</div>
<div id="section">
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field3 = "+fd2);
}
</script>
<body onload="init();">
</body>
</div>
</body>

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources