Is there a way for this? What I want to happen is the hyperlinks from the left side will have sum totals, and so on and on the final page/tab, the summation of all the hyperlinks will be shown there. Here's a jsFiddle to better understand my point https://jsfiddle.net/nerdfighter/121myofn/1/
Here's the initial JavaScript code I wrote in adding the checked chekcboxes
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
window.onload = function() {
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
var new_total = parseFloat(document.getElementById('input').value);
console.log(new_total);
document.getElementById('input').value = new_total + add
}
}
}
</script>
This is just a small project and I don't I won't be using server-side.
There's no id="payment-total" nor id="input" elements in your jsFiddle. So it won't work.
The algorithm is looking correct. But I recommend to pay more attention to strict code formatting - that helps to avoid mistakes.
I've added the following lines and jsFiddle began to work:
<span id="payment-total">0</span>
<input id="input" value="0">
Update by comments:
// TODO: Start using addEventListener() instead
window.onload = function() {
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
// TODO: Consider state variables instead of parsing innerHTML
// TODO: Never miss semicolons. It works, but causes hard debug sometimes
total.innerHTML = parseFloat(total.innerHTML) + add
var new_total = parseFloat(document.getElementById('input').value);
console.log(new_total);
document.getElementById('input').value = new_total + add
// Per tab total calculation
var tabTotalEl = document.getElementById(this.dataset.tabTotalId);
tabTotalEl.innerHTML = parseFloat(tabTotalEl.innerHTML) + add;
}
}
}
Add sum elements like this
<span id="tab-vegetables-total">0</span>
Add data-tab-id="tab-vegetables-total" attributes to the checkboxes.
Related
I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.
as you can see here https://jsfiddle.net/kztnmm9o/ I am trying to check if the inputs are empty. If they are empty I want to display the div id="fehler", if every input has a value (must be a number, if not it shall display id="fehler" as well) I want to do the function. I am pretty new to javascript, might be a obvious mistake.
Thank you for your help!
This is the orignal javascript code without checking the inputs, which works:
var selectors = document.querySelectorAll("#eing1, #eing2, #eing3");
for (var i = 0; i < selectors.length; i++) {
selectors[i].addEventListener('keyup', function(event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById("button").click();
}
});
}
function ausgeben(){
var kostentisch = parseInt(document.getElementById("eing1").value)
var bruttogehalt = parseInt(document.getElementById("eing2").value)
var arbeitstage = parseInt(document.getElementById("eing3").value)
var stundenlohn = bruttogehalt/arbeitstage/8;
var arbeitszeit = arbeitstage*8;
var produktivitaetssteigerung = arbeitszeit*0.12;
var produktivitaetssteigerung2 = arbeitstage/produktivitaetssteigerung;
var gewinnprotag = produktivitaetssteigerung2*stundenlohn;
var amortisationszeit = Math.round(kostentisch/ gewinnprotag);
document.getElementById("arbeitszeit").innerHTML=arbeitszeit + " Stunden";
document.getElementById("produktivitaetssteigerung").innerHTML=produktivitaetssteigerung + " Stunden";
document.getElementById("amortisationszeit").innerHTML=amortisationszeit + " Tage";
}
updated fiddle: https://jsfiddle.net/kztnmm9o/3/
Changed the testing to this:
var test = document.querySelectorAll('input[type="text"]');
var error = false;
for (var i = 0; i < test.length; ++i) {
if (test[i].value == "")
{
test[i].style.borderColor = "red";
error = true;
}
}
I also made some minor changes following this logic, but it should be pretty simple to understand.
I also added this.style.borderColor = "transparent"; to keyup event but I'm not sure whether you like or not. So change on will.
I have a form that I want to track any changes. Right now I have it set so when the user exits the page, an alert box displays saying how many changes were made to the form. However, it keeps registering 0. I've tested with adding an alert to the inputChanges function telling me a change has occurred and the alert fires, but the count still registers as 0 when I exit the page...
Here's my script:
window.onload = function() {
var totalChanges = "";
var inputHandles = 0;
var selectHandles = 0;
var textAreaHandles = 0;
window.onbeforeunload = function(){
alert("Total Form Changes:" + totalChanges);
}//onbeforeunload
var totalChanges = inputHandles + selectHandles + textAreaHandles;
function inputChanges() {
inputHandles++;
alert("Change");
}
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; i++){
inputs[i].onchange = inputChanges;
}
function selectChanges(){
selectHandles++;
}
var selects = document.getElementsByTagName("select");
for (i = 0; i < selects.length; i++){
selects[i].onselect = selectChanges;
}
function textAreaChanges(){
textAreaHandles++;
}
var textAreas = document.getElementsByTagName("textarea");
for (i = 0; i < textAreas.length; i++){
textAreas[i].onchange = textAreaChanges;
}
}//Onload
You declare totalChanges here:
var totalChanges = "";
...and then re-declare it here:
var totalChanges = inputHandles + selectHandles + textAreaHandles;
...at which point the things you're adding up are all 0.
You need to do that calculation at the point where you need the value:
window.onbeforeunload = function(){
totalChanges = inputHandles + selectHandles + textAreaHandles;
alert("Total Form Changes:" + totalChanges);
}
Or set totalChanges = 0 initially and then increment it every time the other variables change, but that's clunkier.
Note also that you're not tallying the number of fields that now have values different to their starting values, you're tallying the number of individual edits. So if the user changes a field twice with the second change being back to the original value your code will track that as two changes (when logically it's kind of zero changes).
Since the user can change values back to what they were, I suggest you compare all input.value with input.defaultValue and check select.options[select.selectedIndex]defaultSelected
also you might want to move the } and the alert to after the sum of total changes
something like this
window.onload = function() {
var totalChanges = 0;
window.onbeforeunload = function(){
var inputs = document.getElementsByTagName("input"); // ditto for "textarea"
for (var i = 0; i < inputs.length; i++){
totaChanges += inputs[i].value != inputs[i].defaultValue;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++){
totalChanges += !selects[i].defaultSelected;
}
alert("Total Form Changes:" + totalChanges);
}//onbeforeunload
}
I want to fill a dropdown list and I've written the following code:
<script language="JavaScript1.2">
window.onload = fillDropDown();
function fillDropDown() {
var ddl = document.getElementById("dia");
var theOption = new Option;
var x;
var i;
for(i = 1; i < 32; i++) {
x = i + 1;
theOption.text = x;
theOption.value = x;
ddl.options[i] = theOption;
}
}
</script>
<body>
<form>
<select id=dia></select>
</form>
<body>
It isn't working, any idea why?
You have some errors in your code.
1. The first common mistake is the following:
window.onload = fillDropDown();
This previous code is registering the result of the called function fillDropDown and then assigning its results into window.onload. Thus, this will never do something. To register an event you have to assign a function not the result of a called function. The difference is this:
window.onload = fillDropDown; // Without the parentheses.
2. Another mistake I found, is about the creation of the option element. The better way to create HTML element in JavaScript is using the almost-standard document.createElement function.
3. Also your HTML markup has an error. Your select is written: <select id=dia></dia> and it should be <select id="dia"></select>;
So, with all theses changes highlighted the resulting code will be like this:
window.onload = fillDropDown;
function fillDropDown() {
var ddl = document.getElementById("dia");
var theOption;
var x;
var i;
for (i = 1; i < 32; i++) {
x = i + 1;
theOption = document.createElement('option');
theOption.label = x;
theOption.value = x;
ddl.add(theOption, null);
}
}
And it works like a charm. You can see it in action in this live demo: http://jsfiddle.net/dyjLS/
Note: I highly recommend to use a JavaScript library such as jQuery to do this, since it will deal with almost all the cross-browser inconsistencies. If you use it, your code will look like the following:
<script type="text/javascript">
jQuery( document ).ready( function($) {
var $select = $('#dia');
for ( var i = 1 ; i < 32 ; i++) {
var x = i + 1;
$select.append('<option value='+ x +'>'+ x +'</option>');
}
});
</script>
¡Voilà!
<script language="JavaScript1.2"> should be <script type="text/javascript">Also window.onload = fillDropDown(); should be window.onload = fillDropDown;
I have two working functions which I want to assign to two inputs:
<input type="text" id="start0" value="0" name="start[]" onkeyup="displayTotal();"/>
<input type="text" id="end0" value="0" name="end[]" onkeyup="displayTotal();"/>
I would like to be able to use a displayHoras(); onkeyup for those two too. (2 many 2s on this thread already). when I use displayHoras(); instead of displayTotal(); it works, but when I call both of them like this it doesnt:
<input type="text" id="start0" value="0" name="start[]" onkeyup="displayTotal();displayHoras();"/>
<input type="text" id="end0" value="0" name="end[]" onkeyup="displayTotal();displayHoras();"/>
Any help will be welcomed.
I'll share the code of both functions because...who knows? The problem might be there, right?
function displayTotal()
{
var tableRows = document.getElementById('budgetTable').getElementsByTagName('tr');
var totalDays = tableRows.length - 3; //Don't count the header rows and the Total rows
var totalPrice = 0;
var price = filterNum(document.getElementById( 'txtPrice' ).value);
var totalField = document.getElementById( 'txtTotal' );
var tempHours = 0;
var tempTotal = 0;
for(var i = 0; i < totalDays; i++)
{
tempHours = document.getElementById("end" + i).value - document.getElementById("start" + i).value;
tempTotal = tempHours * price;
document.getElementById("total" + i).innerHTML = formatCurrency(tempTotal);
totalPrice += tempTotal;
}
totalField.value = formatCurrency(totalPrice*1.21);
}
function displayHoras()
{
var tableRows = document.getElementById('budgetTable').getElementsByTagName('tr');
var totalDays = tableRows.length - 3;
var tempHours = 0;
var tempTotal = 0;
for(var i = 0; i < totalDays; i++)
{
tempHours = document.getElementById("end" + i).value - document.getElementById("start" + i).value;
document.getElementById("totalHoras" + i).innerHTML = tempHours;
}
}
EDIT: I added the functions that create the table below.
function keyUpCall() {displayHoras(); displayTotal();}
function addRowToTable()
{
var tbl = document.getElementById('budgetTable');
var lastRow = tbl.rows.length - 4;
var iteration = lastRow;
var entry = iteration - 1; //because we started with day0, etc
var row = tbl.insertRow(lastRow);
// day cell
var cellDay = row.insertCell(0);
cellDay.appendChild(createInput('text','dia' + entry, '', keyUpCall, 'dia' + entry));
// start cell
var cellStart = row.insertCell(1);
cellStart.appendChild(createInput('text','start' + entry, 0, keyUpCall, 'start' + entry));
// end cell
var cellEnd = row.insertCell(2);
cellEnd.appendChild(createInput('text','end' + entry, 0, keyUpCall, 'end' + entry));
// precio unitario
var cellPrecioUnitario = row.insertCell(3);
cellPrecioUnitario.appendChild(createInput('text', null, '$36', null, null));
// total HOras
var cellTotalHoras = row.insertCell(4);
cellTotalHoras.id = 'totalHoras' + entry;
// total cell
var cellTotal = row.insertCell(5);
cellTotal.id = 'total' + entry;
}
function createInput(type, id, value, action, name)
{
var el = document.createElement('input');
el.type = type;
el.id = id;
el.value = value;
el.onkeyup = action;
el.name = name;
return el;
}
At this point, the action is not even attached for some reason.
Edit2: I SOLVED THE PROBLEM!!! IUPI!! it was this line:
var totalDays = tableRows.length - 3;
In the previous version of this form I was using 3 extra rows, my client got me to add a couple extra ones for Tax and without Tax result. I changed it to:
var totalDays = tableRows.length - 5;
And that fixed it!
You can create a single function that calls both functions
function function1(){
displayTotal();
displayHoras();}
I'd recommend creating a function that then calls your two functions, e.g.:
function handleKeyUp() { // Or `updateDisplay` or some such
displayTotal();
displayHoras();
}
Putting too much text within the onXYZ attributes is problematic (though I'm not immediately seeing why yours isn't working).
Off-topic 1: I'd also suggest hooking up event handlers using DOM2 methods (addEventListener on standards-compliant browsers, attachEvent on IE8 and below) rather than using DOM0 mechanisms like onXYZ attributes.
Off-topic 2: A JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others can help smooth over browser differences (and even bugs) like the event attachment stuff above, as well as providing lots of handy utility functionality. Totally optional, but using one helps you concentrate on what you're actually trying to do, without worrying about slightly different plumbing in various different browsers.
old school javascript ^^
try this instead of the attribute variant, and use bugzilla, or a javascript debugger
var checks_keyup = function() {
displayTotal();
displayHoras();
}
var inputs = document.getElementsByTagName('input');
for(var i=0;i<inputs.length;i++) {
if(/^(start|end)/.test(inputs[i].id))
inputs[i].onkeyup = checks_keyup;
}
Try calling second function withing the first function itself,
function displayTotal()
{
\\.....your code
displayHoras();
}