Can't display javascript object properties in inner HTML - javascript

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?

Related

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.

How can I send an array of values from the inputs to the controller

I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;

How not to overwrite your variables

I've been stuck on this problem without a clear way around it for a while now. https://jsfiddle.net/brendanjackson/4ajs7czo/3/
Here's the scenario. I have two functions that send one set of data to different areas of my page. So if you enter some text in the main field, hit submit, it sends that text to 'set1' and creates a button and select menu.
<body>
<div class="container-fluid">
<div class="start">
<form class="form-inline">
<h1><strong>Start</strong></h1>
<div class="row">
<div class="col-xs-4">
Task:<input type="text" class= "task form-control" id="input_text" >
</div>
</div>
<!--***********************************************************************************************************-->
<div class="row">
<div class="col-md-4">
Send to:
<select class="set1_menu">
<option value="set1table0">set1table0</option>
</select>
</div>
<div class="col-md-4">
<input type="button" id='submit_button' class="btn btn-primary" value="Submit!" />
</div>
</div>
</form>
</div>
<!--***********************************************************************************************************-->
<div>
<h1 class="label label-default">Set1</h1>
<div class="set1 row">
<div class="set1_table0 column ">
<h3>set1table0</h3>
<ul class="set1_text0"></ul>
</div>
</div>
<!--**********************************************************************************************************-->
<div>
<h1 class="label label-default set2">Set2</h1>
</div>
<!--*********************************************************************************************************-->
<div>
<div class="set2_table0 column">
<h3>set2table0</h3>
<ul class="set2_text0"></ul>
</div>
</div>
</div>
$('#submit_button').on("click",function() {
/*==========================================
variabes
===========================================*/
task = $(".task").val();
set1_menu = $(".set1_menu option:selected");
set1_index = set1_menu.index() //switch arg
set2_menu = '<select class="set2_menu"> <option value="set2_table0">set2table0</option> </select>';
set2_button = '<input type="button" class="set2_button" data-set1_data="'+set1_index+'" value="set2_button" />'
$('.set1_table0').append("<li>" + task + " " + set2_menu + " " + set2_button + "</li>" );
})
$("div.set1.row").on("click", "input.set2_button", function(){
/*==========================================
variabes
===========================================*/
var set2_index = $(this).closest('li').find('select.set2_menu option:selected').index();
var set1_data = $(this).data('set1_data');
var set2_data = $(this).data('set2_data');
/*=========================================
TEST
=========================================*/
console.log( "IT WORKS" + " " + set2_index );
switch(set2_index){
case 0:
$('.set2_table0').append("<li>" + task + " " + " (from Table " +set1_data+ " )" + " " /*+ datetimepicker + " "*/ + "</li>" );
break;
}
});
Problem:
If the user follows the data sent to set1 and sends it to set2 all is well and the jedi win!
However, if the user decides to go back to the start, enter new information, and send it to set1, the previous variable has of course been overwritten and can no longer be sent to set2. It will now send whatever the newest variable's information is.
Something was suggested to me like adding var i=0++, task and then adding i++ on my 1st function so it gives each variable its own easy to find # like task0, task1, task(n) as well as turning it into an array. Both of these solutions I'm just not understanding how to implement, maybe for the lack of how to express my problem to research it?
Question
How do I cleanly save each set of data that is submitted so that it can be sent from set1 to set2 whenever the user decides they're ready.

HTML Form data into a Object to pass a method

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;

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