Make <div> to display only 2 decimals after whole numbers in javascript - calculator

I know this kind of topic has been asked several times but non of the answers that I had found had worked with my javascript code. Everything in my page is fine. The web page that I have is about shopping list but not including the product name because there's no space in the web page for that, just for the price and tax, a calculator and to be used in a cell phone because is the cell phone the device that you can use in a supermarket. You make the price additions on the left column and write down the taxes in the right column. The total price is displayed in a <div> that is at the top of the page says 0 in red color. Like I expressed before, everything in the page is fine, is just that I want that <div> to display only 2 decimal digits after whole numbers. Let say you type: 4.65 in one of the textboxes on the left column because that's the product price and .28 on the right column because that is the tax. (Now in FL tax is .07) So, the total instead of showing up 4.93 it shows 4.930000000000001 and that's annoying for me. The same thing also happens in the calculator but that's fine for me.
The shopping list web page is: https://keilita.neocities.org/shop-calc.htm Thank you.

The problem lies in the fact that floating point numbers are actually approximations (except in those cases when they're multiples of negative powers of two, e.g., .75, .125 and the like). You should be able to do something like total.toFixed(2) to get the desired result (note that you'd also need this for cases like 3.10 to display correctly).

<script language="javascript">
function bindFunctions() {
var input = document.getElementsByTagName("input");
for(var i=0; i<input.length;i++){
if(input[i].type == "number"){
input[i].onblur = onBlurFunction;
}
if(input[i].type == "submit"){
input[i].onclick = onClickFunction;
}
}
}
bindFunctions();
function onBlurFunction(){
var ttl=0;
var input = document.getElementsByTagName("input");
for(var i=0; i<input.length;i++){
if(input[i].type == "number"){
ttl += Number(input[i].value);
}
}
document.getElementById("totales").innerHTML=ttl;
}
function onClickFunction(){
var inputHolder = document.getElementById('input-holder');
var input = document.createElement('input');
var br = document.createElement("br");
input.type = "number";
inputHolder.appendChild(input);
inputHolder.appendChild(br);
bindFunctions();
}
</script>

Related

Storing appended elements to localStorage

I'm a teacher and creating a page to organize my lesson plans. There should be the ability to add new lessons (li) and new weeks (ul). The lessons are sortable between each of the weeks. Each newly added item will then be saved to localStorage.
So far, I'm able to create the lessons and new weeks. The sortable function works. The save function works... except that it will not save any of the new weeks (ul). When I refresh, the new lessons (li) are still on the page, but the new weeks (ul) are gone.
$("#saveAll").click(function(e) {
e.preventDefault();
var listContents = [];
$("ul").each(function(){
listContents.push(this.innerHTML);
})
localStorage.setItem('todoList', JSON.stringify(listContents));
});
$("#clearAll").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
loadToDo();
function loadToDo() {
if (localStorage.getItem('todoList')){
var listContents = JSON.parse(localStorage.getItem('todoList'));
$("ul").each(function(i){
this.innerHTML = listContents [i];
})
}
}
I created a fiddle here.
You can click the "Add New Week" button and then click the "Create Lesson" button and drag the new lesson into one of the weeks. After clicking "Save All", only the first week is saved.
I can't seem to figure out what's missing.
It's saving correctly, but since the page only has one <ul> element initially, that is the only one that gets populated in loadToDo(). (listContents has more than one element, but $("ul").each(...) only iterates over one element.)
There is a quick band-aid you can use to resolve this. Refactor your #new-week-but click handler into a named function:
function addNewWeek() {
var x = '<ul class="sortable weeklist"></ul>';
$(x).appendTo('.term').sortable({connectWith: '.sortable'});
}
$('#new-week-but').click(addNewWeek);
Then add this block after you fetch the array from storage but before you enumerate the <ul> elements:
var i;
for (i = 2; i < listContents.length; ++i) {
addNewWeek();
}
This will add the required number of <ul> elements before attempting to populate them.
I chose to initialize i to two because this creates two fewer than the number of elements in listContents. We need to subtract one because there is a <ul> in .term when the page loads, and another because the <ul id="new-lesson-list"> contents also get saved in listContents. (Consider filtering that element out in your #saveAll click handler.)
(Note that this requires merging all of your $(document).ready() functions into one big function so that addNewWeek() is visible to the rest of your code.)
Suggestions to improve code maintainability:
Give each editable <ul> a CSS class so that they can be distinguished from other random <ul> elements on the page. Filter for this class when saving data so that the "template" <ul> doesn't get saved, too.
Remove the one default editable <ul> from the page. Instead, in your loadToDo() function, add an else block to the if block and call addNewWeek() from the else block. Also, call it if listContents.length == 0. This will prevent duplicating the element in the HTML source (duplication is bad!) and having to account for it in your load logic.
If you implement both of these then you can initialize i to 0 instead of 2 in my sample code, which is a lot less weird-looking (and less likely to trip up future maintainers).

How do I match two random numbers, then print match in xcode interface builder, using objective c

I am trying my first iphone app. I am stuck now. I have two label that display seperate random numbers. I used a button and IBAction to generate the numbers then pass them to the label. Now I need to determine when the two numbers match and then print "match" in another label. I am trying all kinds of different things but somehow I am missing something. If anyone can help explain how to do this form a code point of view and hooking it into interface builder that would be awesome! Thanks
In the method where you get and show the random numbers you simply compare them and change the text in the third label accordingly.
- (IBAction)buttonPressed {
// Generate the 2 random numbers and show them in the labels here.
// Then compare them and show the result in the third label:
if (randomNumber1 == randomNumber2) {
thirdLabel.text = #"Match";
} else {
thirdLabel.text = #"No Match";
}
}

How to get row values from a Rounded Rectangle List in Dashcode?

I am new to dashcode and trying to build a simple web app for iphone using it. My primary aim is to have a Rectangular List (I have used the "Rounded rectangle list"). It is a static list and has three rows. What I want is a website to open when user clicks on any of the row, and each row would have a different URL. I was able to add a Rounded rectangle list with three static rows like
The object ID is "list"
Row 1-- Label- "Gift Cards" , Value - "http://www.abcxyz.com/giftcard"
Row 2-- Label- "Toys" , Value - "http://www.abcxyz.com/toys"
Row 3-- Label- "Bikes" , Value - "http://www.abcxyz.com/bikes"
i added onclick even to call a java script function like below
function myButtonPressHandler(event)
{
var websiteURL = "http://www.abcxyz.com/giftcard";
location = websiteURL;
}
the above code opens the same URL "http://www.abcxyz.com/giftcard" when the user clicks on any of the three buttons, but what I want is to fetch the value of each child node (which would be their respective URLs) at runtime and open it using location = WebsiteURL something like below (did'nt work for me :( -
function myButtonPressHandler(event)
{
var websiteURL = document.getElementById("list").children;
var WebURL = websiteURL[???].value;
location = WebURL;
}
Any help would be appreciated.
Thanks
OK ... so figured out my own answer. The Rounded Rectangular list is actually a multidimensional array. so to get the value of each of the rows i.e. the Http URLs and open them on the browser when the rows were touched/tapped/pressed is as below.
function buttonpresshandler(event)
{
// Insert Code Here
var list = document.getElementById("list").object;
var selectedObjects = list.selectedObjects();
//Open webpage with the value of each label
location = selectedObjects[0][1];
}
Hurray!

drawing a path on google static map

I wrote this code in client side and sent to a server for a emailing purpose.in that email the image is appear as broken image I want to draw a path on google static map.here is the code I used.
<img src = "http://maps.googleapis.com/maps/api/staticmap?size=400x400&path=weight:3%7Ccolor:orange%7Cenc:'+polyline+'" />
polyline I created this way
var polyline;
var points = new Array();
for(var i=0; i<googleRoute.getVertexCount(); i++)
{
points[i] = new GLatLng(googleRoute.getVertex(i).lng(),googleRoute.getVertex(i).lat());
}
polyline = new GPolyline(points, '#ff0000', 5, 0.7);
when I used this code it will not appear the image.I wrote this code in client side and sent to a server for a emailing purpose.in that email the image is appear as broken image are there any wrong with my code?
when distance between two cities grows, the polyline variable will include lot of Glatlang values. so it causes to exceed the url character limit (What is the character limit on URL).
we can't send long url that exceed the charcter limit using ajax request. that's why I got that broken image.
As the solution I ignored intermediate Glatlang values by incrementing the for loop with skipping values. Therefore the polyline can be accepted for zoomed out maps.
If you have an array of points you can simply do:
$points = array('53.061969559518,-3.1661187796875', '52.647368106972,-2.6806604056641');
$pointsUrl = "";
for($i=0; $i<count($points); $i++) {
$pointsUrl .= '%7C'.$points[$i];
}
echo '<img src="http://maps.googleapis.com/maps/api/staticmap?path=color:0x0000ff%7Cweight:5'.$pointsUrl.'&size=270x256&maptype=roadmap&sensor=false" />';

find a div and store its name into a a variable

I have a div called album_number_xx (xx being digits).
this div contains another set of divs, each one representing an image with caption and other details.
I need to allow the user to reorder images by drag and drop, and then update the database with the new order.
using jQuery sortable and serialize, I'm able to get the sequence of images on update. But don't know how to get the album_id, (the xx in the name of the container div).
I though that maybe I can grab the name of that div, store it in variable and then cut the last digits, but don't know how to do it.
any ideas?
thanks,
Patrick
I don't know how you're grabbing the div name, but if you have it in a variable:
var albumId = divNameVariable.split('_')[2];
var name = $('div[id^=album_number]').attr('id');
var num = parseInt(name.substr(name.lastIndexOf('_') + 1));
Based on Scott Evernden answer you can do it on click event:
$(document).ready
(function()
{
var albums = $("div[id^='album_number']").click
(function()
{
var id = $(this).attr('id');
var numberId = id.substr(id.lastIndexOf('_') +1);
alert(numberId);
});
});