Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-26-2012, 08:18 PM   PM User | #1
jamesy23
New to the CF scene

 
Join Date: Mar 2012
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
jamesy23 is an unknown quantity at this point
little JavaScript help please

Hi guys,

I'm working on a code at the moment which is like a book shop. I want the program to allow the user to enter a book name and price then add it and after adding the books and its corresponding price, the program should calculate the total price.

I have been working on this (so it is rough) but I think I have managed it bar one slight problem. The book name entered comes up as 'undefined' after adding to basket.
I've played about with it but still no luck.

Code:
<html>
<head>


<script type="text/javascript">

var bookname = new Array();
var bookprice = new Array();



//set functions for the book name entry

function insert1(value)
{
bookname[bookname.length]=value;
}



//set function for the book price entry

function insert2(value)
{
bookprice[bookprice.length]=value;
}


//display inserted name

function showname()
{
var string ="<b>Book Name</b><br>";

for(i = 0; i < bookname.length ; i++) 
{
	string = string +  bookname[i]+"<br>"; 
}

if (bookname.length)				
{
document.getElementById('myDiv1').innerHTML = string;				//if name is entered, show value entered on myDiv section
}
}



//display inserted price

function showprice()
{
var string="<b>Book Price</b><br>";

for(i = 0; i < bookprice.length ; i++) 
{
	string = string + " " + bookprice[i]+"<br>";
}

if(bookprice.length)
{
document.getElementById('myDiv2').innerHTML = string;
}
}



//set function to calculate the total price

function totalprice()
{
var total = 0;
for(var i = 0; i < bookprice.length; i++)
{
var thisvalue = parseFloat(bookprice[i]);							//decimal (allows pence cost as well (ie. £5.50))

if(!isNaN(thisvalue))												//!isNaN() = returns true if value is not a number
{
	total += thisvalue;
}
}

alert( "The total price is £"+total.toFixed(2));				//shows price to 2 decimal places
}


</script>
</head>


<body>

<h3>Book Purchase</h3>


<!--positions for book entry-->

<form name="form1">

<table width="407">
<tr>
<td width="154" align="right"><b>Book Name</b>
<td width="9"><b>&nbsp;:</b>
<td width="224">
<input type="text" name="name"/>
</tr>
<tr>
<td width="154" align="right">
<td width="9">
<td width="224">
</tr>
<tr>
<td width="154" align="right">
<td width="9">
<td width="224"> 


</tr>
</table>
</form>

<!--positions for book price-->

<form name="form2">

<table width="407">
<tr>
<td width="154" align="right"><b>Book Price :</b>
<td width="9"><b>&nbsp;£</b>
<td width="224">
<input type="text" name="cost"/>
</tr>
<tr>
<td width="154" align="right">
<td width="9">
<td width="224">
</tr>
<tr>
<td width="154" align="right">
<td width="9">
<td width="224"> 

<input type="button" value="Add To Basket" onclick="insert1(this.form.name.value),showname(); insert2(this.form.cost.value),showprice();"/> 		<!--the button comprimises of two functions (show both name and price together-->
</tr>

</table>
</form>


<tr>
<table width = 100% >
<td width = 300px>
<div id="myDiv1"></div> 
</td>

<td width = 300px>
<div id="myDiv2"></div> 
</td>
<td width 80%>
</td>

</tr>
</table>


<br><br><input type="button" value="Total Price" onclick="totalprice();" />					<!--button to calculate the total price added-->


<input type="button" Value="Print This Screen" onclick="window.print();"/> 						<!--button to print the window-->

  
</body>

</html>
I've put in little comments to help me as I am not an expert in this field and make it simpler for myself!
Can anybody suggest how I may solve this problem?

Any help is much appreciated!
jamesy23 is offline   Reply With Quote
Old 03-26-2012, 09:36 PM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,237
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
This is pretty clearly homework, so I'm not going to give you the full answer.

But let me recommend a couple of things:

(1) Use meaningful function names. insert1 and insert2 are meaningless.
(2) When operation on parallel arrays, operate on both at the same time.

So, in place of
Code:
//set functions for the book name entry
function insert1(value)
{
    bookname[bookname.length]=value;
}
//set function for the book price entry
function insert2(value)
{
    bookprice[bookprice.length]=value;
}
Better is:
Code:
function addNameAndPrice( name, price )
{
    bookname[bookname.length] = name;
    bookprice[bookprice.length] = price;
}
There are much better ways to do this than parallel arrays, but that's going to be beyond the level you are at now. But you can clearly do as shown, to be sure (for example) that you don't end up with 17 books and only 9 prices. Or vice versa.

**********

Now, to answer your real question:

You have *TWO* forms there!!! The "this.form" in your button is referring to the second <form>, but the name field is in the first <form>, so it can't be found.

You should ALMOST NEVER have two <form>s on a page. Get rid of the first </form> and the second <form>.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 03-26-2012, 09:40 PM   PM User | #3
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,437
Thanks: 52
Thanked 454 Times in 452 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
... what he said

Last edited by xelawho; 03-26-2012 at 09:46 PM.. Reason: needless repitition
xelawho is offline   Reply With Quote
Old 03-27-2012, 02:45 AM   PM User | #4
Mishu
Banned

 
Join Date: Mar 2012
Posts: 306
Thanks: 1
Thanked 28 Times in 28 Posts
Mishu can only hope to improve
Quote:
Originally Posted by jamesy23 View Post
Can anybody suggest how I may solve this problem?

Any help is much appreciated!
To me, you have more functions than are needed. I am assuming you are self teaching and this is not assesable work, so another way of doing it with less functions is

Code:
 <head>
        <script type="text/javascript">
            var bookname = new Array();
            var bookprice = new Array();

            //set functions for the book name entry

            function addBook(idBook,idPrice)
            {
                var strBookName = document.getElementById(idBook).value;
                var price = Number(document.getElementById(idPrice).value);
                if(strBookName == '' || price == 'NaN' || price <= 0){return;}
                bookname[bookname.length]=strBookName;
                bookprice[bookprice.length]=price;
                var string ="<b>Book Name</b><br>";
                for(i = 0; i < bookname.length ; i++) 
                {
                    string += bookname[i]+' '+bookprice[i]+"<br />"; 
                }
                document.getElementById('myDiv1').innerHTML = string;
            }

            //set function to calculate the total price

            function totalprice()
            {
                var total = 0;
                for(var i = 0; i < bookprice.length; i++)
                {
                    total += bookprice[i];
                }

                alert( "The total price is £"+total.toFixed(2));                //shows price to 2 decimal places
            }
        </script>
    </head>
    <body>
        <h3>Book Purchase</h3>
        <form>
            <table width="407">
                <tr>
                    <td width="154" align="right"><b>Book Name</b>
                    <td width="9"><b>&nbsp;:</b>
                    <td width="224">
                        <input type="text" name="txtName" id="txtName"/>
                </tr>
            </table>

            <table width="407">
                <tr>
                    <td width="154" align="right"><b>Book Price :</b>
                    <td width="9"><b>&nbsp;£</b>
                    <td width="224">
                        <input type="text" name="txtPrice" id="txtPrice"/>
                </tr>
                <tr>
                    <td width="154" align="right">
                    <td width="9">
                    <td width="224"> 
                        <input type="button" value="Add To Basket" onclick="addBook('txtName','txtPrice')"/> 
                </tr>
            </table>
        </form>

        <div id="myDiv1"></div> 

        <div id="myDiv2"></div> 

        <br><br><input type="button" value="Total Price" onclick="totalprice();" />                    <!--button to calculate the total price added-->

    </body>
But in the long run this would be easier and more flexible if you create a book object but don't worry aboiut that for now.
Mishu is offline   Reply With Quote
Reply

Bookmarks

Tags
array, book, div, javascript

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:21 AM.


Advertisement
Log in to turn off these ads.