Trying to add variable value from an html form into javascript - javascript

I've got a form set up below which has two inputs Keywords and min price
<form name="Data" method="GET" action="#">
<table cellpadding="2" border="0">
<tr>
<th>Keywords</th>
<th>Min Price</th>
</tr>
<tr>
<td><input type="text" name="keywords" id="keywords"/></td>
<td><input type="text" name="MinPrice" id="MinPrice"/></td>
</tr>
<tr>
<td colspan="2" align="center"><INPUT type="submit" name="submit" value="Search">
</td>
</tr>
</table>
</form>
Then the results obtained need to go into a javascript that then should return result based on the variable. The JS works without the variable i.e. just putting them in in the code, but i can t figure out how to reference the above form then submit the code as a whole
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
var filterarray = [
{"name":"MaxPrice",
"value":"1000",
"name":"MinPrice",
"value":Variable here!!,
"paramName":"Currency",
"paramValue":"GBP"},
Above is part of the script where one of the values would go
Any help apreciated p.s. complete novice so take it very slowly

Your list of options is not correct, several properties have the same name.
Here is a different way to present it:
var maxPrice = document.getElementById('MaxPrice').value;
var minPrice = document.getElementById('MinPrice').value;
var filterOptions = {
"MaxPrice": maxPrice,
"MinPrice": minPrice,
"paramName":"Currency",
"paramValue":"GBP"
};
You can then use them in your code. For example the min price will be filterOptions.MinPrice.

To retrieve the content from the MinPrice input text just do the following:
var minPrice = document.getElementById('MinPrice').value;
or more simply with jquery:
var minPrice = $('#MinPrice').val();
As for the way you are buiding up your array taht does not make much sense to me:
var filterarray = [
{"name":"MaxPrice",
"value":"1000",
"name":"MinPrice",
"value":Variable here!!,
"paramName":"Currency",
"paramValue":"GBP"},
...
Here you are building an array of objects containg the same fields multiple times (name and value). That does not make much sense to me. You should maybe reconsider the structure of the literal objects you are trying to populate the array with.

Related

How to get value from input field with Javascript?

How can I get the value of an specific input field with Javascript?
Lets take this shopify shop for example: https://geekymate.com/products/magic-doormat-1?variant=18941211607138
I am trying to create a script which is automatically applying an discount code based on the quantity filled in the quantity field.
But to do that I need to be able to get the latest value of the field.
How would the code look like to get the latest/current value?
EDIT: Thank you for the hint with the question. I do know that I need to use getElementById ( For the linked page above it would be this: var x = document.getElementById("Quanity").value; ) but how do I always get the latest input automatically if the enduser is changing the value?
The other answers are also correct (using jQuery .keyup), but you can also use this solution below (which is better). This solution uses pure javascript.
The code selects the element by using .getElementById() and uses .addEventListener() to do something when input changes.
var text = document.getElementById("text");
window.onload = function() {
text.addEventListener("input", function() {
console.log(text.value);
});
}
<input id="text" />
Or you can use the following if you want a jQuery solution. This uses jQuery .bind().
$("#text").bind("input", function() {
console.log($("#text").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="text" />
keyup() function ;)
It runs each time, when user types new text.
Also, you can use input() or change() functions.
In jQuery it works like this:
$(document).on('keyup', '#InputID', function(){
//...code...
var discount = Number( document.getElementById('InputID').value )*10/100;
});
It's a Jquery function that runs on keypress. I've included a snippet below to see how it would tie in with an input field.
$('#code').keyup(function() {
var discountcode = this.value;
console.log(discountcode);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="code" type="test" />
Keyup runs every time a specific element is lifted. Imagine someone enters 'Hello'
You will see the following logged:
'H' 'He' 'Hel' 'Hell' 'Hello'
look at the code snippet. using JavaScript to get the values. and can use addEventListener to detect the change and use detectChange function to get the latest values.
var discount = [];
function detectChange() {
var table = document.getElementsByClassName("shappify_qb_grid")[0];
for (var i = 0; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
row = table.rows[i].cells[j].innerHTML;
rate = parseFloat(row);
if (rate && discount.indexOf(rate) < 0) {
discount.push(parseFloat(row));
console.log('---', parseFloat(row));
}
}
// console.log('discount : ', discount);
}
}
}
detectChange();
console.log('discount : ', discount);
<table class="shappify_qb_grid" border=1>
<thead>
<tr>
<th>Qty</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Buy 1</td>
<td>0% Off</td>
</tr>
<tr>
<td>Buy 2</td>
<td>10% Off</td>
</tr>
<tr>
<td>Buy 4</td>
<td>12% Off</td>
</tr>
<tr>
<td>Buy 5</td>
<td>14% Off</td>
</tr>
<tr>
<td>Buy 6</td>
<td>17% Off</td>
</tr>
</tbody>
</table>
This work for me!
document.getElementById("text").value;
<input id="text" />
Use the document.getElementById(); -command to get the existence of the referenced element in your HTML page. Then use the same technique of assigning attributes in the original HTML coding rules.
Use document.getElementById('able').value = 'whatever';.

Calculate quantity and total on an order form in javascript

I'm looking for some help with a bit of code please. I'm supposed to create a form that allows the user to input a quantity for items which they wish to purchase. When the quantity is input, the total price for that particular item is displayed, and the grand total (at the bottom of the form) for all purchases.
When the user presses the submit button, an alert popup appears.
I'm having trouble with the calculation part in javascript. It is not calculating any of the total amount or quantity values.
(For some reason the code won't indent here properly but they are in the actual documents).
function calc(){
var QtyA = 0; var QtyB = 0; var QtyC = 0;
var TotA = 0; var TotB = 0; var TotC = 0;
var PrcA = 3; var PrcB = 4; var PrcC = 5.50;
if (document.getElementById('QtyA').value > "");{
QtyA = document.getElementById('QtyA').value;}
TotA = eval(QtyA) * eval(PrcA);
TotA = TotA.toFixed(2);
(document.getElementById('TotalA').value = TotA);
if (document.getElementById('QtyB').value > "");{
QtyB = document.getElementById('QtyB')value;}
TotB = eval(QtyB) * eval(PrcB);
TotB = TotB.toFixed(2);
(document.getElementById('TotalB').value = TotB);
if (document.getElementById('QtyC').value > "");{
QtyC = document.getElementById('QtyC')value;}
TotC = eval(QtyC) * eval(PrcC);
TotC = TotC.toFixed(2);
(document.getElementById('TotalC')value = TotC);
Totamt = eval(TotA) + eval(TotB) + eval(TotC);
Totamt = Totamt.toFixed(2); //fix to 2 decimal places
(document.getElementById('Grand Total is: ').value = Totamt);
alert (Totamt);
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<style>
#import "css/OrderForm.css";
</style>
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td width="80">Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€3.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€4.00</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td width="80">Glasses</td>
<td><img src="images/glasses.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA" size="5" onchange "calc()"></td>
<td>€5.50</td>
<td>
<input type="text" id="TotalA" size="12" onchange "calc()">
</td>
</tr>
<tr>
<td> Total: </td>
<td><input type="text" id="GrandTotal" size="15" onchange="calc()"></td>
</tr>
</table>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Ok, as a teacher, I just can't let all the bad habits that someone is trying to teach you go. So, here we go....
eval() is EVIL - Don't use it, ever!
eval() tells the JavaScript runtime to process a string as if it were JavaScript. This is very dangerous because if the string contains malicious code, eval() will run it. In your code, you run eval() on the value entered into a text box and since you have no idea what value will be entered, you also have no idea what string eval() will receive. This equates to a huge security hole and is one of the reasons eval() should not be used. Secondly, even in a perfect world, eval() is slow, so from a purely performance standpoint, you wouldn't want to use it. Frankly, I'm shocked that someone taught you to use it and especially for converting strings to numbers. That alone is enough to ask for your money back!
In your case, you need to convert the string input into numbers so that you can do math with the input. JavaScript offers several ways to do this:
parseInt(stringContainingNumber, radix)
parseFloat(stringContainingNumber)
Number(stringContainingNumber)
+stringThatIsNumber Unary Operator
Don't set up your event handling in HTML with event attributes.
When JavaScript was first created (25+ years ago), the way to set up an event handler for an HTML element (a.k.a DOM element) was to use HTML attributes such as onclick, onchange, onmouseover, etc. inline with the element in the HTML. Unfortunately, because of how simple that technique looks it gets used over and over again instead of dying the quick death it deserves. There are several reasons not to use this outdated technique. Today, we have modern standards and best practices to follow and so, event handling should be done in JavaScript, separate from HTML, with .addEventListener()
Also, your code of: onchange "calc()" was incorrect anyway because the code should have been: onchange = "calc()".
Additionally, think about what elements need events set up for them. Your original code had it set up so that if the total gets changed, calc() would run, but that makes no sense. Why would someone be able to change the total directly and what would doing so actually cause to happen? Should the quantity change because the total has changed?
Pay attention to details
You have 3 rows to calculate 3 quantities * 3 prices to get 3 totals, but you just copied/pasted the HTML for the 3 rows and wound up with 3 input elements with the same id of QtyA even though your JavaScript was correctly looking for QtyB and QtyC.
Do your styling with CSS, not HTML
All of your quantity input fields need to have their width set to a size of 5. Don't use the HTML size attribute for that, do it with the width CSS property. The HTML will be cleaner and you won't have to repeat the same instruction 3 times.
#import is being used incorrectly
The CSS #import directive is meant to be used as the first line in external stylesheets that import instructions from another stylesheet, effectively combining multiple sheets into one. If you have only one stylesheet to use, you don't import it, you link to it.
Instead of: <style> #import "css/OrderForm.css";</style>
use: <link href="css/OrderForm.css" rel="stylesheet">
When you are just displaying a result, don't place it into a form field.
There's no reason to put a total into an input field when you don't want the user to be able to modify that result. Instead, just place it as the text of a non-editable element - - in your case the appropriate cell of the table.
Lastly: Use the developer's tools!
All modern browsers incorporate "developer's tools", which you can activate by pressing F12. There are many tabs in the tools, but the "Console" tab is probably the most important for you right now. If you have errors in your syntax (as you did), the Console will show them and the line number. You must eliminate all of your syntax errors before you can expect your code to run.
The Console is also an invaluable tool for testing values in your code. You can insert:
console.log(anything that is supposed to produce a value);
into your code to verify that variables, elements, etc. have the values you think they do.
Now, in reality, I would go about solving this problem in a very different way that you are attempting, but that is more complex than you are ready for at this stage, so I've gone along with your approach somewhat.
Please read through the HTML and JavaScript comments carefully to explain what's being done.
<!DOCTYPE html> <!-- The DOCTYPE tells the browser what version of HTML it should be expecting. -->
<html>
<head>
<meta charset="UTF-8">
<title>Order Form</title>
<!-- To reference a single stylesheet, use the link element: -->
<link href="css/OrderForm.css" rel="stylesheet">
<style>
/* Make all the input elements that have an id that starts with Qty
be 5 characters wide. (Now size=5 isn't needed in the HTML 3 times) */
input[id^=Qty] { width:5em; }
/* The first <td> in each row should be 80px wide. Now we don't have to
clutter up the HTML with this and we don't have to repeat it 3 times. */
td:first-child { width:80px; }
</style>
</head> <!-- You didn't close your <head> tag! -->
<body>
<form>
<table border="1">
<tr>
<th>Item</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Hat</td>
<td><img src="images/hat.jpg" alt="Hat"></td>
<td><input type="text" id="QtyA"></td>
<td>€3.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalA"></td>
</tr>
<tr>
<td>T Shirt</td>
<td><img src="images/t_shirt.jpg" alt="T-Shirt"></td>
<td><input type="text" id="QtyB"></td>
<td>€4.00</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalB"></td>
</tr>
<tr>
<td>Glasses</td>
<td><img src="images/glasses.jpg" alt="Glasses"></td>
<td><input type="text" id="QtyC"></td>
<td>€5.50</td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<td id="TotalC"></td>
</tr>
<tr>
<td> Total: </td>
<!-- You shouldn't be putting results of calculations into input fields
when you don't want the user to modify the data. Just place it into
an elmeent as its .textContent -->
<!-- You need to have this cell span over the remaining columns of the
table, so colspan=4 needs to be added. -->
<td id="grandTotal" colspan="4"></td>
</tr>
</table>
<!-- Your form doesn't actually submit data anywhere, so you shouldn't
have a submit button. A regular button will do. -->
<input type="button" value="Get Grand Total">
<input type="reset" value="Reset">
</form>
<script>
// Get references to the HTML elements that you'll be working with
var qtyBoxA = document.getElementById('QtyA');
var qtyBoxB = document.getElementById('QtyB');
var qtyBoxC = document.getElementById('QtyC');
var totBoxA = document.getElementById('TotalA');
var totBoxB = document.getElementById('TotalB');
var totBoxC = document.getElementById('TotalC');
var grandTot = document.getElementById('grandTotal');
var btnGetTot = document.querySelector("input[type=button]");
var btnReset = document.querySelector("input[type=reset]");
// Set up event handling in JavaScript, not HTML.
qtyBoxA.addEventListener("change", calc);
qtyBoxB.addEventListener("change", calc);
qtyBoxC.addEventListener("change", calc);
btnGetTot.addEventListener("click", getGrandTotal);
btnReset.addEventListener("click", reset);
var gt = null; // Will hold the grand total
function calc() {
var priceA = 3;
var priceB = 4;
var priceC = 5.50;
gt = 0;
// Convert the values in the quantity textboxes to numbers. The 10 that
// is being passed as the second argument indicates the "radix" or the
// numeric base system that should be used when the string is being
// interpreted. Here (and often), we work in the base 10 numeral system.
var qtyA = parseInt(qtyBoxA.value, 10);
var qtyB = parseInt(qtyBoxB.value, 10);
var qtyC = parseInt(qtyBoxC.value, 10);
// If each of the quantity fields are not empty, calculate the price * quantity
// for that row, place the answer in that row's total field and add the answer
// to the grand total
// NOTE: You had semicolons like this: if(); {}, which is incorrect.
// NOTE: Notice that there are + signs right in front of the total box references?
// this forces a conversion of the string in the text to a number. Since we
// just put a number into the cell, we know for sure it can be converted.
// NOTE: If parseInt() can't parse a number from the string provided, it returns NaN
// (Not A Number), we can check to see if we got NaN with the isNaN() function
// and here, we want to know if we don't have a NaN, so we prepend a ! to it
// (the logical NOT operator) to test the opposite of the isNaN() function result.
if (!isNaN(qtyA)) { totBoxA.textContent = qtyA * priceA; gt += +totBoxA.textContent; }
if (!isNaN(qtyB)) { totBoxB.textContent = qtyB * priceB; gt += +totBoxB.textContent; }
if (!isNaN(qtyC)) { totBoxC.textContent = qtyC * priceC; gt += +totBoxC.textContent; }
grandTot.textContent = gt.toFixed(2); // Just place the answer in an element as its text
}
function getGrandTotal(){
calc(); // Make sure all values are up to date
alert(gt);
}
function reset(){
// The built-in functionality of the <input type=reset> will clear out
// the quantity input fields automatically, but we need to manually reset
// non form field element that have been modified:
totBoxA.textContent = "";
totBoxB.textContent = "";
totBoxC.textContent = "";
grandTot.textContent = "";
}
</script>
</body>
</html>

Looping through html tables

I have a page that has a table and a small form. The table has some data on questionnaires. I am trying to use jquery to loop through the table, checking if a condition is met, then adding it to the correct field of the form. The problem I have is that the forms are not created by me so I cant match them to set id's. So i need to get the field_id from relate, and the answer inserting into that location. Im new to Jquery and js. This is what I came up with.
html
<div align="left">
<table class="table table-striped">
<thead>
<td>Question</td>
<td>Answer</td>
<td>Relates to</td>
</thead>
<tbody>
<tr>
<td>Random question 1</td>
<td>Random answer 1</td>
<td>add to variable form field</td>
</tr>
<tr>
<td>Random question 2</td>
<td>Random answer 2</td>
<td>add to a different form field</td>
</tr>
</tbody>
</table>
</div>
<input type="text" id="variable id that could be matched with element of table">
main.js
table.find('tr').each(function (i, el) {
var $mylists = $('#' + relate)
$mylists.html('');
var $tds = $(this).find('td'),
label = $tds.eq(0).text(),
relate = $tds.eq(1).text(),
answer = $tds.eq(2).text();
$('<span></span>').text(answer).appendTo($mylists);
});
Since you have a single input that you want to append values you, you need to set the val of the input. And since you want to create that single input value from multiple other values (answers), you need to loop through, get all your answers, then combine them into a single value. Something like this:
var $mylists = $('#' + relate);
$mylists.val('');
var answers = [];
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
label = $tds.eq(0).text(),
relate = $tds.eq(1).text(),
answer = $tds.eq(2).text();
answers.push(answer);
});
// at this point, answers contains an array of all your individual answer values.
// decision time: what do you want to do with them?
// in this example, I join them together in a comma-delimited list.
$mylists.val( answers.join(', ') );

populate div by doing math on table cells

Trying to figure this stuff here out. Can't figure out if it's on the count of me having the numbers in the tds already. Is it takin em in as strings so it don't know how to do the math? I know I got this all wrong, but this is easy stuff I reckon so I hope you can set me straight. Much obliged.
<table id="Table">
<tr>
<td width="124" style="position: relative" rowspan="4">
<div id="percentage"></div>
</td>
<td>Total</td>
<td id="Total">259</td>
<td>Result</td>
<td id="Count">11</td>
</tr>
</table>
JS:
var total = $("Total");
var count = $("Count");
var Result = (Count/Total*100);
document.getElementById("percentage").innerHTML = Result;
That didn't work.
Also I need that there Result in .innerHTML to come out as a percentage. Should I just multiply it by 100 like I did here and attach a "%" manually?
Your JavaScript is looking for element types instead of the id's change your js to:
var total = parseInt($("#Total").text(), 10);
var count = parseInt($("#Count").text(), 10);
var Result = (count/total*100);
You are also not converting to a number.
you forget '#' to select by Id and you are not convert to int, so you can make it by jQuery in one line:
$('#percentage').text(parseInt($('#Count').text())/parseInt($('#Total').text())*100);

How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery

<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>
Goal: To get buttons button1 and button2 to trigger the same function get() which should get the value of the first <td> in the same <tr> the button resides in. Which is, in this case: foo1 and foo2 respectively.
This is a rough outline of the function which should help understand what I'm trying to achieve-
function get(element){
alert(element.tr.first_td.innerHTML);
}
I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.
Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:
function find( element ) {
alert( element.parentNode.parentNode.cells[0].innerHTML );
}​
Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/
Try this, since you have many tr and td tags right, so, you can do DOM Parsing. But you need to specify one ID for the table to get that table. For now lets call it foo-table.
var table = document.getElementById("foo-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
If you don't wanna give an ID and you are sure that there is only one table, then use this:
var table = document.getElementsByTagName("table");
var cells = table[0].getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
Enjoy! Hope this helps! :) No jQuery or any other plugin. Pure JavaScript. :)
<table>
<tr>
<td id="button1_value">foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get('button1_value');"></td>
</tr>
<tr>
<td id="button2_value">foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get('button2_value');"></td>
</tr>
</table>
You shoul identify what you want to get using an ID so that you can easily retrieve it. This also helps prevent the chance of getting erroneous data. If you give the component an id you should be able to use document.getElementById() to get that component.
function get(element){
var obj = document.getElementById(element)
alert(obj.innerHTML);
}

Categories

Resources