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>
Related
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>
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}
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.
function ProvideValue(){
Values = document.getElementById('HiddenValue').value;
FirstCut = Values.split("###"); // This will return the array ID#-#VALUE#-#TYPE
var CtrlId;
for (i = 0; i < FirstCut.length - 1; i++) {
Strings = FirstCut[i];
SecondCut = Strings.split("#-#");
if(SecondCut[2].match("TEXT")) {
CtrlId = "" + SecondCut[0];
document.getElementById(CtrlId).value = SecondCut[1];
}
}
}
This is my code instead of the Id, which i can print it.But CtrlId is not replaced by the actual value. Am getting error document.getElementById(CtrlId).value is NULL. I tried to hard code the ID then its working fine but i cannot hard code the controlsID because there are 1000s of control and everytime the ID changes.
Your code seems fine (apart from implied globals1), you must have some other problem in your HTML document... I'm also not sure why you're leaving out the last value from the first cut since you're interating to length - 2, because i is less than length - 1 (not less than or equal) which means that it goes all the way to value length - 2 and then breaks the loop.
Here's a JSFiddle I created that uses your code and displays some additional console messages and actually applies values to inputs as provided by the hidden input.
1Important
I applied var to your variables so they're not implied globals which should be avoided at all times because they're nothing but evil friend of hidden bugs.
The code I used
HTML is super simple but I do have both elements with IDs that are being addressed in the compound value of the hidden field:
<input type="hidden" id="hidden" value="me#-#Rob#-#text###you#-#Mike#-#text" />
<input id="me" value="name" />
<input id="you" value="name" />
Script is simple as well (runs on DOM ready for JSFiddle simplicity reasons):
var vals = document.getElementById('hidden').value;
var firstCut = vals.split("###");
for(var i = 0; i < firstCut.length; i++) {
var ctrl = firstCut[i].split("#-#");
if (ctrl[2].match("text")) {
var id = ctrl[0];
document.getElementById(id).value = ctrl[1];
}
}
I am creating a small app and on one part of the app, i am creating a drop down select menu, that is populated with values from an array.
The problem i have is that when the form is loaded, it successfully loads and populates the select options with array values, but the problem is that when i add another element to an array and call the form again, it will still only load the values from when the form was first called.
How would i have the select option clear its values when i press the submit button. Here is the code the is called:
<div class="popupForm" id="newRelate_Form" style="display:none">
<form name="relationFormOne">
<script type="text/javascript" language="javascript">
var $selectFrom = $('<select id="mySelect">');
$($selectFrom).attr('id', 'objFrom');
for (var i = 0; i < objectArray.length; i++)
{
var value = objectArray[i].Name;
$('<option>').val(value).text(value).appendTo($selectFrom);
}
$selectFrom.appendTo($("#from_Object"));
var fromVal = document.getElementById("objFrom");
</script>
<button class="closeDOMWindow" onclick="createObj(fromVal.options[fromVal.selectedIndex].text)">Create</button>
</form>
The value is then passed to the function createObj():
function createObj()
{
/*
DO THE WORK NEEDED
*/
}
Now what javascript code would clear the select option so that when it is called again it can be repopulated with any new objects placed into the array?
Thanks for any feedback.
BTW the popup form refers to the fact that im using the following jquery plugin: DOM Window
Thanks for any feedback.
Plain JavaScript:
var ob = document.getElementById('selectID');
while (ob.hasChildNodes())
ob.removeChild(ob.firstChild);
jQuery:
$('#mySelect').children().remove()
Don't forget to delete the previously created select tag using $('#mySelect').remove() and then run the function.
First of all, the best way to add a piece of html is to write it from string:
<form id="relationFormOne">
<script type="text/javascript" language="javascript">
$(function(){
var objectArray = [{Name:'1'},{Name:'2'},{Name:'3'}];
var selectHtml = [];
$('#relationFormOne').append($('<select name="mySelect">'));
$(objectArray).each(function(ix, val){
selectHtml.push('<option>'+val.Name+'</option>');
});
$('select[name=mySelect]').html(selectHtml.join(''));
});
</script>
<input type="button" value="clear" onclick="$('select[name=mySelect]>option').remove()" />
</form>
When you want to clear your select just use the code like the following:
$('#mySelect>option').remove();