Dropdown list to JavaScript array to fill text boxes - javascript

I am trying to display a MySQL table on a job sheet system form that I am making the drop down list shows the customer details and then once selected the fields should be filled in on the main form.
I know people tend to use AJAX but this is to be used on a tablet tethered to a mobile and want to ask the server as little as possible.
Because I have already got the details from the SQL to display the drop down I thought I could use this. I found the original code at:
http://board.phpbuilder.com/showthread.php?10372137-RESOLVED-How-do-I-populate-multiple-text-boxes-from-a-dropdown-(I-can-populate-1-text-box!)
but I also want to display items that aren't on the dropdown list. Someone said it works but the more I have learned I couldn't see how because the array it was building just didn't seem to be in a JavaScript format.
I have the drop down working and also it fills a JavaScript array using names but I just cannot work out how to use the array to show in the fields.
It seems to be the named indexes used in the array. I can get a test array to display when I use the normal static array but I have commented them out but as soon as I try to use the names on the array I get undefined errors.
<html>
<head>
<script type="text/javascript">
<?php
include_once 'includes/db_connect.php';
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array building an object
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo 'customer['.$row['customer_id'].'] = new Array(';
echo 'customer['.$row['customer_id'].'][customer_id] = "'.$row['customer_id'].'";';
echo 'customer['.$row['customer_id'].'][post_code] = "'.$row['post_code'].'";';
echo 'customer['.$row['customer_id'].'][company_name] = "'.$row['company_name'].'");';
}
?>
</script>
</head>
<body>
<form name="customerform" form id="customerform">
<p>
<select name="customerselect" id="customerselect" onChange="showname()">
<option value="">Select customer</option>
<?php
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo'<option value="'.$row['customer_id'].'">'.$row['forename'].'">'.$row['surname'].'">'.$row['customer_name'].'</option>';
}
?>
</select>
</p>
<p>
<input type="text" name="cust" value="" id="cust" />
<input type="text" name="cust" value="" id="customerselected" />
<input type="text" name="post_code" value="" id="post_code" />
</p>
<p>update
<input type="button" name="update" id="update" value="update" onClick="showname()">
<p> </p>
<p>
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
<script>
//var customer = Array();
var customer = Array();
//This below is a test multi dimensional Array which does work. //
//customer['CCS'] = Array[{forename:'Robert', surname:'Grain', company:'HOMS'}];
function showname() {
//this var takes the result of the selected drop down list and shows the correct part of the array.
var customerselected = document.getElementById('customer');
customername = customerselected.value;
// this does work but not from the array just fills the details up
document.customerform.customerselected.value = customername;
// the next part takes the selected dropdown data and calls for the correct place in the array
// document.getElementById("cust").value = customer['CCS'][0];
// document.getElementById("cust").value = customer[CCS]["forename"] ;
// (customer[''][forename]);
document.customerform.post_code.value = customer[customerselect]["post_code"];
}
window.onload=function() {
showname();
}
</script>
</html>
This is the source code from Explorer in the console. from the JavaScript Array.
</body>
</html>customer[118] = new Array(customer[118][customer_id] = "118";customer[118][post_code] = "L37 4RG";customer[118][company_name] = "jc knight");customer[119] = new Array(customer[119][customer_id] = "119";customer[119][post_code] = "DE56 7HG";customer[119][company_name] = "farm Customer giles");customer[122] = new Array(customer[122][customer_id] = "122";customer[122][post_code] = "LE67 8FH";customer[122][company_name] = "a test company");
Also this dropdown list creates:
<select name="customerselect" id="customer" onChange="showname()">
<option value="">Select customer</option>
<option value="118">John">Knight"></option><option value="119">Bill">Giles"></option><option value="122">Robert">Grain"></option> </select>
</p>
Maybe I should move the code to the bottom of the HTML for the JavaScript array although I wasn't sure if this wouldn't be initialised when required because it has ran the HTML first. I'm a little unsure if the order of things were correct.
The error I receive happens as soon as I change the drop downlist and it shows the following:
document.customerform.post_code.value = customer['customerselect'][post_code];
}
X 'post_code' is undefined
I think somewhere I am getting my document.value wrong when showing my array ?

Rather don't hope that a constant will work here.
Instead try the below as a replacement:
// build javascript array
while($row=mysqli_fetch_array($result1)){ ?>
var customer["<?=$row['customer_id']?>"] = [];
customer["<?=$row['customer_id'];?>"]['customer_id'] = "<?=$row['customer_id'];?>";
customer["<?=$row['customer_id'];?>"]['post_code'] = "<?=$row['post_code'];?>";
customer["<?=$row['customer_id'];?>"]['company_name'] = "<?=$row['company_name'];?>";
<? }

Thanks smftre for that. In the end I have opted for the jquery and ajax. and I think it has worked out betted for it originally I was trying to make the code as efficient as possible on bandwidth because the system is to be used but ajax seems to be the standard for a reason and works very well.

Related

Javascript functions to print SIMPLE

I am new to programming and can not figure out why the innerHTML function will not print a value on the screen (I realized I used two functions and it seems extra for this small amount of code but it is because it is for a larger project)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="moneyform" name="moneyform">
<fieldset>
<select id="money" name="money" onselect="calculateTotal()">
<option value="loon">1 dollar</option>
<option value="toon">2 dollar</option>
</select>
<br>
<p id="pg"></p>
</fieldset>
</form>
<script type="text/javascript" src="TEST.js"></script>
</body>
</html>
//JAVASCRIPT BELOW
var moneyprice = new Array();
moneyprice["loon"] = 1;
moneyprice["toon"] = 2;
function moneyTotal() {
var mons = 0;
var frm = document.forms["moneyform"];
var selectedMoney = frm.elements["money"];
mons = moneyprice[selectedMoney.value]
return mons;
}
function calculateTotal() {
var total = moneyTotal();
document.getElementById("pg").innerHTML = total;
}
First, you are using the onselect event to kick things off, but select is for when text inside of a text field or textarea is selected by the user. You'll want to use the change event, which triggers when the value of an element changes.
Next, you aren't working with your Array properly and it's causing your result to come back as nothing. Arrays have non-negative integer indexes where data can be stored. They don't have key names to store data in - - Objects do that. You can see here that after these lines run, you still have an empty Array:
var moneyprice = new Array(); // Ok.
// moneyprice doesn't/can't have a "loon" or a "toon" index
// so neither of these lines accomplish anything
moneyprice["loon"] = 1;
moneyprice["toon"] = 2;
console.log(moneyprice); // Empty array
// ******************************************
// Now, this is how to use an array:
var moneyprice2 = new Array(); // Ok.
// You interact with an Array via its numeric indexes:
moneyprice2[0] = "loon";
moneyprice2[1] = "toon";
console.log(moneyprice2); // Empty array
Now, it's not clear as to what you are trying to do with that Array anyway and it seems that what you are attempting to do doesn't really make much sense - your functions talk about money and calculating totals, but your select has string values.
Lastly, the code you are using uses ancient techniques that you really shouldn't get too comfortable using. There's a lot of bad code out there, so learn from a reputable source. The Mozilla Developer Network is one.
See this scaled back solution to give you an idea of the "moving parts" to get something up and running. Notice how all the JavaScript is separated from the HTML.
// Get your element references the proper way.
// No need to get a reference to the form, just to get a reference
// to the select and even if we did want to get a reference
// to the form, we use the modern DOM API to do it (not document[forms]).
let select = document.getElementById("money");
let pg = document.getElementById("pg");
// Set up event handlers in JavaScript, not with HTML attributes
select.addEventListener("change", calculateTotal);
function calculateTotal() {
// .innerHTML should only be used when the string you are dealing with
// contains HTML that needs to be parsed as such. When there isn't any
// HTML, use .textContent
pg.textContent = select.value;
}
<form id="moneyform">
<fieldset>
<select id="money" name="money">
<option value="loon">1 dollar</option>
<option value="toon">2 dollar</option>
</select>
<br>
<p id="pg"></p>
</fieldset>
</form>

Automatically changes the value of total field when other field has value dynamically in javascript

I try to achieve Total of two input fields and those fields got their value dynamically from database after selecting a dropdown option. The html code and the sql query looks like below:
<select name="getData" ID="getData" onchange="getData()">
<option value="Select">Select Subscription Package</option>
<?php
$sql = "SELECT * FROM package WHERE status = 1";
$result = $connect->query($sql);
while($row = mysqli_fetch_row($result)){
echo '<option data-price="'.$row[4].'" value='.$row[0].'> '.$row[1].' </option>';
}
?>
</select>
<input type="text" id="price1" name="price1"/>
<input type="text" id="price2" name="price2"/>
<input type="text" id="totalAmount" name="totalAmount" onblur="totalCalc()">
Value of price1 & price2 changes when SELECT Option changed. Now I need to get total of these two fields by javascript. The js code is below:
<script>
function totalCalc() {
var A = document.getElementById("price1").value;
var B = document.getElementById("price2").value;
var C = A + B;
document.getElementById("totalAmount").value = C;
}
</script>
I got the total but it needs to click the total amount field. I want the calculation should be done automatically right after the first two fields got their values dynamically.
Any help is appreciated.
You should just set up change event handlers on both inputs that point to your totalCalc function and then, at the end of your getData() function, manually trigger the change event of one of the inputs.
If the code in getData is asynchronous, then the code that manually triggers the change event should be included in the success handler of the operation.
A note about the UI. If the two price fields are being auto-populated and users won't be inputting anything into them manually, disabling the fields is probably appropriate. With regards to the final total, an input there may not make sense at all - you just need to show the result, so a span element would work.
Also, inline HTML event attributes (onclick, onchange, etc.) should not be used. There are many reasons why this 20+ year old technique needs to die the death it deserves, but because so many people don't take the time to really learn JavaScript and modern best-practices, they just copy someone else's code that uses them and go on their merry way.
So, in the code below, I'm showing how to solve this problem using modern, standards-based code that follows best-practices.
// Get references to the DOM elements you'll need to work with
let a = document.getElementById("price1");
let b = document.getElementById("price2");
let total = document.getElementById("totalAmount");
let select = document.getElementById("getData");
let price1 = document.getElementById("price1");
let price2 = document.getElementById("price2");
// Set up event handlers in JavaScript, not HTML
select.addEventListener("change", getData);
price1.addEventListener("change", totalCalc);
price2.addEventListener("change", totalCalc);
function totalCalc() {
total.textContent = +a.value + +b.value;
}
function getData(){
// This is just mean to replicate what SQL does
price1.value = 15;
price2.value = 27;
// Manually trigger the change event for either one of the inputs
// If the existing code in getData is asynchronous, then this code
// should be added to the "success" callback. If not, it can just be
// placed at the end of the function as I'm showing it here.
var event = new Event('change');
price1.dispatchEvent(event);
}
<select name="getData" id="getData">
<option value="Select">Select Subscription Package</option>
<option>Data 1 from SQL</option>
<option>Data 2 from SQL</option>
<option>Data 3 from SQL</option>
</select>
<input type="text" id="price1" name="price1" disabled>
<input type="text" id="price2" name="price2" disabled>
<!-- No need to place the result in an <input> since users won't
be inputted data here. You just need to show it. -->
<span id="totalAmount"></span>

Trouble setting variables from form inputs. Radio and Text entries

I am attempting to create an equation using people's pay rates and some other information from a from. However, I can't even get variables to set based on information from the form. The form includes 1 set of radio buttons and 2 text input forms.
<form id="userInfo" action="" method="post">
<p>Pay Frequency: <select name="payFreqS">
<option>Hourly</option>
<option>Weekly</option>
<option>Bi-Weekly</option>
<option>Monthly</option>
</select></p>
<p>Pay Rate:<input type="text" name="payRateS" value="0000.00">
</p>
<p>Cost of Item:<input type="text" name="costS" value="000.00">
</p>
</form>
<p><input name="submit" type="submit" class="btn" value="Submit" onclick="shouldIBuy()"/></p>
Javascript:
function shouldIBuy()
{
// attempt to find error with console statements
console.log("How far can we get?");
// setting variables for my function
var payRate = document.getElementByIds("payRateS").value;
var cost = document.getElementById("costS").value;
// pay frequency variable
var payFreq = document.forms[0].payFreqS;
var i;
for (i=0;i<payFreq.length;i++)
{
if (payFreq[i].checked)
{
payFreqVal = i;
}
}
//more console.log statements to troubleshoot
console.log(cost);
console.log(payRate);
console.log(payFreq);
// setting what I hoped were strings to integers.
var payRateInt = parseInt(payRate);
var costInt = parseInt(cost);
There should be errors in your console because you are using the non-existent getElementByIds.
I went back and broke it down to the very basic elements to figure out was going on. I was not referencing the right things. You were right. Thanks.

Creating form fields from user input

I found a code that creates some form fields based on a number chose by the user.
<script type='text/javascript'>
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Member " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "Member["+i+"]";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
</script>
<input type="text" id="member" name="member" value="">Number of Members: <br />
<input type="button" id="enterdetails" value = "Enter Details"onclick="addFields()">
<div id="container"/>
</div>
It works fine. But I want to create elements with names/values imported from a database. In php I do like this:
<SELECT name='smth'>
<OPTION value=""></OPTION>
<?php
$qry = $dbh->query("select * FROM table");
while ($a = $qry->fetch(PDO::FETCH_ASSOC)) {
$smth = $a['smth'];
echo "<OPTION value='$smth'>".$smth."</OPTION>";
}
?>
</SELECT>
Need help on how to do it in javascript.
You cant get database fields with javascript. You must use php or something like this.
Maybe this can help you. Here is the link. choose your database and table, and select your field names, and choose field's type of form (text area, text, radio button groups, etc) and push create. You will have a bootstrap designed form and php insert code writed with medoo (medoo.in).
you can use this. create your database first and make form automaticly. Copy code and paste to your pages.
Also i offer you to use meddo to connect and use sql with it. There is a sample in that link form.min.php, includes your database and user and pass information.

How to send and receive MySQL data for dynamic input fiels

I was wondering how someone would send and receive input data to and from a MySQL database when the form that is being submitted can have additional fields added to it (So one order form might have 10 input fields and another might have 30). Here is a snippet to give you an idea of what I am talking about - http://jsfiddle.net/gv0029/M84r7/
I saw an post about using arrays but it was from 4 years ago and am wanting to make sure whatever I do is still using best practices. Any and all help or ideas would be greatly appreciated! Thank you!
HTML:
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<label>Fence Height</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input name="postQuantity_1" class="postQuantity" />
</label>
<label>Picket Quantity
<input name="picketQuantity_1" class="picketQuantity" />
</label>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
parts = $('.6foc:last').attr('name').split("_");
parts[1]++;
$('.6foc:last').attr('name', parts.join("_"));
parts = $('.railQuantity:last').attr('name').split("_");
parts[1]++;
$('.railQuantity:last').attr('name', parts.join("_"));
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
So it sounds like you have an unknown number of fields and you are looking for an easy way to send them to MySql. So I'm assuming you are calling a stored procedure but don't know how to deal with the unknown parameters. I would take the form and either serialize it into JSON or turn all the $_POST values into a XML object. Then you would only need to pass that single object into your MySql stored procedure. Once inside you could use some loops and XML function to do what you have to do. This way it wouldn't matter if your submitting 10 fields or 100 fields, the call to the stored proc would always be the same. I do this with a site and it works pretty good. Not on that PC to where I can get the code right now though. These might help....
To turn the PHP $_POST into XML: http://davidwalsh.name/watch-post-save-php-post-data-xml
Some MySql XML function to use once you're inside the stored proc: http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html
I could help more later when I get on my other PC.. Hope this helps.
UPDATE: Here is how I grab all $_POST data and turn it into a valid XML document...
//Grab all the POST info, turn it into a valid XML object and store it
$postData = null;
if($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) > 0) $postData = assocArrayToXML('POST_DATA',$_POST);
//The assocArrayToXML returns the XML object with page breaks, we need a stright non-breaking string
//so that the flexigrid can display the results properly.
$postData = str_replace(chr(13), '', $postData);
$postData = str_replace(chr(10), '', $postData);
And this is the assocArrayToXML function...
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = create_function('$f,$c,$a','
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild(htmlspecialchars($k));
$f($f,$ch,$v);
} else {
$c->addChild($k,htmlspecialchars($v));
}
}');
$f($f,$xml,$ar);
return $xml->asXML();
}
Serialize your form and send. In the server side unserialize it and insert to database
var str = $( "form" ).serialize();
Reference
http://api.jquery.com/serialize/

Categories