Credit Card Swipe in Javascript not working - javascript

I am using Javascript to get the credit card information from Magentic Strip Reader device. (I am using USB attached device)
I have written a code in HTML Javascript but it failed to run. I mean my page is on HTTPS when I connected the device after opening this page. The device lights turns to green which means this page is security proof.
But when I swipe the card it did not show nothing in the field. I also have a function to focus on the field. But I don't know whats wrong it, Please see my code below and give me any suggestions.
HTML:
<span style='required'>*</span> - Indicates required field.
<div class='fields'>Swiped Information</div>
<input type=text name='swiped' id='swiped'>
<div class='fields'>First Name</div>
<input type=text name='first_name' id='first_name'><span style='required'>*</span>
</div>
<div class='fields'>Last Name</div>
<input type=text name='last_name' id='last_name'><span style='required'>*</span>
</div>
<div class='fields'>Expiration</div>
<input type=text size=8 name='expiration' id='expiration'><span style='required'>*</span>(MMYY)
</div>
<div class='fields'>CVV Code</div>
<input type=text size=8 name='cvv' id='cvv'><span style='required'>*</span>
</div>
<div class='fields'>Credit Card Number</div>
<input type=text name='card' id='card'><span style='required'>*</span>
</div>
<hr>
<div class='buttons'></div>
<a onclick="readCard();" style="cursor:pointer; color:red;">Swipe Credit Card</a>
</div>
Javascript code:
<script type="text/javascript">
function readCard () {
document.getElementById('swiped').focus();
var card_data = document.getElementById('swiped').value;
if(card_data != ''){
var details1 = card_data.split("^");
var card_number = details1[0];
card_number = card_number.substring(2);
var names = details1[1].split("/");
var first_name = names[1];
var last_name = names[0];
var details2 = details1[2].split(";");
details2 = details2[1].split("=");
var exp_date = details2[1];
exp_date = exp_date.substring(0, exp_date.length - 1);
exp_date = exp_date.substring(2, 3) + "/" + exp_date.substring(0,2);
document.getElementById('card').value = card_number;
document.getElementById('first_name').value = first_name;
document.getElementById('last_name').value = last_name;
document.getElementById('expiration').value = exp_date;
}
}
</script>

If the swiper model is IDMB, then it is not encrypted but may be set to HID and not KBE (keyboard emulated). Are you able to swipe into a text editor, notepad? If not, you may be able to switch it from HID to KBE with MagTek's demo application.
http://www.magtek.com/support/software/demo_programs/usb_swipe_insert.asp

Related

How to make a dropdown autocomplete navigable by keyboard

Here, I have a nice autocomplete dropdown that, given a city typed by the user, the page will show all possible city-state-country triplets. For example the name Guadalajara would suggest
Guadalajara de Buga, Valle del Cauca Department, Colombia
Guadalajara, Castilla La Mancha, Spain
and
Guadalajara, Jalisco, Mexico
The code works perfectly from both the backend and the frontend, the only problem left is that the autosuggest drop down menu will only work with the mouse and not with the keyboard. The Up and Down arrow keys will not allow to navigate through the most appropriate choice and pressing esc doesn't cancel the menu.
I tried everything and I have no idea about what is missing to make this work with the keyboard as well. I would like to find a solution with pure vanilla JavaScript and that would involve the least possible changes in the rest of working code. Here the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vanilla Javascript Cities Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.2/css/bulma.min.css">
</head>
<body id="body">
<div class="title has-text-centered" id="main"></div>
<section id="form" class="section" onclick="clearCities()">
<div class="container">
<h1 class="title">Vanilla Cities Javascript</h1>
<!-- Row for City, State and Country -->
<div id="location">
<div class="field">
<div class="control">
<div id="cities-dropdown" class="dropdown">
<div class="dropdown-trigger">
<input name="cities" id="cities" onkeyup="getCities()" maxlength="50" class="input" type="text" placeholder="Enter a city" aria-haspopup="true" aria-controls="dropdown-menu3" -autocomplete="off" required
>
</div>
<div class="dropdown-menu" id="dropdown-menu3" role="menu">
<div id="cities-dropdown-content" class="dropdown-content">
<!-- content -->
<a class="dropdown-item"></a>
</div>
</div>
</div> Clear
</div>
<span class="is-size-7 has-text-info">(If your location doesn't appear immediately, try to type slower).</span>
</div>
<!-- City Field -->
<div class="field">
<div class="control">
<input name="city" id="city" class="input" type="text" placeholder="City" required>
</div>
</div>
<!-- State Field -->
<div class="field">
<div class="control">
<input name="state" id="state" class="input" type="text" placeholder="State" required>
</div>
</div>
<!-- Country Field -->
<div class="field">
<div class="control">
<input name="country" id="country" class="input" type="text" placeholder="Country" required>
</div>
</div>
</div>
</div>
</section>
</body>
<script>
function getCities(){
var inputCity = document.getElementById('cities').value;
const city = changeCase(inputCity);
if(city.length <= 2){
return false;
}
// Create request to get cities locations
var request = new XMLHttpRequest();
request.addEventListener("load", transferComplete);
request.open("GET", "/cities/?cityname=" + city);
request.send();
// Called when transfer is complete
function transferComplete(event){
//alert(event.srcElement.response);
locations = JSON.parse(event.srcElement.response);
// Return false if no matching city was found
if(locations.length == 0){
return false;
}
// Append choices
dropContent = document.getElementById('cities-dropdown-content');
dropContent.innerHTML = "";
for (var i = 0; i < locations.length; i++) {
var link = document.createElement("a");
link.setAttribute("onclick", "setCity(" + JSON.stringify(locations[i].name) + "," + JSON.stringify(locations[i].state) + "," + JSON.stringify(locations[i].country) + ")");
link.setAttribute("class", "dropdown-item");
link.innerHTML = locations[i].name + ", " + locations[i].state.name + ", " + locations[i].country.name
dropContent.append(link);
}
document.getElementById("cities-dropdown").classList.add("is-active");
}
// document.getElementById("products-list").innerHTML = html;
}
function setCity(city, state, country){
document.getElementById('cities').value = city+', '+state.name+', '+country.name;
document.getElementById('city').value = city;
document.getElementById('state').value = state.name;
document.getElementById('country').value = country.name;
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function clearCities(){
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function deleteEntry(e){
e.preventDefault();
document.getElementById('cities').value = '';
}
function changeCase(inputCity){
return inputCity
.replace(/([a-z])([A-Z])/g, function (allMatches, firstMatch, secondMatch) {
return firstMatch + " " + secondMatch;
})
.toLowerCase()
.replace(/([ -_]|^)(.)/g, function (allMatches, firstMatch, secondMatch) {
return (firstMatch ? " " : "") + secondMatch.toUpperCase();
}
);
}
var eraser = document.getElementById("clear");
eraser.addEventListener('click', deleteEntry);
</script>
I hope to find the simpler and least invasive solution to complete a code that just have this left.
I would change your dropdown and input to the semantic html datalist element:
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Then both search and keyboard accessibility should work more or less out of the box.
If you really don't want to do that, you have to attach event listeners (vanilla js) to the different elements of your dropdown and input field and write a rather long thing to be able to tab or arrow key your way down and up and back into the search field. I would say it's too much work compared to the reward.
Better to use some time to css-animate the datalist so it behaves a bit smoother and style it neatly.

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

Is there a way to edit a javascript function to live update in a html form output?

I've written a working absence calculator using a HTML form and a javascript function. Unfortunately I need this to update to the output in real time and I cannot figure out how to do it without firing the function multiple times.
HTML
<form id="absence-form">
<div class="input">
<div id="title">Absence Calculator</div>
<div id="firstCell">
<div id="instruct">
Enter number of employees:
</div>
<input id="employees" type="text" name="employees">
<div id="secondCell">
<div id="instruct">
Enter average salary:
</div>
</div>
<input id="salary" type="text" name="salary">
<div id="thirdCell">
<div id="instruct">
Enter absence %:
</div>
</div>
<input id="absence" type="text" name="absence">
</div>
<div id="instruct">
<div id="output">Total salary (£):
<div id="totalSalary">
</div></div>
<div id="output">Monthly absence cost (£):
<span id="monthlyAbsence">
</span></div>
<div id="output">Annual absence cost (£):
<span id="absenceCost">
</span></div>
</div>
</div>
</form>
Javascript Function
function multiply() {
var employees = document.getElementById('employees').value;
var salary = document.getElementById('salary').value;
var totalSalary = parseInt(employees) * parseInt(salary);
var result1 = document.getElementById('totalSalary');
result1.innerHTML += totalSalary;
var absence = document.getElementById('absence').value;
var absenceCost = parseInt(totalSalary) / 100 * parseInt(absence);
var result2 = document.getElementById('absenceCost');
result2.innerHTML += absenceCost;
var monthlyAbsence = parseInt(absenceCost) / 12;
var result3 = document.getElementById('monthlyAbsence');
result3.innerHTML += monthlyAbsence;
}
});
Any pointers would be greatly appreciated.
You'll need to bind your function to the change event for the input elements.
This can be done a couple of ways:
Obtrusively (not recommended) with the element's onChange attribute (JSFiddle)
Non-obtrusively (preferred) with .on('change', function() {} }) (JSFiddle)
I'm assuming from the tag that you're using jQuery but you can achieve the same thing with vanilla JS using .addEventListener('change', callback, false) (JSFiddle)

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

Save and retrieve user input from database with javascript?

I'm working on a small, temporary site that will be used for collecting some names.
The idea is that people fill in the number of their class and their name and once they press a button, these two values are added to the page and can be viewed by everyone who visits the site.
I've already made a concept of this using javascript: www.googledrive.com/host/0B_eZKT0Ni3-tOXF5OVVQeWZRRjQ
The only problem is that the items aren't really stored on the site. As far as I know, you can only accomplish this using a database, but I have no experience with linking a database to a webpage.
Can someone help me with this or does someone know a source where I can find a solution for this? My searches turned up nothing.
I'm sorry if I'm sounding like a "help vampire". I only turned to you guys for a solution because I can't find it anywhere else.
HTML:
<body>
<div id="wrapper">
<div id="header">
<h2 id="title">Italiëreis 2015: opdiening tijdens quiz</h2>
</div>
<div id="content">
<!-- eerste ploeg -->
<div class="L">
<p id="kop">Ploeg 1</p>
<p class="klas"><input type="text" id="klas1" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam1" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText1()" value="Schrijf in" class="button" />
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst1"></ol>
</div>
</div>
<!-- tweede ploeg -->
<div class="L">
<p id="kop">Ploeg 2</p>
<p class="klas"><input type="text" id="klas2" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam2" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText2()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst2"></ol>
</div>
</div>
<!-- derde ploeg -->
<div class="L">
<p id="kop">Ploeg 3</p>
<p class="klas"><input type="text" id="klas3" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam3" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText3()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst3"></ol>
</div>
</div>
<!-- vierde ploeg -->
<div class="L">
<p id="kop">Ploeg 4</p>
<p class="klas"><input type="text" id="klas4" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam4" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText4()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst4"></ol>
</div>
</div>
</div>
<div id="footer">
<div id="credits">Code geschreven door Bert-Jan van Dronkelaar - 6E</div>
</div>
</div>
CSS is irrelevant.
Javascript:
//eerste ploeg
function changeText1() {
var klas1 = document.getElementById('klas1').value;
var naam1 = document.getElementById('naam1').value;
if (document.getElementById('klas1').value != "" && document.getElementById('naam1').value != "") {
var node = document.createElement("LI");
var textnode1 = document.createTextNode(klas1 + " " + naam1);
node.appendChild(textnode1);
document.getElementById("lijst1").appendChild(node);
}
}
//tweede ploeg
function changeText2() {
var klas2 = document.getElementById('klas2').value;
var naam2 = document.getElementById('naam2').value;
if (document.getElementById('klas2').value != "" && document.getElementById('naam2').value != "") {
var node = document.createElement("LI");
var textnode2 = document.createTextNode(klas2 + " " + naam2);
node.appendChild(textnode2);
document.getElementById("lijst2").appendChild(node);
}
}
//derde ploeg
function changeText3() {
var klas3 = document.getElementById('klas3').value;
var naam3 = document.getElementById('naam3').value;
if (document.getElementById('klas3').value != "" && document.getElementById('naam3').value != "") {
var node = document.createElement("LI");
var textnode3 = document.createTextNode(klas3 + " " + naam3);
node.appendChild(textnode3);
document.getElementById("lijst3").appendChild(node);
}
}
//vierde ploeg
function changeText4() {
var klas4 = document.getElementById('klas4').value;
var naam4 = document.getElementById('naam4').value;
if (document.getElementById('klas4').value != "" && document.getElementById('naam4').value != "") {
var node = document.createElement("LI");
var textnode4 = document.createTextNode(klas4 + " " + naam4);
node.appendChild(textnode4);
document.getElementById("lijst4").appendChild(node);
}
}
#SpencerWieczorek is not wrong, PHP and MySql will work for what you need. However, there is a bit of a learning curve there.
For a beginner, I'd recommend using Parse. It's free and it makes saving and retrieving data trivial. Below is simple app that lets the user input a class year and their name and saves them so others can see them on the same page.
The snippet here wont work due to SO restrictions...
...but here is a working jsfiddle
This is accomplished with plain ole javascript BTW
To get this going on your own you'll need to:
You'll need to go to https://www.parse.com/#signup and create an account with them
Go to https://www.parse.com/apps/new and create an app
add this in your html's head tag <script type="text/javascript" src="https://www.parsecdn.com/js/parse-1.3.0.min.js"></script>
Go to https://www.parse.com/apps/quickstart#parse_data/web/new, select your app from the dropdow (top-ish right) the Parse.initialize() function will be shown here with your app's Application ID and JavaScript key, copy this line for later
Replace the Parse.initialize() function in my example with the one you copied in step 4
Read up on the their javascript guide here to see what all you can do with parse
for a more indepth look, check out the Parse JavaScript SDK & Cloud Code Reference
You can also interact with parse with other scripting languages if you'd like.
Parse is free up to a certain amount of usage. I have one app that's used daily by 100+ users and doesn't come anywhere near having to pay anything.
Parse.initialize("Application ID", "JavaScript key");
function saveInput(){
//get our new values
var klassYear = document.getElementById('klassYear').value.trim();
var studentName = document.getElementById('studentName').value.trim();
// dont continue if either value is blank
if(klassYear=="" ||studentName=="" ){
alert ('Please fill in both fields.') ;
return;
}
// create the `Parse` object
var Klass = Parse.Object.extend("Klass");
var _klass = new Klass();
// set the object's values to our input values
_klass.set("klassYear", klassYear);
_klass.set("studentName", studentName);
// save the object
_klass.save(null, {
success: function(_klass) {
// if the save succeeded, add the new info to our page
retrieveSavedInputs()
},
error: function(_klass, error) {
// save failed, do error handeling here
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
function retrieveSavedInputs(){
// create a query to search for our `Klass` items
var Klass = Parse.Object.extend("Klass");
var query = new Parse.Query(Klass);
query.find({
success: function(results) {
// get our table's `tbody` and clear it
var myTbl = document.getElementById('mytbl');
myTbl.innerHTML='';
// `results` is an array of all the matches
// loop through each
for(var i =0; i < results.length; i++){
// get the values from the saved object
// note that `klassYear` and `studentName`
// are not available within the scope of the `success` function
var k = results[i].get("klassYear")
var s = results[i].get("studentName")
// create a table row with the info and add it at the top of `contents`
myTbl.innerHTML = '<tr><td>'+k+'</td><td>'+s+'</td></tr>' + myTbl.innerHTML;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
// load all previously saved items
window.onload = retrieveSavedInputs();
//clcik handeler for the btn
document.getElementById("myBtn").addEventListener('click', saveInput , false);
table{
margin-top:50px;
}
Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table> Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table>

Categories