What I have so far is a table where a user can input their hours,minutes,activity name, and the category of that activity. A user can add/delete rows as they see fit.
What I need to accomplish is, when the user clicks the "Calculate" button it will add the hours/minutes and then store the input value in "activity" and "category".
Here is a Fiddle of what I have so far. http://jsfiddle.net/os214gru/
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>English Styles Test</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.17.2/build/cssreset/cssreset-min.css">
<link href="http://explore.hawkeslearning.com/portal/content/css/learn_content_styles.css" rel="stylesheet">
<link href="css/form-styles.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
// if Google is down, it looks to local file...
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='js/jquery-1.11.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="js/clone-form-td.js"></script>
</head>
<body>
<!-- https://jqueryui.com/dialog/
http://www.jacklmoore.com/notes/jquery-modal-tutorial/ -->
<div id="screenContainer">
<div id="screenContainerEng">
<div class='budgetForm-ENG'>
<form action="#" method="post" id="BudgetFormEng">
<table>
<thead>
<tr>
<th colspan='4'>Time Budget Calculator</th>
</tr>
<tr>
<th id='hourLabel'>Hour</th>
<th id='minuteLabel'>Minutes</th>
<th id='activityLabel'>Activity</th>
<th id='categoryLabel'>Category</th>
</tr>
</thead>
<tbody>
<tr id="CloneRow">
<td>
<input class="input_hr" type="number" value="0" name="ID_hour" id="ID_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID_min" id="ID_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input type="text" name="ID_act" id="ID_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID_cat" id="ID_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr id="CloneRow0">
<td>
<input class="input_hr" type="number" value="0" name="ID0_hour" id="ID0_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID0_min" id="ID0_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input type="text" name="ID0_act" id="ID0_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID0_cat" id="ID0_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr id="CloneRow1" class='clonedInput'>
<td>
<input class="input_hr" type="number" value="0" name="ID1_hour" id="ID1_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID1_min" id="ID1_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input class="input_act" type="text" name="ID1_act" id="ID1_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID1_cat" id="ID1_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr class='output'>
<th>Total:</th>
<td id='output' colspan='3'></td>
</tr>
</tbody>
</table>
<div id="addDelButtons">
<input type="button" id="btnAdd" value="add section" class='fontawesome-plus' aria-label="Add Row">
<input type="button" id="btnDel" value="remove section above" class='fontawesome-minus' aria-label="Remove Last Row">
<input type="button" id="btnRes" value="Reset form" aria-label="Reset Form">
<input type="button" id="btnCalc" value="Calculate" aria-label="Reset Form">
</div>
</form>
</div>
<p id='demo'></p>
</div>
</div>
</body>
</html>
This is the JS
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#CloneRow' + num).clone().attr({'id': 'CloneRow' + newNum}).addClass('addedRow').fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
/* This is where we manipulate the name/id values of the input inside the new, cloned element
Below are examples of what forms elements you can clone, but not the only ones.
There are 2 basic structures below: one for an H2, and one for form elements.
To make more, you can copy the one for form elements and simply update the classes for its label and input.
Keep in mind that the .val() method is what clears the element when it gets cloned. Radio and checkboxes need .val([]) instead of .val('').
*/
// Title - select
newElem.find('.input_hr').attr('id', 'ID' + newNum + '_hour').attr('name', 'ID' + newNum + '_hour').val('0');
// First name - text
newElem.find('.input_min').attr('id', 'ID' + newNum + '_min').attr('name', 'ID' + newNum + '_min').val('0');
// Last name - text
newElem.find('.input_act').attr('id', 'ID' + newNum + '_act').attr('name', 'ID' + newNum + '_act').val('');
// Color - checkbox
newElem.find('.input_cat').attr('id', 'ID' + newNum + '_cat').attr('name', 'ID' + newNum + '_cat').val('');
// Insert the new element after the last "duplicatable" input field
$('#CloneRow' + num).after(newElem);
$('#ID' + newNum + '_title').focus();
// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel').attr('disabled', false);
// Right now you can only add 13 sections, for a total of 15. Change '13' below to the max number of sections you want to allow.
if (newNum == 13)
$('#btnAdd').attr('disabled', true).prop('value', "That's all, folks!"); // value here updates the text in the 'add' button when the limit is reached
});
$('#btnDel').click(function () {
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
{
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#CloneRow' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "add section");});
}
return false; // Removes the last section you added
});
// Enable the "add" button
$('#btnAdd').attr('disabled', false);
// Disable the "remove" button
$('#btnDel').attr('disabled', true);
// Reset the entire form
$('#btnRes').click( function () {
{
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Do you really want to reset the form? All data will be lost."))
{
document.getElementById("BudgetFormEng").reset();
$('.addedRow').remove();
$('#output').empty();
};
return false;
};});
$('#btnCalc').click(function() {
var hours = $(".input_hr").serializeArray();
var minutes = $(".input_min").serializeArray();
var categories = $(".input_cat").serializeArray();
var blargh = [];
for(var i=0;i<categories.length;i++){
blargh.push({cat:categories[i].value,hour:hours[i].value,minute:minutes[i].value});//add object literal
}
/* jQuery.each(blargh, function (i, cat) {
console.log(i.value)
});
/* var totalHours = 0;
var totalMins = 0;
jQuery.each(hours, function( i, hours) {
totalHours += parseInt(hours.value) * 60
});
jQuery.each(minutes, function( i, minutes) {
totalMins += parseInt(minutes.value)
});
var totalTime = totalHours + totalMins;
var realMin = totalTime % 60;
var realHour = Math.floor(totalTime / 60);
$('#output').empty();
$('#output').append(realHour + ' hours, ' + realMin + ' minutes');*/
})
});
First: You'll save yourself MUCH time and work, if you use classes instead of id for your elements.
This solution works only, if you give your TR a class of trclass, your activity a class of "input_act" and the category a class of "input_cat"
I output the categories and activities on the console only, decide yourself what to do with it.
the actual calculating is rather easy:
$(function() {
$("#btnCalc").click(function(e) {
e.preventDefault();
calcIt();
});
}
function calcIt() {
var hours = 0;
var minutes = 0;
var activities = "";
var cats = "";
$(".trclass").each(function(index) {
hours += parseInt($(this).children("td").children(".input_hr").val());
minutes += parseInt($(this).children("td").children(".input_min").val());
activities += $(this).children("td").children(".input_act").val();
cats += $(this).children("td").children(".input_cat").val();
});
$("#output").html(hours+":"+minutes);
console.log(activities);
console.log(cats);
}
DEMO
Related
TL;DR: I want to be able to make a selection using currently-active HTML select box, when I have multiple select boxes with the same name, but only one of them is to be active at any one time.
--
My question is this - I have multiple filename select boxes, that upon submit, always send the value of the last select box that is at the bottom of HTML that has filename name in HTTP Request. I want to find a way to send only the filename that is associated with the currently-active a_XX_row box, and not any others.
i.e. I select id of 40, I should only see the box that says "A-40 Designer and Specs", and not the 800 box. When I press submit I want POST['filename'] to have the "A-40 Designer and Specs", but instead I always get the "A-800 Designer E.xlsm", because it is the last select in the HTML file.
$('#modelid').on('change', function() {
if (this.value == 40)
$('.a_40_row').show();
else
$('.a_40_row').hide();
if (this.value == 800)
$('.a_800_row').show();
else
$('.a_800_row').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--
<option value="40">40
<option value="800">800
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
don't show/hide selects form.
you just need to update the second select when the first is changed
the way to do that:
const
myForm = document.forms['my-form']
, filenames =
[ { model: '40', cod: 'A-40-B', fn:'A-40 Designer and Specs B.xlsm' }
, { model: '40', cod: 'A-40-A', fn:'A-40 Designer and Specs A.xlsm' }
, { model: '800', cod: 'A-800-E', fn:'A-800 Designer E.xlsm' }
]
myForm.modelid.onchange = () =>
{
myForm.filename.innerHTML = ''
filenames
.filter(x=>x.model===myForm.modelid.value)
.forEach( filename=>
{
myForm.filename.add( new Option(filename.fn,filename.cod))
}
)
}
select,
button {
display : block;
float : left;
clear : left;
margin : .3em;
}
select {
min-width : 8em;
padding : 0 .3em;
}
<form name="my-form">
<select name="modelid" >
<option value="" selected disable >--select--</option>
<option value="40" > 40 </option>
<option value="800" > 800 </option>
</select>
<select name="filename"></select>
<button type="submit">submit</button>
</form>
Two options,
Enable/disable the element as you show it.
Populate one field with what you need.
Option 1 :
$('#modelid').on('change', function() {
//Set visibility
$('.a_40_row').toggle(this.value == 40);
//Toggle disabled
$('.a_40_row [name=filename]').prop("disabled", this.value != 40);
$('.a_800_row').toggle(this.value == 800)
$('.a_800_row [name=filename]').prop("disabled", this.value != 800);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disabled>
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disbled>
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Option 2 : - This uses HTML 5 which has issues in IE 10 and less
$('#modelid').on('change', function() {
$(".row").show();
var selVal = $(this).val();
//Go through the options
$("[name=filename] option").each(function(){
//Dont use jquerys data here, it will convert to a number when it can
//Get array of values where can display from the data attribute
var arrDisplay = this.dataset.display.split(",");
//Add the hidden property if not contained in array -- wont work in IE 10 and older
$(this).prop("hidden", !arrDisplay.includes(selVal));
//Set a default
$(this).prop("selected", $(this).data("optiondefault") && !arrDisplay.includes(selVal) )
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option data-display="40" data-optiondefault="true">A-40 Designer and Specs B.xlsm</option>
<option data-display="40">A-40 Designer and Specs A.xlsm</option>
<option data-display="800" data-optiondefault="true">A-800 Designer E.xlsm</option>
<option data-display="40,800">Hybrid</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Tried all the answers on this q, but just can't get the count to display (or maybe the js to run?)
Here's my code .. I want the current count of selected items to update each time I select another
Any advice appreciated .. learning every day
<html>
<head>
<script type="text/Javascript">
function count_cars() {
var options = document.getElementById("cars").options, count = 0 ;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
} // end of for loop
// now put the current count in the element with id='car_count'
document.getElementById("car_count").innerHTML = count ;
} // end of function
</script>
</head>
<body>
<form name="test1" method="GET" action="test2.html">
How many cars have you got?
<table>
<tr><td>
<select multiple name="cars[]" value="" onchange="count_cars">
<option value="ford" >Ford </option>
<option value="saab" >Saab </option>
<option value="merc" >Merc </option>
<option value="audi" >Audi </option>
</select>
</td><td>Total : <div id="car_count"></div></td></tr>
<tr><td><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
You were trying to access the select list option by id - but the select did not have an id. Also - its better to indent your code in a more readable fashion.
function count_cars() {
var options = document.getElementById("cars").options, count = 0 ;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
} // end of for loop
document.getElementById("car_count").innerHTML = count ;
} // end of function
<form name="test1" method="GET" action="test2.html">
How many cars have you got?
<table>
<tr>
<td>
<select multiple id="cars" name="cars[]" value="" onchange="count_cars()">
<option value="ford" >Ford </option>
<option value="saab" >Saab </option>
<option value="merc" >Merc </option>
<option value="audi" >Audi </option>
</select>
</td>
<td>
Total : <div id="car_count"></div>
</td>
</tr>
<tr>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>
You can use the filter feature.
const options = document.getElementById("cars").options;
const count = [...options].filter(option => option.selected).length;
Don't forget to set an the cars id to your select.
You can use selectedOptions.
It contains a list of the elements contained within the element that are currently selected.
It is an HTMLCollection object with one entry per currently selected option
var count = document.getElementById("cars").selectedOptions.length;
and display it using
document.getElementById("car_count").innerHTML = count ;
I want to print the form with all the input values and selected option text. It works for the rest of the text and number inputs but the problem is with the select options. Whatever option is selected it only prints the first option from the dropdown (T4 + T4). I want it to print the text from the option that is selected
<div id="printContent">
<table border="1" class="css-serial" id="POITable">
<!-- Rand Titlu -->
<tr>
<th>Nr</th>
<th>Latime (mm)</th>
<th>Lungime (mm)</th>
<th>Cantitate</th>
<th>Material</th>
<th>Client</th>
<th>Suprafata (m2)</th>
<th>Total (€)</th>
<th>Sterge</th>
</tr>
<!-- Rand 1 formular -->
<tr class="item">
<td>1</td>
<td><input id="latime_sticla" type="number" class="form-control lat amount" value=""></td>
<td><input id="lungime_sticla" type="number" class="form-control lung amount" value=""></td>
<td><input type="number" class="form-control cant amount" value=""></td>
<td>
<select id="materialSticla" name="material" class="form-control price amount" onchange="calculPret()">
<option value="13.5">T4+T4</option>
<option value="14.5">T4+Low</option>
<option value="16.1">T4+4 Anotimpuri</option>
<option value="18.5">T4+P</option>
<option value="20.8">T4+Stopsol</option>
<option value="16.5">T4+Niagara Alb</option>
<option value="14.7">T4+Delta Alb</option>
<option value="15.5">T4+Diamant</option>
<option value="15.5">T4+Krizet</option>
<option value="16.5">T4+Cincilla Alb</option>
<option value="19.5">T4+Niagara Bronz</option>
<option value="19.5">T4+Delta Bronz</option>
<option value="19.5">T4+Cincilla Bronz</option>
<option value="19.8">Oglinda+Oglinda</option>
<option value="21.5">Oglinda+Mat Alb</option>
<option value="24.5">Oglinda+Mat Bronz</option>
<option value="24.21">T4+T4+4 Anotimpuri</option>
<option value="25.6">T4+4 Anotimpuri+Low</option>
<option value="26.8">T4+T4+Mat Alb</option>
<option value="27.8">T4+T4+Mat Bronz</option>
<option value="29.6">T4+4 Anotimpuri + Mat Alb</option>
<option value="30.6">T4+4 Anotimpuri + Mat Bronz</option>
</select>
</td>
<td><input type="text" class="form-control" value=""></td>
<td><input type="text" name="suprafata" class="form-control totals" id="totals" value=""readonly="readonly"></td>
<td><input type="text" name="total" class="form-control total" id="total1" value=""readonly="readonly"></td>
<td><input type="button" class="btn btn-danger" id="delPOIbutton" value=" - " onclick="deleteRow(this)"/></td>
</tr>
</table>
</div>
Here is the javascript
function calculPret() {
$(".item").each(function () {
var lat = 1;
var lung = 1;
var cant = 1;
var price = 1;
var total = 1;
if (!isNaN(parseFloat($(this).find(".lat").val()))) {
lat = parseFloat($(this).find(".lat").val());
}
if (!isNaN(parseFloat($(this).find(".lung").val()))) {
lung = parseFloat($(this).find(".lung").val());
}
if (!isNaN(parseFloat($(this).find(".cant").val()))) {
cant = parseFloat($(this).find(".cant").val());
}
if (!isNaN(parseFloat($(this).find(".price").val()))) {
price = parseFloat($(this).find(".price").val());
}
var arie = (lung * lat);
var arieM = (arie / 1000000);
var pretTotal = (arieM * price * cant);
total = pretTotal;
$(this).find(".totals").val(arieM.toFixed(2));
$(this).find(".total").val(total.toFixed(2));
});
var sum = 0;
$(".total").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var sumsuprafata = 0;
$(".totals").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sumsuprafata += parseFloat(this.value);
}
});
$("#totalSuprafata").val(sumsuprafata.toFixed(2));
$("#totalPret").val(sum.toFixed(2));
$("#TVA").val(sum.toFixed(2) * 0.19);
$("#totalPretTVA").val(parseFloat(sum.toFixed(2)) + parseFloat(($("#TVA").val())));
}
function printDiv() {
$('form input[type=number]').each(function() {
$(this).attr('value', $(this).val());
});
$('form input[type=text]').each(function() {
$(this).attr('value', $(this).val());
});
$("select").change(function() {
$(this.options[this.selectedIndex].text);
});
var divToPrint = document.getElementById('printContent');
newWin = window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
here is an example, the options were not T4+T4
I believe that your goal is to make sure that when you write the contents of the table to the new window, that the selected value will be selected in the new window.
So, in other words, you need to make sure that the 'selected' attribute exists on the <option> tag which was selected by the user.
So:
$('select').change(function() {
$(this.options).removeAttr('selected');
$(this.options[this.selectedIndex]).attr('selected', 'selected');
});
Explanation:
$(this.options).removeAttr('selected');
Removes the selected attribute from the previous choice, and
$(this.options[this.selectedIndex]).attr('selected', 'selected');
Adds the selected attribute to the new chosen <option>.
Hope this helps.
How do I go about getting an amount from a selected drop down box? For instance
var alertMessage = 'Thanks for the order ' + field1 + ' ' + field2 + '. Your total is $' + String(parseInt() * parseInt()) + '.00.';
alert(alertMessage);
Select a product:
<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>Select a quantitiy:
<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>Select a Shipping Method:
<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25</option>
</select>
I need to calculate an order total with the following constraints
a select box which incorporates a shipping method selection (values should be Standard - free; 3-day - $10; and Next Day - $25)
add 7% sales tax to any order.
Widget 1 is worth $5
Widget 2 is worth $10
I need it to take widget 1 or 2s cash value and multiply it by the quanitity selected, for this case lets just say 5, or 10. It then will add another amount for the shipping cost that is selected. With that it will add a tax of 7% and then sends you and alert message with final cost. I already have part of the final message started from my other code. In the below code field 1 and field 2 are the customers first and last name.
This is what I am trying to implement this for
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css"> <!-- links stylesheet -->
<h1>JS Order Form</h1> <!-- Heading -->
</head>
<body>
<script src="script.js"> <!--links js -->
</script>
<div align="center">
<form id="myForm">
<fieldset>
<legend>Personal Information:</legend> <!-- first Form with first and last name-->
First Name: <input type="text" id="field1" name="fname"><br><br>
Last Name: <input type="text" id="field2" name="lname"><br>
</fieldset>
</form>
</div>
<br>
<div align="center">
<form id="myForm1"> <!-- form 2-->
<fieldset>
<legend>Order Info:</legend>
<table style="width:100%">
<table align="left"> <!-- Setting table constraints-->
<table border="1">
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr>
<td>Widget 1</td> <!-- table contents-->
<td>$5</td>
</tr>
<tr>
<td>Widget 2</td>
<td>$10</td>
</tr>
</table>
<br>
<!-- form 2 with price and quanitity-->
<!--Price : <input type="text" id="field3" name="pname"><br><br>
Quantity: <input type="text" id="field4" name="qname"><br> -->
Select a product:<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>
Select a quantitiy:<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>
Select a Shipping Method:<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25 2</option>
</select>
</div>
</fieldset>
</form>
<div align="center">
<input type="button" onclick="myFunction();myFunction2() ;blankElement('productselection') ;blankElement('shippingselection') ;blankElement('quantityselection');" value="Clear"> <!-- submit and clear buttons-->
<input type="button" onclick="myFunction1()" value="Order">
</div>
function myFunction() {
document.getElementById("myForm").reset(); //grabs form and clears entrys
}
function myFunction2() {
document.getElementById("myForm1").reset(); // clears bottom form
}
function blankElement(id)
{
var element = document.getElementById(id);
element.value = blank;
}
function myFunction1()
{
var field1 = document.getElementById("field1").value.trim();
var field1Valid= true;
var field2 = document.getElementById("field2").value.trim(); // checks to see that a value is inputed
var field2Valid= true;
if ( field1.length == 0)
{
field1Valid= false;
} // the following checks to see if anything is inputed and returns a true or false/yes or no
if ( field2.length == 0)
{
field2Valid= false;
}
var formValid= field1Valid && field2Valid && field3Valid && field4Valid; //true if all fields are valid else false
if( !formValid){
var alertMessage= 'Please fill in the following '; //sets a var alert message if it meets criteria
if( !field1Valid){ alertMessage+= '[First Name] '; }
if( !field2Valid){ alertMessage+= '[Last Name] '; } // adds the following fields to the alert if they did not meet criteria of being full
alert(alertMessage);
return false;
}
else{
var alertMessage= 'Thanks for the order '+ field1+ ' '+ field2+ '. Your total is $'+ String(parseInt() * parseInt() )+ '.00.';
alert(alertMessage);
return true; // pushes out alert message by using field1 and field 2 and then multipling field 3 and 4 together to get a total
}
}
</body>
</html>
Check the below answer.
function Calculate() {
var f1 = document.getElementById("productselection");
var field1 = parseInt(f1.options[f1.selectedIndex].value);
var f2 = document.getElementById("quantityselection");
var field2 = parseInt(f2.options[f2.selectedIndex].value);
var alertMessage = 'Thanks for the order ' + field1 + ' x ' + field2 + '. Your total is $' + (field1 * field2).toFixed(2);
alert(alertMessage);
}
Select a product:
<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>Select a quantitiy:
<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>Select a Shipping Method:
<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25</option>
</select>
<br>
<br>
<button type="button" onClick="Calculate()">Calculate</button>
I really don't know how to do it. Is it possible to do this process?
I want to change the select option value based on the user input on the quant field
<input type="number" name="quant" id="quant" /> // for example I enter 2
<select name="shipment" disable>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option> //this must be selected
</select>
My actual code in php
<select name="shipment" id="">
<?php
foreach($shipment as $num => $price)
{
if($num != NULL || $price !=NULL)
{
?>
<option value="<?php echo "{$price}"?>">
<?php echo "{$price}"." for "."{$num}"." item";?></option>
<?php
}
}
?>
</select>
<h4 style="padding:0px;margin:0px;float:left;margin-top:10px;" class="col-md-3" >Quantity: </h4>
<div class="col-md-9" style="padding-left:0px;"><input type="number" name="quant" onblur="multiply.call(this,this.form.elements.price.value,this.form.elements.quant.value)"
min="1" max="10" placeholder="2" style="height:2em;margin:3px;"></div>
I have to make a simple calculation this is the price of the item:
<h4 style="padding:0px;margin:0px;float:left;" class="col-md-12" >Sale Price: ₱<font color='red'><?php $price= number_format(intval($shop_item_orig_price-($shop_item_orig_price*($shop_item_sale/100)))); echo $price;?> </font> </h4>
I will multiply it based on the quantity
<input type="number" name="quant" onblur="multiply.call(this,this.form.elements.price.value,this.form.elements.quant.value);myFunction(this.value)"
min="1" max="10" placeholder="2" style="height:2em;margin:3px;">
And then add the shipping fee based on the selected value.
I am showing you the simple demo for your question below:
UPDATE
function myFunction(quantValue)
{
var shipmentOption = document.getElementById("shipmentSelect");
shipmentOption.selectedIndex = quantValue - 1;
}
<input type="number" name="quant" placeholder="2" onblur="myFunction(this.value)"/>
<select name="shipment" id="shipmentSelect">
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option> //this must be selected
</select>
Explanation: The demo is with very simple logic of selectedIndex. So assuming that your entries would be searialized options. So if 1 is the input than select first option, 2 is the input select the second option,.... and so on.
Second Update:
JSFiddle:Demo
Hope that it help you.
HTML
<input type="number" name="quant" id="quant" />
<select name="shipment" disable>
<option value=""></option>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 4 item </option>
<option value="150"> 150 per 5 item </option>
<option value="150"> 150 per 2 item </option>
<option value="150"> 150 per 3 item </option>
</select>
JavaScript
document.getElementById('quant').addEventListener("change", function(){
multiply(this.form.elements.price.value,this.form.elements.quant.value);
var value = parseInt(this.value, 10),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
Using jQuery:
$(function() {
$('#quant').keyup(function() {
var text = $(this).val();
var select = $('select[name="shipment"]');
var option = select.find(':contains(' + text + ')');
if (option.length) {
select.val(option.attr('value'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quant" id="quant" />
<select name="shipment" disable>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option>
</select>
Sorry, don't know vanilla js solution.
An alternative
Create one attribute data-quantity in <option> tag. Give 1,2,3... value to it. And, in <script>, use change() or keyup() function.
<select name="shipment" id='selectbox'>
<option value="100" data-quantity="1"> 100 per 1 item </option>
<option value="150" data-quantity="2"> 150 per 2 item </option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.quantity').change(function(){
var quant= $('.quantity').val();
$("#selectbox").find("option[data-quantity=" + quant + "]").attr('selected', 'selected').siblings().removeAttr('selected');
});
});
</script>