Trying to create quantity x cost with Javascript - javascript

I am creating a merchandise page where I have put the items into separate tables. I want to have it so that when someone selects a quantity, it will display the appropriate price in the field below. Here's the HTML so far:
<table border="1" id="tshirtTable" style="float:left">
<tr>
<th colspan="2">Burundi T-Shirt</th>
</tr>
<tr>
<td colspan="2"><img src="https://rlv.zcache.com/burundi_t_shirt-re5f84ff8b0724bbda7582389e5816a6f_k2g1o_324.jpg" alt="Burundi T-shirt"></td>
</tr>
<tr>
<td id="qty">Quantity</td>
<td>
<select id="tshirt">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr>
<td id="price">Price</td>
<td><input type="text" disabled="true"></td>
</tr>
</table>
I'm pretty new to JS so not sure how to have it calculate the price, depending on which quantity is selected. Guessing I'll have to set the price somewhere, but not exactly sure how to get started on it.
Any help is appreciated, thanks!

I've refactored your code. In my example, we have list of products. It doesn't really matter, you can have here one product or as many as you want. For learning purposes it's better do handle table of items.
First of all we won't be using disabled attribute but readonly. It's is very important, because disabled key-value won't be send to the server. If you want to block the input from changing use readonly. Secondly you don't need to pass =true value to your attribute.
<input type="text" disabled="true"> // bad
<input type="text" readonly> // ok
Another thing is that attribute id is unique per document and we can have only one. Read more on MDN.
The id global attribute defines a unique identifier (ID) which must be
unique in the whole document. Its purpose is to identify the element
when linking (using a fragment identifier), scripting, or styling
(with CSS).
No jQuery in my example, you should learn pure javascript first.
To calc, we must change type of our values. Reading them from inputs, their type is String, we must convert them to Number. In our case we use parseInt() function. It's better to use parseFloat(), when we expect floating point number.
Read my comments to have better understanding what is going on. If you have any confusion make sure to ask.
var table = document.getElementById('tshirtTable');
table.addEventListener("change", function(e) {
// If we are not changing these elements we quit
if (e.target.name !== 'quantity' && e.target.name !== 'each-price') {
return;
}
// Let's check what is id of our element
// We store our id in <tr id="..."
// To access tr, we must find tr by using .closest function
var tr = e.target.closest('tr');
var productId = tr.id;
var quantityValue = tr.querySelector('.quantity').value;
var eachPriceValue = tr.querySelector('.each-price').value;
var totalPriceValue = tr.querySelector('.total-price').value;
// Here is important part, we must parse values as type Number, because currently they are type String
tr.querySelector('.total-price').value = ( parseInt(quantityValue) * parseInt(eachPriceValue)).toFixed(2);
});
<table border="1" id="tshirtTable" style="float:left">
<thead>
<th>Name</th>
<th>Quantity</th>
<th>Price / Each</th>
<th>Total Price</th>
</thead>
<tbody>
<tr id="1">
<td>Burundi T-Shirt</td>
<td><select class="quantity" name="quantity">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td><input class="each-price" type="text" name="each-price" value="15"></td>
<td><input class="total-price" name="total-price" type="text" readonly></td>
</tr>
<tr id="2">
<td>Burundi Skirt</td>
<td><select class="quantity" name="quantity">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td><input class="each-price" type="text" name="each-price" value="25"></td>
<td><input class="total-price" name="total-price" type="text" readonly></td>
</tr>
<tr id="3">
<td>Burundi Mask</td>
<td><select class="quantity" name="quantity">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td><input class="each-price" type="text" name="each-price" value="30"></td>
<td><input class="total-price" name="total-price" type="text" readonly></td>
</tr>
</tbody>
</table>

First you have to add function which have to be call on document ready or as pure javascript document.onload()
Then you have to define a variable name for the price,
Then you have to get the value of your (#tishirt) and multiply it with the price get the result as a value for your text input in which the price display
Here is the script
<script type ="text/javascript">
document.onload=function(){
document.getElementById(#tishirt).onchange=function(){
var price=100 ;//only example price
var total=price*document.getElementById(#tishirt).value;
if (total>0){
document.getElementById(#total).value=total;
}
};
};
</script>
Don't forget to add id to your text box (#total)

Related

Using text instead of Select statement

I have a drop down box, this is populated with options that after selecting it shows hidden text by calling the function toggletDisplay() and sending the value of the option throug, I want it to be able to do the same but without the drop down box to select, using instead plain text with onclick() instead of onchange() or something similiar.
Current Code
<form id="criteria" name="criteria">
<table width="200px" height="700px" name="criteria_search" align="left" border="1" style="margin-right:70px">
<tr>
<td class="dataLabel" width="100%" align="left"><strong>Add Rule : </strong>
<select name="rule" id="rule" onChange="toggletdDisplay(this.form);">
<optgroup label="Simple Rules">
<option value="instructions" selected="selected"> </option>
<option value="email">Email</option>
<option value="assigned">Assigned Racecourse</option>
</optgroup>
</select>
</td>
</tr>
</table>
<table align="right" border="1" width="300px" height="400px" style="float:left;">
<tr>
<td class="dataLabel" name="assigned" id="assigned" style="display: none;">
<table border="0">
<tr>
<td colspan="3"><h4>Assigned to Racecourse</h4></td>
</tr>
<tr>
<td style="margin-left:20px">
<b>Assigned To: </b><select name="selected_assigned_location" id="selected_assigned_location"></select>
</td>
</tr>
</table>
</td>
<td width="100px" class="dataLabel" name="email" id="email" style="display: none;" >
<table>
<tr>
<td colspan="3"><h4>Registered Email</h4></td>
</tr>
<tr>
<td><b>Do they have a registered Email Account?</b></td>
</tr>
<tr>
<td>
Yes <input type="radio" name="email_c" value="true_ex" {EMAIL_TEX_CHECKED} checked="checked"> No <input type="radio" name="email_c" value="false" {EMAIL_F_CHECKED}>
</td>
</tr>
</table>
</td>
...ect
I tried just sending the value through as an onclick
<td>
<p id="rule" name="rule" value="email" onclick="toggletdDisplay(this.form);">Email</p>
</td>
But I get an error of value rule is undefined. How would I send the value through the same as before but without using a select statement?
Added the toggletDisplay, simply uses the value sent back to change the style of the datalabel from hidden to inline
function toggletdDisplay(me)
{
list = Array("instructions","sex", "email", "mobile", "account", "age", "location", "spent", "booked_anything", "internet_booked", "package_type", "package_name", "booked_location", "new_booked_event", "booked_event_range","team", "no_reorder", "newsletter","hear_about","hear_about_bookings","mosaic_group","mosaic_type","assigned","assigned_user","lead_source","target_list","awc","birthday");
// hide any previously selected elements
for(x=0; x<list.length; x++)
{
deselect = getElementsByName_iefix("TD", list[x]);
for (j=0; j<deselect.length; j++)
{
deselect[j].style.display = "none";
}
}
// display currently selected criteria
selected = getElementsByName_iefix("TD", me.rule.value);
selected[0].style.display = "inline";
}
There seem to be a number of issues with your code. One of them is the undefined function toggletdDisplay() that is called whenever you change the selection in your select field.
But, basically, if you want to send a value of an input field or a select box within a form to a php script on your server you will need to define an action attribute in your <form> tag and make sure that the form is submitted. This can be achieved in your case by changing the onchange attribute in your select box (simplified code, without the table architecture):
Whenever you change the selection in your select box the form will be submitted and the value of that select box will be sent to target.php. The address line in your browser will show something like
...<your URL>/target.php?rule=email
It is also not clear to me why you use colspan attributes in some of your <td>-elements, as there is only one column to display in that table.
My advice is to be economical with "cut and paste" and only use code that you fully understand. Build your page slowly, step by step. That way you will be able to understand what needs to be fixed if something goes wrong.
Edit
With your toggletdDisplay() script we have something to work on. The first thing that springs to my mind is that you are not using jquery functions where they might be helpful. And secondly, you don't do anything to display the form values in the console window or send them to a php script.
It is also important to note that name attributes can only be assigned to <input> or <select> elements and not to <td> elements. In my following script I used the id attribute instead.
var tds,tdis;
$(function(){
var list = ["instructions","sex", "email", "mobile", "account", "age", "location", "spent", "booked_anything", "internet_booked", "package_type", "package_name", "booked_location", "new_booked_event", "booked_event_range","team", "no_reorder", "newsletter","hear_about","hear_about_bookings","mosaic_group","mosaic_type","assigned","assigned_user","lead_source","target_list","awc","birthday"];
// consider only TDs with IDs from list array:
tds= $('td').filter(function(i,el){return $.inArray(el.id,list)>-1;});
// trigger the display of results only for select and input elements within tds:
tdis=$('select,input', tds).on('change',listResults);
// assign the toggletdDispla function to the rule selector:
$('.action').on('change',toggletdDisplay);
});
function toggletdDisplay(){ tds.hide().filter('#'+this.value).show()}
function listResults(){
$('#show').html('<p>Values to be sent:</p>'+tdis.serialize().replace(/&/g,'<br/>'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="target.php">
<table name="criteria_search" align="left" border="1" style="margin-right:70px">
<tr><td class="dataLabel"><strong>Add Rule : </strong>
<select name="rule" id="rule" class="action">
<optgroup label="Simple Rules">
<option value="instructions" selected="selected"> </option>
<option value="email">Email</option>
<option value="assigned">Assigned Racecourse</option>
</optgroup>
</select>
</td><td class="dataLabel" id="email" style="display:none">
<b>email:</b>
<br/><label><input type="radio" name="email_c" value="true_ex"> yes</label>
<br/><label><input type="radio" name="email_c" value="false"> no</label>
<br/><label><input type="radio" name="email_c" value="soon"> not yet</label>
</td>
<td class="dataLabel" id="assigned" style="display:none">
Racecourse<br/>
<b>Assigned To: </b>
<select name="selected_assigned_location">
<option value=""></option>
<option value="a">racecourse A</option>
<option value="b">racecourse B</option>
<option value="c">racecourse C</option>
</select>
</td>
</tr>
</table>
</form><br style="clear:both" />
<div id="show"></div>

Iterating over checkboxes in jQuery

I have a table with check-boxes, a dropdown, and other accompanying data.
I'd like to iterate over the rows that have been checked, and pull it's data, add that data into a dictionary, then into a master array.
It seems to be finding the correct rows with check boxes, but my for loop is not pulling each row properly. Here is my js code:
$("#thechecked").click(function(){
var send_list = []
$('#mytable').find(':checkbox:checked').each(function () {
var dict = {};
var value = $("#presetChoosen").val();
var filename = $("#filename").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
FULL EXAMPLE IN JSFIDDLE
What am I doing wrong?
You should not use the same ids everywhere like you did on the select element. Id's elements are meant to be unique.
I've used some jQuery methods(parent(), find(), next()) to target the specific values:
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
Below is a working snippet of what you're trying to achieve:
$("#thechecked").click(function() {
var send_list = []
$('#mytable').find(':checkbox:checked').each(function() {
var dict = {};
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
tr,
td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td><input type="checkbox" /></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td id="filename_1">Underthesea</td>
<td>1920x1080</td>
<td> <select id="presetChoosen_1">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td id="filename_2">Overthehill</td>
<td>1280x720</td>
<td> <select id="presetChoosen_2" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td id="filename">Mocking</td>
<td>1280x720</td>
<td> <select id="presetChoosen" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>
You're re-using id attributes. IDs are supposed to be unique - and I believe it's actually a WC3 validation error to re-use the same ID in HTML.
You're also not scoping your selector to your checkbox at all.
Change your id="" to name="" and then try the following code concept:
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
var tr = $(this).closest('tr'),
filename = tr.find('[name="filename"]').val();
// [...]
});
Once you get the checkbox (inside the loop), then you need to get the row for that checkbox, eg:
$("#thechecked").click(function(){
var send_list = []
$('#mytable :checkbox:checked').each(function () {
var row = $(this).closest("tr");
var value = row.find("#presetChoosen").val();
var filename = row.find("#filename").text();
var dict = {};
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
bit hard to be 100% without your HTML (in the question) and it looks like you have elements with the same id, eg id='presetChoosen' on every row, which is advised against.
Like the accepted answer said, ids should be unique. What I would do is change filename and presetChoosen to classes instead, since they are a type of thing (class), not a particular thing (id). That way you could traverse the DOM in a more readable and easier to understand way:
$("#thechecked").click(function(){
var send_list = [];
$('#mytable').find(':checkbox:checked').each(function (index, checkbox) {
// Find the row this checkbox is in
var row = $(checkbox).closest('tr'),
value = row.find('.presetChoosen').val(),
filename = row.find('.filename').text();
send_list.push({
filename: filename,
value: value
});
});
console.log(send_list);
});
tr,td{border:1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td class="filename" >Underthesea</td>
<td>1920x1080</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td class="filename" >Overthehill</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td class="filename" >Mocking</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>

Dropdown box - onchange and onselect

I want help, i am very new to html..
On selecting option from dropdown menu, I want html to put the values in word..
e.g. When I select "1" from drop down, it must show "one"
When I select "2' from drop down, it must show "two"
How to do that??
<HTML>
<Table border=10>
<TR>
<TD>Select Number</TD>
<TD><Select>
<option>1</option>
<option>2</option>
<option>3</option>
</Select></TD>
</TR>
<tr>
<td>In Words</td>
<td><input type="text" readonly></td>
</tr>
</Table>
</HTML>
Please make a script and show me...
A non-jQuery solution:
Firstly, give your select- and input-tags id's, and your options values (value=""). Then add a onchange=""-listener in the select-tag and make a function that carries out what you want to do (i.e. checking the selected value and displaying it in your input field), like so:
function showValue() {
var x = document.getElementById("mySelect").value;
document.getElementById("mySelection").value = "You selected: " + x;
}
<Table border=10>
<tr>
<td>Select Number</td>
<td><Select onchange="showValue()" id="mySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</Select></td>
</tr>
<tr>
<td>In Words</td>
<td><input type="text" id="mySelection"></td>
</tr>
</Table>
If I understand what you want, you'll need some javascript to find what you selected, and take that 'string' and shove it in an element for the user to see.
Here is a working example. Try making one these next time you ask a question. Welcome to Stack Overflow.
http://jsfiddle.net/sheriffderek/6vp5Lskn/
HTML
<select name='my_select' id='my_select'>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
<option value='4'>Option 4</option>
<option value='5'>Option 5</option>
</select>
<div id="outcome">
You have selected: <span></span>
</div>
javascript (jQuery)
var selectedOption; // define this variable
// when the select is changed...
$('#my_select').on('change', function() {
// get the option that was selected
selectedOption = $( "#my_select option:selected" ).text();
// put the option in the place you want it
$('#outcome span').html(selectedOption);
});

School assignment onChange

I have a small problem that hopefully someone can help with. I am a student in a Web Programming Class, the instructor has given the assignment to: Add an "onChange" event handler to the shipping field in the form to run the "shipping_price()" function whenever the user changes the selected shipping method.
Here is the code he offered:
<td colspan="3" align="right"><span class="fmlabel">Shipping:</span>
<select name="shipping">
<option value="0">Select a Shipping Method
<option value="7.95">3-5 days ($7.95)
<option value="9.95">2 days ($9.95)
<option value="12.95">Next Day ($12.95)
</select>
</td>
What I put here is all the information he gave for this part of the assignment, any help would be great.
Edit:
I took the suggested help and put this in:
function shipping_price()
{
var ship=document.getElementById("shipping");
document.order.total.value=(shipping+sub_total);
}
<tr>
<td colspan="3" align="right"><span class="fmlabel">Shipping:</span>
<select name="shipping" onChange="shipping_price">
<option value="0">Select a Shipping Method
<option value="7.95">3-5 days ($7.95)
<option value="9.95">2 days ($9.95)
<option value="12.95">Next Day ($12.95)
</select>
</td>
<td><input class="numbers" name="sub8" id="sub8" size="7" value="0.00" disabled></td>
</tr>
This works if I change the value of the shipping field, but will not put the "option value=" into the shipping field.
There are many ways to do this .There are many site for reading deeply.The below is one of the method.When the value in the select is changed to the new value. Then the functionfirst() will call and the functionfirst() will the alert the selected value.
<script>
function functionfirst(){
var myselect = document.getElementById("shipping");
alert(myselect.options[myselect.selectedIndex].value);
}
</script>
<td colspan="3" align="right"><span class="fmlabel">Shipping:</span>
<select id="shipping" name="shipping" onchange="functionfirst()">
<option value="0">Select a Shipping Method</option>
<option value="7.95">3-5 days ($7.95)</option>
<option value="9.95">2 days ($9.95)</option>
<option value="12.95">Next Day ($12.95)</option>
</select>
</td>

Jquery: get name of option field

I am trying to copy a name of the selected html form option field to another field using jquery.
This is what i got now:
script
$(document).ready(
function()
{
//check for change on the categories menu
$('#categories').change(function() {
//get category value
name = $('#categories').text();
$('#name').val(name)
});
});
HTML
<form action="editcat.pnp" method="post" accept-charset="utf-8">
<table>
<tr>
<td><label for="category">Category:</label></td><td><select name="category_id" id="categories">
<option value="1">Info</option>
<option value="2">Resr</option>
<option value="3">Pro</option>
<option value="4">Geo</option>
<option value="5">Site's</option>
<option value="6">Well</option>
<option value="7">Link</option>
<option value="#" selected="selected">Please select</option>
</select></td>
</tr>
<tr>
<tr>
<td><label for="name">Name:</label></td><td><input name="name" type="text" size="40" maxlength="40" id="name"></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Update"> <input type="reset"></td>
</tr>
</table>
</form>
The problem is that the name field now contains all the names from the option dropdown list and not only the one i selected.
You should use :selected Selector to get selected option, and then .text() to get its name.
var name = $('#categories option:selected').text();
try this....
$(document).ready(
function()
{
//check for change on the categories menu
$('#categories').change(function() {
//get category value
name = $("#categories option:selected").text();
$('#name').val(name)
});
});
Hope its help
I think you are looking to use $("#categories").val() instead of .text().
Example: http://jsfiddle.net/shanabus/wZAM7/
Read jQuery Docs and shown Examples in the .change() function.

Categories