Calculate the sum of DIV content - onclick

I have a form with several SELECT boxes and based on the user's selection a value appears. This is fully working.
Now I want a script that calculates the SUM of these values either automatically or when pressing a button.
The full code I have so far is this:
The JavaScript:
<script type="text/javascript">
window.onload=function(a,b)
{
value=document.getElementById('value1'),
combobox=document.getElementById('first');
combobox.onchange=function(a)
{
document.getElementById('value1').innerHTML = "€ " +this.value;
}
value2=document.getElementById('value2'),
combobox2=document.getElementById('second');
combobox2.onchange=function(b)
{
document.getElementById('value2').innerHTML = "€ " +this.value;
}
}
function changeText(){
var sum;
sum= (value * 1) + (value2 * 1);
document.getElementById('sum').innerHTML = "€ " +this.value;
}
</script>
The HTML:
<ol>
<li><label><span>First</span></label>
<select name="block1" id="first">
<option value="0">Please select...</option>
<option value="1">Summer</option>
<option value="2">Spring</option>
</select></li>
</ol>
<ol>
<li><label><span>Second</span></label>
<select name="block2" id="second">
<option value="0">Please select...</option>
<option value="1">Summer</option>
<option value="2">Spring</option>
<option value="3">Pink</option>
<option value="4">Corporate</option>
</select></li>
</ol>
<div id="value1">value 1</div>
<div id="value2">value 2</div>
<input type='button' onclick='changeText()' value='Calculate'/>
<div id="sum">Total here</div>
If anybody could help, that would be great. I really can't figure it out. Many many thanks!!

I've modified your JavaScript slightly to cater for the calculation, and now it works fine:
window.onload=function(a,b)
{
value=document.getElementById('value1'),
combobox=document.getElementById('first');
combobox.onchange=function(a)
{
document.getElementById('value1').innerHTML = "€ " +this.value;
}
value2=document.getElementById('value2'),
combobox2=document.getElementById('second');
combobox2.onchange=function(b)
{
document.getElementById('value2').innerHTML = "€ " +this.value;
}
}
function changeText(){
var sum;
div1Value = document.getElementById('value1').innerHTML.replace(/[^0-9]/g, '')*1;
div2Value = document.getElementById('value2').innerHTML.replace(/[^0-9]/g, '')*1;
sum = div1Value + div2Value;
document.getElementById('sum').innerHTML = "€ " +sum;
}​
Example here: http://jsbin.com/awici/2
However, I'd suggest you used some other approach, as this one is a bit flaky, and deal with numbers as strings.
A good approach, would be to store the values in hidden fields, and then simply calculate the values in there.
Hope this clear things out and helps you. Feel free to ask anything you don't understand

Related

Meteor helper function not returning changed Session value

I'm not getting the behavior I'm looking for. Say I've got a html template in Meteor called Teacher. It has two selectors, a 'week' selector and a 'sunday-lessons' selector (I've simplified the template somewhat here):
<template name="Teacher">
{{#each TeacherName}}
<div class="row">
<div class="input-field col s2 fullModal">
<select class="teacher-week-selector" id="week-selector">
<option value="Off" disabled selected>Week</option>
<option value="Week1">Week 1</option>
<option value="Week2">Week 2</option>
<option value="Week3">Week 3</option>
<option value="Week4">Week 4</option>
<option value="Week5">Week 5</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s1 fullModal">
<select id="sunday-lessons">
<option value="Off" disabled selected>{{sundayLesson}}</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
</select><label>SUN</label>
</div>
</div>
{{/each}}
</template>
In this case, {{#each TeacherName}} is returning ONE document since it returns an array with the document of interest in it.
I'm trying to get the behavior such that when the week selector is changed, it grabs the state of certain document properties in the database and inserts them into the sunday selector.
So I set a Session value first when the template renders:
Template.Teacher.onRendered(function () {
Session.set('WeekNumber', undefined);
});
Then in the events template I listen for the selector to change:
Template.Teacher.events({
'change #week-selector': function(){
var sselect = document.getElementById('week-selector').value;
Session.set('WeekNumber', sselect);
}
});
Then in the template helper I create a function that grabs the Session value and returns the value I want:
Template.Teacher.helpers({
sundayLesson: function () {
var lessonNum = Session.get('WeekNumber');
if (lessonNum === "Week1")
return Lessons.Week1.Sunday;
else if (lessonNum === "Week2")
return Lessons.Week2.Sunday;
else if (lessonNum === "Week3")
return Lessons.Week3.Sunday;
else if (lessonNum === "Week4")
return Lessons.Week4.Sunday;
else if (lessonNum === "Week5")
return Lessons.Week5.Sunday;
}
});
Even if I try to have the function return a primitive:
if (lessonNum === "Week1")
return 3;
Nothing happens. I'm expecting the 3 to be placed in the sunday-lesson selector at the moment the week selector is changed. I can see the value of the Session change if I put in alert(lessonNum), but the condition statements don't appear to be re-evaluating to return the different value. Not sure where I'm going wrong.
EDIT:
Interesting find. If I place the {{sundayLesson}} OUTSIDE the selector, I can get the reactive 3 value when the Session changes.
<p>{{sundayLesson}}</p> <!-- this works -->
<select id="sunday-lessons">
<option value="Off" disabled selected>{{sundayLesson}}</option> <!-- Doesn't work -->
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
</select><label>SUN</label>
The answer was found in the Materialize documentation. In order to update the selector dynamically, I needed to re-initialize the selector like this:
Template.Teacher.helpers({
sundayLesson: function () {
var lessonNum = Session.get('WeekNumber');
if (lessonNum === "Week1") {
$('select').material_select();
return Lessons.Week1.Sunday;
}
else if (lessonNum === "Week2") {
$('select').material_select();
return Lessons.Week2.Sunday;
}
else if (lessonNum === "Week3") {
$('select').material_select();
return Lessons.Week3.Sunday;
}
else if (lessonNum === "Week4") {
$('select').material_select();
return Lessons.Week4.Sunday;
}
else if (lessonNum === "Week5") {
$('select').material_select();
return Lessons.Week5.Sunday;
}
}
});
Sort of clumsy, but that's the solution.

How can i get a dropdownbox working with a css class?

I have a SelectList in the controller that its value passed to the view by ViewData to the view as below:
List<string> available = new List<string>();
available.AddRange(product.AvailableSizes.Split(',').ToList());
ViewData["availablesize"] = new SelectList(available);
in the view i have a drop down box which display the values of the variable availablesize as below:
#Html.DropDownList("availablesize")
for some reasons i need to display this drop down box in the following format but unable to handle this issue any suggestion?
<div class="product-page-options">
<div class="pull-left">
<label class="control-label">Size:</label>
<select class="form-control input-sm">
<option>L</option>
<option>M</option>
<option>XL</option>
</select>
</div>
</div>
This code must work, you can give css attributes as well in the razor syntax.
Also Make sure your ViewData["availablesize"] has IEnumerable<SelectListItem>
Change your controller code to below
ViewData["availablesize"] = new SelectList((IEnumerable)available);
in Views syntax must be like below
<div class="product-page-options">
<div class="pull-left">
<label class="control-label">Size:</label>
#Html.DropDownList("availablesize", ViewData["availablesize"], new {#class = "form-control input-sm "})
</div>
</div>
This is the syntax that you require
If you want to style each option differently, depending on the values passed, you can use some JQuery for that:
$(document).ready(function() {
$("#availablesize option").each(function() {
if ($(this).val() != '') {
switch ($(this).val()) {
case 'S':
$(this).css('background-color', 'lightgreen');
break;
case 'M':
$(this).css('background-color', 'green');
break;
case 'L':
$(this).css('background-color', 'orange');
break;
case 'XL':
$(this).css('background-color', 'red');
break;
default:
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="availablesize">
<option value="">- select size -</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
Fiddle

Set value of a select HTML element reactively with Meteor

I want to set the value of an HTML <select> element reactively, without changing the various options for the element. I have found a solution, but it in not elegant.
To test, create a barebones Meteor app with create meteor select and change the contents of the select.html and select.js files to the following:
select.html
<body>
{{> select}}
</body>
<template name="select">
<label for="select">{{category}}</label>
<select id="select">
<option value='' disabled selected style='display:none;'>Select...</option>
<option value="Animal">Animal</option>
<option value="Vegetable">Vegetable</option>
<option value="Mineral">Mineral</option>
</select>
</template>
select.js
if (Meteor.isClient) {
Session.set("category", "")
Session.set("label", "Category")
Template.select.onRendered(function () {
setSelectValue()
})
Template.select.helpers({
category: function () {
setSelectValue()
return Session.get("label")
}
});
function setSelectValue() {
var select = $("#select")[0]
if (select) {
select.value = Session.get("category")
}
}
}
Now launch your app. In the browser console, you can change the value of the category Session variable:
Session.set("category", "Animal")
However, the select element will not update until you change the label:
Session.set("label", "category") // was "Category'
Now the select element updates, and any subsequent change the category Session variable will also update the select element.
Session.set("category", "Vegetable") // Now the select element updates
Is it possible to achieve the same effect directly, without using this clumsy workaround?
Yes. You can do it as follows:
<select id="select">
<option value="Animal" {{animalSelected}}>Animal</option>
<option value="Vegetable" {{vegetableSelected}}>Vegetable</option>
<option value="Mineral" {{mineralSelected}}>Mineral</option>
</select>
And helpers that looks something like this:
Template.select.helpers({
animalSelected: function () {
return (someCondition === true) ? 'selected' : '';
},
vegetableSelected: function () {
return (someOtherCondition) ? 'selected' : '';
}
});
A better way might be something like this though:
<select id="select">
{{#each options}}
<option value="{{value}}" {{selected}}>{{label}}</option>
{{/each}}
</select>
And then you can use this in the helpers to decide what is selected and what isn't.
Another option is just using standard jQuery to change the select box. Something like this:
$('[name=options]').val( 3 );
Or this SO answer.
If you want the selection set dynamically I usually use a handlebar helper like this
Template.newtask.helpers({
filler: function(element){
return Session.get(element);
}
});
then in html
<select class="browser-default" id="selectedService" name="jobtype">
<option id="zero" value="{{filler 'type'}}">{{filler 'type'}}</option>

CSHTML - SQL QUERY....WHERE NAME=#NameOne

I'm using ASP.NET Razor.
<form style="display:inline" name="formular1" method="post" action="default.cshtml">
<select name="phone1" class="dropdown">
#foreach(var row in db.Query("SELECT * FROM Handy")){
<option value="#row.Handyname">#row.Handyname</option>
}
</select>
vs.
<select name="phone2" class="dropdown">
#foreach(var row in db.Query("SELECT * FROM Handy")){
<option value="#row.Handyname">#row.Handyname</option>
}
</select>
<input type="submit"/ value="Compare">
</form>
#{
var phoneOne = "";
var phoneTwo = "";
if(IsPost){
// request input of the select forms
phoneOne = Request["phone1"];
phoneTwo = Request["phone2"];
}
}
</div>
<div class="content">
<div class="start">
<p><h2>#phoneOne</h2></p>
<ul>
#{
if(IsPost){
foreach(var row in db.Query("SELECT * FROM Handy WHERE Handyname=#phoneOne")){
<li>processor: #row.Prozessor GHz</li>
<li>memory: #row.RAM MB Ram</li>
<li>weight: #row.Gewicht g</li>
<li>display: #row.Display ''</li>
<li>OS: #row.OS</li>
}
}
}
</ul>
</div>
Getting an error with the query: WHERE Handyname=#phoneOne ...leaving it out all works fine. What am I doing wrong?
Thanks:)!
Not very sure, but I think you need to replace this:
foreach(var row in db.Query("SELECT * FROM Handy WHERE Handyname=#phoneOne"))
With this:
foreach(var row in db.Query("SELECT * FROM Handy WHERE Handyname= " + phoneOne))
As described here, try the following:
foreach(var row in db.Query("SELECT * FROM Handy WHERE Handyname=##phoneOne")){
Is db a reference to the database component in Razor? If so, it uses #0, #1, (indexes) not named parameters instead.
foreach(var row in db.Query("SELECT * FROM Handy WHERE Handyname=#0"))
And pass in the value through the collection of parameters in that method too.

jquery reset conditional filter

I have 2 dropdown lists on my webform and using jquery trying to filter/reset filter 2nd dropdown elements based on 1st dropdown selection.
$(document).ready(function()
{
$('#dropdown1').change(function(e)
{
switch ($(this).val())
{
case "4":
//this removal works
$('#dropdown2').filter(function()
{
return ($(this).val() == 16);
}).remove();
break;
.................
default:
//how would I restore filter here?
}
}
});
Removing part works, so it filters item with no problem, but I have difficulty restoring the filter on dropdown 2 if something else is chosen in dropdown 1. I was trying to use .hide() and .show() instead of .remove() but it doesn't seem to work on IE6 at least.
At the start of your document ready take a copy of the values in dropdown2 like this:
var drp2values = $('#dropdown2').html();
then whenever you want to reset the values in dropdown2 to its original state do this:
$('#dropdown2').html(drp2values);
The actual value in the var will be something like :
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="16">16</option>
just tried it:
This code works:
$(document).ready(function()
{
var drp2values = $('#dropdown2').html();
$('#dropdown1').change(function(e)
{
switch ($(this).val())
{
case "4":
//this removal works... now ;)
$('#dropdown2').find('option').filter(function()
{
alert('in4 filt' + drp2values + $(this).val());
return ($(this).val() == 16);
}).remove();
break;
default:
//how would I restore filter here?
$('#dropdown2').html(drp2values);
}
});
});
With this HTML
<BODY>
<select id='dropdown1'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id='dropdown2'>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="16">16</option>
</select>
</BODY>
The original code you posted where you said the remove worked, it didnt remove the individual option with value 16, it removed the entire dropdown as you were not geting the options before you filtered, you were removing the dropdown :)
Hope this helps.

Resources