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.
Related
function random() {
document.querySelector('[name="stationerytype[]"]').value = ""
var a = document.getElementById('purpose').value;
if (a === "Meeting") {
var datalist = "datalist1";
} else if (a === "Departmental") {
var datalist = "datalist2";
}
document.querySelector('[name="stationerytype[]"]').setAttribute("list", datalist)
}
var options = document.querySelectorAll(".option1");
options.forEach(function(option) {
option.addEventListener("keyup", function() {
calculatingMinimunQuantity(option);
});
option.nextElementSibling.addEventListener('change', evt => {
if (+evt.target.value < +evt.target.min) evt.target.value = evt.target.min
});
});
function calculatingMinimunQuantity(option) {
var minimum = 0, step1 = 0;
var value = option.value;
if (value === "PENCIL") {
minimum = "5";
step1="5";
} else if (value === "NOTEPAD") {
minimum = "10";
step1="10";
}
// getting the quantity input field
option.nextElementSibling.setAttribute("min", minimum);
option.nextElementSibling.setAttribute("step", step1);
}
<div class="col-sm-6">
<label for="purpose">Purpose</label>
<select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required />
<option ></option>
<option value="Meeting">Meeting</option>
<option value="Departmental">Departmental</option>
</select>
</div>
<td><input type="text" name="stationerytype[]" id="stationerytype" class="option1 form-control" autocomplete="off" required>
<datalist id="datalist1" >
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
<option value="PENCIL">PENCIL</option>
</datalist>
<datalist id="datalist2" >
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="BMO LETTER HEAD">BMO LETTER HEAD</option>
</datalist>
</td>
<td><input type="NUMBER" name="stationeryqtyrqst[]" id="stationeryqtyrqst" class="form-control" required ></td>
I have a form that has two fields stationerytype and stationeryrqstqty.The stationeryrqstqtyfield of the form accepts the number. The minimum number which can be entered in this field(QTY) depends upon the value of the stationerytype field i.e. If the stationerytype field value is 'pencil' then the minimum value property of the stationeryrqstqty field should be 5 and if it is 'notepad' then the minimum property of the stationeryrqstqty field should be 10. I am doing it by the given code but it's not working.it gives always 1,2,3.......
<td><input type="text" name="slno" value= "<?php echo $i; ?>" class="form-control " readonly ></td>
<td><input type="text" name="stationerytype[]" id="stationerytype" class="option1 form-control" autocomplete="off" required>
<datalist id="datalist1" >
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
<option value="PENCIL">PENCIL</option>
</datalist>
<datalist id="datalist2" >
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="BMO LETTER HEAD">BMO LETTER HEAD</option>
</datalist>
</td>
<td><input type="NUMBER" name="stationeryqtyrqst[]" id="stationeryqtyrqst" class="form-control" required ></td>
<script>
var options = document.querySelectorAll(".option1");
options.forEach(function(option) {
option.addEventListener("keyup", function() {
calculatingMinimunQuantity(option);
});
option.nextElementSibling.addEventListener('change', evt => {
if (+evt.target.value < +evt.target.min) evt.target.value = evt.target.min
});
});
function calculatingMinimunQuantity(option) {
var minimum = 0, step1 = 0;
var value = option.value;
if (value === "PENCIL") {
minimum = "5";
step1="5";
} else if (value === "NOTEPAD") {
minimum = "10";
step1="10";
}
// getting the quantity input field
option.nextElementSibling.setAttribute("min", minimum);
option.nextElementSibling.setAttribute("step", step1);
}
</script>
I wont get in to details, of your workaround or anything, just hints on how to set min, max on an input,
using vanilla js, you can do this:
document.querySelector("input[name='stationeryqtyrqst[]']").setAttribute("min",10)
change the selector to whatever you want to, and update it accordingly,
this should work for input type=number, for inputs of other types, you should implement some value check on input/keydown/keyup event.
you can set max the same way.
The below lines are setting the attributes to the datalist tag and not the input tag.
option.nextElementSibling.setAttribute("min", minimum);
option.nextElementSibling.setAttribute("step", step1);
I changed it to select the correct tag and set default value as minimum:
let quantity_field = document.getElementById("stationeryqtyrqst");
if(quantity_field){
quantity_field.setAttribute("min", minimum);
quantity_field.setAttribute("step", step1);
quantity_field.value = minimum;
}
Attaching snippet for reference:
function random() {
document.querySelector('[name="stationerytype[]"]').value = ""
var a = document.getElementById('purpose').value;
if (a === "Meeting") {
var datalist = "datalist1";
} else if (a === "Departmental") {
var datalist = "datalist2";
}
document.querySelector('[name="stationerytype[]"]').setAttribute("list", datalist)
}
var options = document.querySelectorAll(".option1");
options.forEach(function(option) {
option.addEventListener("keyup", function() {
calculatingMinimunQuantity(option);
});
option.nextElementSibling.addEventListener('change', evt => {
if (+evt.target.value < +evt.target.min) evt.target.value = evt.target.min
});
});
function calculatingMinimunQuantity(option) {
var minimum = 0, step1 = 0;
var value = option.value;
if (value === "PENCIL") {
minimum = "5";
step1="5";
} else if (value === "NOTEPAD") {
minimum = "10";
step1="10";
}
// updated the below code to get the correct field and set default values.
let quantity_field = document.getElementById("stationeryqtyrqst");
if(quantity_field){
quantity_field.setAttribute("min", minimum);
quantity_field.setAttribute("step", step1);
quantity_field.value = minimum;
}
}
<div class="col-sm-6">
<label for="purpose">Purpose</label>
<select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required />
<option ></option>
<option value="Meeting">Meeting</option>
<option value="Departmental">Departmental</option>
</select>
</div>
<td><input type="text" name="stationerytype[]" id="stationerytype" class="option1 form-control" autocomplete="off" required>
<datalist id="datalist1" >
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
<option value="PENCIL">PENCIL</option>
</datalist>
<datalist id="datalist2" >
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="BMO LETTER HEAD">BMO LETTER HEAD</option>
</datalist>
</td>
<td><input type="NUMBER" name="stationeryqtyrqst[]" id="stationeryqtyrqst" class="form-control" required ></td>
in this table I need to get the total count of options having green value selected or red or yellow from the dropdown bar and show it on the green yellow re input boxes.
Html Code:
<td>
<select class="form-control col-md-6 " type="text" id="Zone" name="Zone">
{% for z in Zone %}
<option value="{{ z.ZoneName }}">{{ z.ZoneName }}</option>
{% endfor %}
</select>
</td>
Script code:
$(document).ready(function () {
$("#calculatebtn").on('click', function () {
Calculate();
});
});
function Calculate() {
// var green = $("tbody tr:visible td:select:nth-child(5):contains('Green')").length;
var tasks = $('#myTable tr').length - 1;
var green = parseInt($("#Green").val() * 20);
// console.log(green)
var yellow = parseInt($("#Yellow").val() * 10);
// console.log(yellow)
var red = parseInt($("#Red").val() * 5);
// console.log(red)
var help = parseInt($("#Help").val() * 10);
// console.log(help)
var notdone = parseInt($("#NotDone").val() * 20);
// console.log(notdone)
var bonus = $('input:checkbox:checked').length - 4;
// var bonus=parseInt($("#Bonus").val() * 20);
// console.log(bonus)
var result = green + yellow + red;
// console.log(result)
var total = (green + yellow + red + bonus) - (help + notdone);
// console.log(total)
var warpercent = (result / 100) * tasks;
document.getElementById("Green").value = green
document.getElementById("Total").value = total
document.getElementById("Bonus").value = bonus
document.getElementById("Score").value = result
document.getElementById("Total").value = total
document.getElementById("Game").value = game
}
Database Table
You can use .each loop to iterate through your selectbox . Inside this depending on the value add 1 to your variable and then add final result inside relevant box using .val().
Demo Code :
$(document).ready(function() {
$("#calculatebtn").on('click', function() {
Calculate();
});
function Calculate() {
var green = 0;
var yellow = 0;
var red = 0;
//loop through slect
$("select[name=Zone]").each(function() {
//check select value
if ($(this).val() == "Green") {
green = green + 1
} else if ($(this).val() == "Yellow") {
yellow = yellow + 1
} else {
red = red + 1
}
})
//add total..
$("#Green").val(green)
$("#Red").val(red)
$("#Yellow").val(yellow)
$("#Total").val(green + red + yellow)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="form-control col-md-6 " type="text" name="Zone">
<option value="Green">Green</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="form-control col-md-6 " type="text" name="Zone">
<option value="Green">Green</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="form-control col-md-6 " type="text" id="Zone" name="Zone">
<option value="Green">Green</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="form-control col-md-6 " type="text" id="Zone" name="Zone">
<option value="Green">Green</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="form-control col-md-6 " type="text" name="Zone">
<option value="Green">Green</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
</table>
<button id="calculatebtn">Calculate</button>
<br>Green
<input type="text" id="Green"><br> Yellow
<input type="text" id="Yellow"> <br> Red : <input type="text" id="Red"> <br> Total :<input type="text" id="Total">
I am creating a currency exchange website portal. However, I can't get my code to work properly. When I input a value (onkeyup and onchange), I need to calculate the exchange rate of the currency. All I get is a blank input or NaN.
Below is my code:
<div id="box">
<h2>Currency Converter </h2>
<table>
<tr>
<td>
<input id="fromAmount" type="text" size="15" value="1" onkeyup="convertCurrency();">
</td>
<td>
<select id="from" onchange="convertCurrency();">
<option value="ETH">ETHEREUM</option>
<option value="LTC">LITECOIN</option>
<option value="BCH">BITCOIN CASH</option>
<option value="BTC" selected>BITCOIN</option>
<option value="DASH">DASH</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="toAmount" type="text" size="15" value="" oninput="convertCurrency();">
</td>
<td>
<select id="to" onchange="convertCurrency();">
<option value="ETH" selected>ETHEREUM</option>
<option value="LTC">LITECOIN</option>
<option value="BCH">BITCOIN CASH</option>
<option value="BTC">BITCOIN</option>
<option value="DASH">DASH</option>
</select>
</td>
</tr>
</table>
</div>
And here is my javascript
function convertCurrency() {
var from = document.getElementById("from").value;
var to = document.getElementById("to").value;
var xmlhttp = new XMLHttpRequest();
var url = "https://coinlib.io/api/v1/coin?key=659b81f02b22b218&pref=" + to + "&symbol=" + from;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var result = xmlhttp.responseText;
var jsResult = JSON.parse(result);
var oneUnit = jsResult.price[from] / jsResult.price[to];
var amt = document.getElementById("fromAmount").value;
document.getElementById("toAmount").value = (oneUnit * amt).toFixed(2);
}
}
}
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
I have what I thought would be a simple task.
A table of drop down lists, and a text box at the end of each line.
All I want to do is loop through each row of the table, get the "hours dropdown value" and multiply by the "rate dropdown value" - and place the result in the text box.
I just keep getting undefined when trying to get the dropdownlist values.
My HTML is:
<table class="hours-table">
<tr>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Date Total</th>
</tr>
<tr>
<td>
<select id="HoursSelected1" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected1" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
<tr>
<td>
<select id="HoursSelected2" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected2" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
<tr>
<td>
<select id="HoursSelected3" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected3" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
</table>
<p><a class="calculate" href="#" title="calculate row">Calculate</a>
</p>
My jQuery is:
$(document).ready(function () {
$('.calculate').on('click', function () {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours').val();
var rate = $(this).find('select.rate').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
});
return false;
});
});
Can anyone see where I've gone wrong please? There is a fiddle here: http://jsfiddle.net/Lr5pq/26/
Thank you, Mark
You have 2 problem in your code, first is neglecting the first row (the header row in the table) in your calculation, second using return false; which is deprecated and we use e.preventDefault();, instead, you can fix them like:
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours').val();
var rate = $(this).find('select.rate').val();
if (hours !== undefined && rate !== undefined) {
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
}
});
e.preventDefault();
BTW, if I were I would changed it like:
$(document).ready(function () {
$('.calculate').on('click', function (e) {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours>option:checked').val();
var rate = $(this).find('select.rate>option:checked').val();
//this is for your header row
if (hours !== undefined && rate !== undefined) {
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
}
});
e.preventDefault();
});
});
as you see, we can use :checked instead of :selected, to select the selected option in a select node.
and it is your working jsfiddle
Try this:
$(document).ready(function () {
$('.calculate').on('click', function () {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours > option:selected').val();
var rate = $(this).find('select.rate > option:selected').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
});
return false;
});
});