HTML Form data into a Object to pass a method - javascript

I'm trying to make a basic cash register app. How do I pass the form data from this:
<form action="#" id="target">
<input type="text" required class="field1 col-md-3 col-md-offset-3" placeholder="Enter Item Name Here">
<input type="text" required class="field1 col-sm-2 " placeholder="Enter Item Quantity">
</div>
<div class="row">
<input type="text" class="field1 col-md-3 col-md-offset-3" placeholder="Enter Staff Name (Optional)">
<button type='submit' class="col-md-2 butn btn-one" id="check">Checkout</button>
</div>
into the methods listed below everytime something is submitted
cashRegister.scan('ITEM NAME', QUANTITY);
// Apply your staff discount
// applying a staff discount to the total amount
cashRegister.applyStaffDiscount(EMPLOYEE);
then print the results of the script from the console to the HTML page
console.log('Your bill is ' + cashRegister.total.toFixed(2));
I want to be able input a quantity of 5 for an item of apples, on my discount and have that form spit out this following JavaScript to execute this script http://codepen.io/illusionelements/pen/xGQrxN
(item: apple, quantity: 5, Employee:me)
cashRegister.scan('apple',5);
cashRegister.applyStaffDiscount(me);

It looks like the problem you're having is that you're trying to get the values of the form to the javascript. If that's the case then try something like this:
$('#check').on('click', function(e) {
e.preventDefault(); //Stops the form from being posted
var item = $('#item').val();
var quantity = $('#quantity').val();
var staff = $('#staff').val();
cashregister.scan(item, quantity);
if(staff.length > 0 && typeof staffMembers[staff] != 'undefined')
{
cashregister.applyStaffDiscount(staffMembers[staff]);
}
console.log('Your bill is ' + cashRegister.total.toFixed(2));
$('#target2').fadeIn(5000)
// .animate({opacity: 0.5}, 3000)
.fadeOut(5000);
});
A couple things you'd need to do to make this work:
give your inputs unique classes or ids
make an object of your staff members
var staffMembers = {};
var sally = new StaffMember("Sally", 5);
staffMembers['sally'] = sally;

Related

Putting values from Textboxes into an array

Good Day,
I have created a simple form with three boxes to capture text data. I also have a button that duplicates the form to facilitate multiple entries. I want to be able to take that data and place into 3 arrays, one for each text box.
The code is below:
$(document).ready(function()
{
$("#add").click(function()
{
addThis = "<div class='row mb-3'><div class='col-12'><input type='text' name='fname[]' id='fname' class='form-control' placeholder='First Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='mname[]' id='mname' class='form-control' placeholder='Middle Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='lname[]' id='lname' class='form-control' placeholder='Last Name'></div></div>";
$("#form1").append(addThis);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card" id="form2">
<div class="card-body">
<form action="" id="form1" class="card-body">
<div class="row mb-3">
<div class="col-12">
<input type="text" name="fname[]" id="fname" class="form-control" placeholder="First Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="mname[]" id="mname" class="form-control" placeholder="Middle Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="lname[]" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
</form>
<form action="">
<div class="d-grid gap-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add">Add Another</button>
<button type="button" name="test" class="btn btn-success">TEST</button>
</div>
</div>
</form>
</div>
I want to eventually submit the data into the table, looping through the arrays for each instance of the form.
Could some one point me in the right direction please?
Heres a possible solution using fieldsets to group your name inputs.
See comments in jQuery JS so you know whats happening...
// our form as const object
const form = $('#form');
// on form submit pass event
$(form).on('submit', function(e) {
// stop event default behaviour
e.preventDefault();
// set entry as serialized array
let entry_arr_obj = $(this).serializeArray();
// set empty object for formatted entry data
let formatted_entry_obj = {};
// for each entry array obj values as key => object
$.each(entry_arr_obj, function(k, obj) {
// split object field name by underscore to create name_fieldset array containing fieldset id and name key
let name_fieldset = obj.name.split('_');
// set the set id from name_fieldset array
let fieldset = parseInt(name_fieldset[1]);
// set name key from name_fieldset array
let name = name_fieldset[0];
// if formatted_entry_obj does not have own property matching current fieldset id
if(!formatted_entry_obj.hasOwnProperty(fieldset)) {
// add fieldset id and empty object to formatted_entry_obj
formatted_entry_obj[fieldset] = {};
}
// add field name and field value to formatted_entry_obj current fieldset object
formatted_entry_obj[fieldset][name] = obj.value;
});
// log our entry object
console.log(formatted_entry_obj);
});
// on form add field set
$(form).on('click', '.add', function(e) {
// get all our fieldsets
let fieldsets = $('fieldset',form);
// last fieldset obj and id
let last_fieldset = fieldsets[fieldsets.length-1];
let last_fieldset_id = parseInt($(last_fieldset).data('set'));
// create new fieldset id
let new_fieldset_id = last_fieldset_id + 1;
// clone last fieldset and filter attributes
$(last_fieldset).clone().filter(function() {
// update data set attribute with new fieldset id
$(this).attr(
'data-set',
new_fieldset_id
// now filter children elements (cols)
).children().filter(function() {
// now filter children elements (inputs)
$(this).children().filter(function() {
// get child element name attr
let name_attr = $(this).attr('name');
// if we have name attr
if(name_attr) {
// explode the name attr value via underscore
let name_fieldset = name_attr.split('_');
// return updated name attribute with new fieldset name and empty value
return $(this).attr(
'name',
name_fieldset[0] + '_' + new_fieldset_id
).val(null);
}
// else return child element
return $(this);
});
// return child element
return $(this);
});
// return all of cloned elem
return $(this);
// then insert after last field set
}).insertAfter(last_fieldset);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container py-3">
<form id="form">
<fieldset data-set="1" class="form-row mb-3">
<div class="col-sm-4">
<input type="text" name="fname_1" placeholder="First Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="mname_1" placeholder="Middle Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="lname_1" placeholder="Last Name" class="form-control form-control-sm" />
</div>
</fieldset>
<button type="button" class="add btn btn-sm btn-primary btn-block">Add Fieldset</button>
<button type="submit" class="btn btn-sm btn-success btn-block">Submit</button>
</form>
</div>

javascript function sets the value of a form input field, but then the value disappeared

I'm trying to do a live database search using ajax with a form input field.
The whole thing runs so far that i can select a text from the proposed list.
The corresponding event "livesearchSelect" is also addressed, the value of the input field is set. Unfortunately the set value is missing in the form.
I have no clue what is going on, someone can throw some hints at me pls ?
screenshot
html:
<form name="demoform" id="demoform" action="" method="post" >
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-4">
<input type="text" name="name" id="name" value="a value" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-4">
<input type="text" name="email" id="email" value="" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="search" class="col-sm-2 col-form-label">Live Search</label>
<div class="col-sm-4">
<input type="search" name="search" id="search" value="" class="form-control" oninput="livesearchResults(this, '/livesearch/Album');">
<ul class="list-group" id="search-results" style="display:none">
<li class="list-group-item">?</li>
</ul>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-4">
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-primary" />
</div>
</div>
</form>
javascript:
function livesearchResults(src, dest){
var results = document.getElementById(src.id + '-results');
var searchVal = src.value;
if(searchVal.length < 1){
results.style.display='none';
return;
}
var xhr = new XMLHttpRequest();
var url = dest + '/' + searchVal;
// open function
xhr.open('GET', url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var text = xhr.responseText;
results.style.display='inline';
results.innerHTML = text;
console.log('response from searchresults.php : ' + xhr.responseText);
}
}
xhr.send();
}
function livesearchSelect(src) {
var input_element = document.getElementById(src.parentElement.id.split("-")[0]);
input_element.defaultValue = src.text;
input_element.value = src.text;
}
php controller:
<?php
namespace controller;
use database\DBTable;
class livesearch extends BaseController {
public function index() {
echo "nothing here";
}
public function Album($input) {
$table = new DBTable('Album');
$results = $table->where('Title',$input.'%', 'like')->findColumnAll('Title', '', 6);
foreach ($results as $key => $value)
echo ''.$value.'';
}
}
Clicking an anchor element with an href attribute, even when blank, will load the linked page, which is what you see happening here.
One solution would be to prevent the default action for the link (by e.g. returning false in the handler or calling Event.preventDefault), but a better design would be to replace the <a> elements (which aren't actually links) with something more semantically appropriate. Given that the consumer expects a sequence of <li>, the simplest solution is to replace the <a> in the PHP controller with <li>. The result would still have a higher degree of coupling than is desirable; the HTML classes and click handler couple the results tightly to the specific search form, rather than representing the resource as its own thing.
Not that text is not a DOM-standard property of HTML elements; you should be using textContent or innerText instead.

Firebase Chat change reference with javascript

I am trying out how to incorporate firebase with angular in such a way that the user is able to change the "Channel" of the chat via selecting from a dropdownlist.
This is the code that I have at the moment:
Note: The channel attribute is defined in another portion of code, and the entire page is loaded only once.
app.controller('mychat', function($scope, $firebaseArray) {
var d = new Date();
var today = d.getDate()+d.getMonth()+d.getYear();
var txt = document.getElementById('txtFBMsgs'); //store id of textbox
//Query
var ref = firebase.database().ref().child(channel)
$scope.fbmessages = $firebaseArray(ref);
$scope.send = function() {
if (txt.value != ""){ //check if textbox contains any message
$scope.fbmessages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
txt.value = ""; //reset value of textbox
}
}
})
and here is my html portion:
<div class="card mb-1 col-md-3" ng-controller="mychat" id="myDiv">
<div class="card-body" style="overflow-x: hidden; overflow-y:scroll; min-height:60vh; max-height:64vh;">
<div>
<p ng-repeat="m in fbmessages"> {{m.date | date:'short'}} - {{m.sender}}: <br> {{m.message}}</p>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-9">
<input type="text" id = "txtFBMsgs" class="form-control" placeholder="Message here..." ng-model="messageText" onkeydown = "if (event.keyCode == 13) document.getElementById('sendBtn').click()">
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
basically, it is a div that displays the chat messages, and an input box which is able to send the message to firebase.
Can I change the 'Channel' dynamically via javascript, such as on an onchange in a DDL?

Can't display javascript object properties in inner HTML

I'm trying to better understand javascript objects and how to actually put some data back into div. I created simple form in order to: 1.) retrieve data to HTML, 2.) made them into variables, 3.)display those variables in another div(to see if previous step worked fine) 4.) use variables to construct object 5.) display object's properties in div (again to see if previous step worked fine). No matter what do i do, i cannot display object's variables in HTML.
function processFormData() {
var fname = document.getElementById('input-name');
var sname = document.getElementById('input-surname');
var fnameTest = "Name: " + fname.value;
var snameTest = "Surname: " + sname.value;
document.getElementById('fname-display').innerHTML=fnameTest;
document.getElementById('sname-display').innerHTML=snameTest;
People();
}
function People(fname,sname) {
this.fn = fname;
this.sn = sname;
}
var people = new People(
fname,
sname,
);
//function showPeople() {
// alert(people.fn);
// alert(people.sn);
//};
function processObjData() {
var objFname = "Name: " + people.sn;
var objSname = "Surname: " + people.sn;
showPeople();
}
function showPeople() {
document.getElementById('fname-display-obj').innerHTML=objFname;
document.getElementById('sname-display-obj').innerHTML=objSname;
};
showPeople();
<form action="#">
<div class="col">
<input type="text" name="fname" id="input-name" class="form-control" placeholder="Name">
<input type="text" name="sname" id="input-surname" class="form-control" placeholder="Surname">
</div>
<button type="submit" onclick="processFormData(); return false;" class="btn btn-primary"><i class="fa fa-paper-plane"></i> Submit</button>
</form>
<div class="col visual">
<div id="fname-display"></div>
<div id="sname-display"></div>
</div>
<div class="col visual">
<div id="fname-display-obj"></div>
<div id="sname-display-obj"></div>
</div>
If i run it in console, but with part alert making version of
showPeople()
(here disabled) and without whole rest, alerts display normally.
I tried also bracket notation or putting
.value
after properties but nothing worked.
What i'm doing wrong?

Sending form data to Parse.com

I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>
This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});

Categories

Resources