jQuery to iterate through table and select dropdown lists - javascript

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;
});
});

Related

Why is my array not appending as a new row in my table? when it does it is undefined? JavaScript / HTML

So as shown below, in the console it gives my all the data that has been entered, however it will not display as a new row. If i move the second function/for loop into the first, it only displays each value as undefined, which seems like progress. Why? and how can i fix this issue? (also when everything is in one function, it goes from 1 row, to three each time the button is clicked to submit the data)
var list = [];
function addAppointment() {
var appointmentData = {};
var inputDate = document.getElementById('date').value;
appointmentData.date = inputDate;
var inputStartTime = document.getElementById('startTime').selectedIndex;
appointmentData.startTime = inputStartTime;
var inputEndTime = document.getElementById('endTime').selectedIndex;
appointmentData.endTime = inputEndTime;
var inputSubject = document.getElementById('subject');
appointmentData.subject = inputSubject;
var inputVenue = document.getElementById('venue');
appointmentData.venue = inputVenue;
list.push(appointmentData);
}
console.log("list", list)
function addData(data) {
console.log(data)
const tbody = document.getElementById("tbody");
for (var i = 0; i < data.length; i++) {
var tr = document.createElement("tr");
tr.innerHTML = `
<td>${data[i].inputDate}</td>
<td>${data[i].inputStartTime}</td>
<td>${data[i].inputEndTime}</td>
<td>${data[i].inputSubject}</td>
<td>${data[i].inputVenue}</td>
`;
tbody.append(tr);
}
addData(list);
}
</script>
<title>Diary</title>
<h1 style="text-align: center;">Diary</h1>
<form>
<table bgcolor="#cccccc" cellpadding="5" cellspacing="0" align="center">
<tr>
<td align="right">Date</td>
<td><input type="date" id="date" size="10" min="2020-01-01"></td>
<td align="right">Start Time</td>
<td>
<select id="startTime">
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="05:00">05:00</option>
<option value="06:00">06:00</option>
<option value="07:00">07:00</option>
<option value="08:00">08:00</option>
<option value="09:00">09:00</option>
<option value="10:00">10:00</option>
<option value="11:00">11:00</option>
<option value="12:00">12:00</option>
<option value="13:00">13:00</option>
<option value="14:00">14:00</option>
<option value="15:00">15:00</option>
<option value="16:00">16:00</option>
<option value="17:00">17:00</option>
<option value="18:00">18:00</option>
<option value="19:00">19:00</option>
<option value="20:00">20:00</option>
<option value="21:00">21:00</option>
<option value="22:00">22:00</option>
<option value="23:00">23:00</option>
</select>
</td>
<td align="right">End Time</td>
<td>
<select id="endTime">
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="05:00">05:00</option>
<option value="06:00">06:00</option>
<option value="07:00">07:00</option>
<option value="08:00">08:00</option>
<option value="09:00">09:00</option>
<option value="10:00">10:00</option>
<option value="11:00">11:00</option>
<option value="12:00">12:00</option>
<option value="13:00">13:00</option>
<option value="14:00">14:00</option>
<option value="15:00">15:00</option>
<option value="16:00">16:00</option>
<option value="17:00">17:00</option>
<option value="18:00">18:00</option>
<option value="19:00">19:00</option>
<option value="20:00">20:00</option>
<option value="21:00">21:00</option>
<option value="22:00">22:00</option>
<option value="23:00">23:00</option>
</select>
</td>
</tr>
<tr>
<td align="right">Subject:</td>
<td><input type="text" id="subject" size="10"></td>
</tr>
<tr>
<td align="right">Venue:</td>
<td><input type="text" id="venue" size="10"></td>
</tr>
<tr>
<td valign="top" align="center">Priority</td>
<td><input type="radio" id="high" name="Priority" checked />High<br />
<td><input type="radio" id="medium" name="Priority" checked />Medium<br />
<td><input type="radio" id="low" name="Priority" checked />Low<br />
</td>
</tr>
</table>
<tr>
<td></td>
<td></td><input type="button" value="Add Appointment" onclick="addAppointment()" /></td>
</tr>
<hr>
<div>
<table align="center" width="80%" height="150px" cellpadding="1px" cellspacing="1px" border="1" id="table1">
<thead>
<tr>
<th width="50">Date</th>
<th width="20">Start</th>
<th width="20">End</th>
<th width="75">Subject</th>
<th width="60">Venue</th>
<th width="5">Priority</th>
</tr>
</thead>
<tbody id="tbody"> </tbody>
</table>
</div>
<tr>
<td></td>
<td></td><input type="reset" value="Randomise Appointments" onclick="shuffleAppointments()" /></td>
<td></td><input type="button" value="Sort Appointments" onclick="sortRecords()" /></td>
<td>by</td>
<td>
<select id="Date">
<option value="date">Date</option>
<option value="startTime">Start Time</option>
<option value="endTime">End Time</option>
<option value="subject">Subject</option>
<option value="venue">Venue</option>
<option value="priority">Priority</option>
</select>
</td>
</tr>
<hr>
<table>
<th width="50">Date</th>
<th width="20">Year</th>
<th width="20">Appointment</th>
</hr>
</table>
</form>
Review this bit:
var inputDate = document.getElementById('date').value;
appointmentData.date = inputDate;
var inputStartTime = document.getElementById('startTime').selectedIndex;
appointmentData.startTime = inputStartTime;
var inputEndTime = document.getElementById('endTime').selectedIndex;
appointmentData.endTime = inputEndTime;
var inputSubject = document.getElementById('subject');
appointmentData.subject = inputSubject;
var inputVenue = document.getElementById('venue');
appointmentData.venue = inputVenue;
selectedIndex on a SELECT element will return a number, so inputStartTime/inputEndTime will be numbers not times. Change .selectedIndex to .value
inputSubject and inputVenue both point to elements NOT their values. So, add .value to the end of both.
did you run addAppointment() first?
It also looks like you are calling addData(list) within the addData definition, is this on purpose?
I recon this would do it:
fucntion addAppointment (){
var list = [];
function getDataFromSubmit() {
var appointmentData = {};
var inputDate = document.getElementById('date').value;
appointmentData.date = inputDate;
var inputStartTime = document.getElementById('startTime').selectedIndex;
appointmentData.startTime = inputStartTime;
var inputEndTime = document.getElementById('endTime').selectedIndex;
appointmentData.endTime = inputEndTime;
var inputSubject = document.getElementById('subject');
appointmentData.subject = inputSubject;
var inputVenue = document.getElementById('venue');
appointmentData.venue = inputVenue;
list.push(appointmentData);
}
function addData(data) {
console.log(data)
const tbody = document.getElementById("tbody");
for (var i = 0; i < data.length; i++) {
var tr = document.createElement("tr");
tr.innerHTML = `
<td>${data[i].inputDate}</td>
<td>${data[i].inputStartTime}</td>
<td>${data[i].inputEndTime}</td>
<td>${data[i].inputSubject}</td>
<td>${data[i].inputVenue}</td>
`;
tbody.append(tr);
}
}
getDataFromSubmit()
console.log("list", list)
addData(list);
}
Try this script instead:
var list = [];
let appointment = {
date: "",
startTime: "",
endTime: "",
subject: "",
venue: "",
rowData: function () {
return "<tr><td>" + this.date + "</td><td>" + this.startTime + "</td><td>" + this.endTime + "</td><td>" + this.subject + "</td><td>" + this.venue + "</td></tr>";
}
}
function addAppointment() {
let thisAppointment = Object.create(appointment);
thisAppointment.date = document.getElementById('date').value;
thisAppointment.startTime = document.getElementById('startTime').value;
thisAppointment.endTime = document.getElementById('endTime').value;
thisAppointment.subject = document.getElementById('subject').value;
thisAppointment.venue = document.getElementById('venue').value;
list.push(thisAppointment);
let tbody = document.getElementById("tbody");
tbody.innerHTML += thisAppointment.rowData();
}
This creates an object called appointment and defines some properties for it - including a function to output the tr/td row data.
The addAppointment() function creates a new instance of this object, populates it with the new data and updates the innerHTML of the "tbody" element with the rowData() value.

Jquery retrieve form selected option text and print table

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.

html jquery move items from listbox to other listbox then move items up and down

I have listbox and I can move items to another listbox with this code
$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
});
});
<select multiple="multiple" name="listbox1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
>><br/>
<<
<select multiple="multiple" name="listbox2" id="select2"></select>
With the code above I can move items from listbox1 to listbox2 and everything works fine.
I need to move items in listbox2 up and down
I googled and found that javascript code but I don't know how I can use it for listbox2 only
https://jsfiddle.net/m0f757wh/
Refer to this question.
I just added event listeners to the buttons and followed the above post. I think the code is self-explanatory. Let me know if you're confused.
$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
});
let $select1 = $('#select1');
let $select2 = $('#select2');
$('#up1').click(function () {
let $selected = $select1.find('option:selected');
$selected.insertBefore($selected.prev());
});
$('#down1').click(function () {
let $selected = $select1.find('option:selected');
$selected.insertAfter($selected.next());
});
$('#up2').click(function () {
let $selected = $select2.find('option:selected');
$selected.insertBefore($selected.prev());
});
$('#down2').click(function () {
let $selected = $select2.find('option:selected');
$selected.insertAfter($selected.next());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select multiple="multiple" name="listbox1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
>><br/>
<<
<select multiple="multiple" name="listbox2" id="select2"></select>
</td>
</tr>
<tr>
<td>
<button id="up1">↑</button>
<button id="down1">↓</button>
</td>
<td>
<button id="up2">↑</button>
<button id="down2">↓</button>
</td>
</tr>
</table>

time tracker with jquery

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

How to select the td where my active element is in

I have got a table with a select option in it. After the select changes, the td's innerHTML should change to the selected value so the select disappears.
<table>
<tr>
<td>
<select onchange="update(param1, param2)">
<option value="Value 1">Value 1</option>
<option value="Value 1">Value 2</option>
</select>
</td>
</tr>
</table>
So, when I select Value 2, the table should look like this:
<table>
<tr>
<td>
Value 2
</td>
</tr>
</table>
How do I do this. I've tried things like parentNode, parent()..
It has to be javascript or jQuery.
function update(id, row) {
var val = document.activeElement.value;
var id = id;
var row = row;
if (val != '') {
$.post('../inc/helikopter_beheer.php', {val: val, id: id, row: row}, function(data) {});
$.post('../inc/gereedstelling_get_info.php', {id: id, rij: row}, function(data) {
var result = data.split(",");
// this.parents('id').innerHTML = result;
$(this).closest("td").html(result[0]);
alert(result[0]);
});
};
}
This is what I got. It's getting some data out of my database, turns it into result and i have to get result in my td instead of the select.
JQuery function that accomplishes it (once you've given your select element an id of mySelect):
$('#mySelect').on('change', function () {
var val = $(this).val();
$(this).parent().html(val);
});
JS Fiddle Demo
<table>
<tr>
<td>
<select id="wdm_select">
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Value 3">Value 3</option>
</select>
</td>
</tr>
</table>
<script>
$(document).ready(function() {
$("#wdm_select").on("change",function() {
var selected_val = $(this).val();
$(this).parent().html( selected_val );
})
})
</script>
here is demo
$(document).on('change','#foo',function(){
$(this).parent('td').html($(this).val());
$(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select id="foo">
<option value="">--Select--</option>
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
</select>
</td>
</tr>
</table>

Categories

Resources