Jump to content
New account registrations are disabed. This website is now an archive. Read more here.

Recommended Posts

I'm having a minor problem with a calculator script. There's 2 text boxes where you input your 2 numbers, and a drop-box that has either +, -, *, or /.

I can't seem to figure out how to set it up, so I tried this method "what would I do in VB.NET?", "Use the IF..ELSE statement". One problem solved, new problem, no idea how to set up the IF..ELSE statement in java script.

 

Here's what it looks like for the math part....

 

	<script language="javascript" type="text/javascript">  
		function multiply()
		{  
		a=Number(document.frmSimpleCalculator.txtValue1.value);  
		b=Number(document.frmSimpleCalculator.txtValue2.value);  
		c=a*b;  
		document.frmSimpleCalculator.txtTotal.value = c; 	
		}  
	</script>

	<script language="javascript" type="text/javascript">  
		function btnCalculateTotal_Click()
		{   
		if (document.frmSimpleCalculator.ddlOperator.value == 1)
			{
				a = Number(input.txtValue1);  
				b = Number(input.txtValue2);
				c = a + b;
				document.frmSimpleCalculator.txtTotal.value = c; 	
			}	
		else if (document.frmSimpleCalculator.ddlOperator.value == 2)
			{
				a=Number(document.frmSimpleCalculator.txtValue1.value);  
				b=Number(document.frmSimpleCalculator.txtValue2.value);
				c=a-b;
				document.frmSimpleCalculator.txtTotal.value = c; 	
			}
		else
			{
			alert ("<b>Error</b>");
			}
	</script>

	<script type="text/javascript" language="javascript">  
		function btnClear_Click( )
		{ 
			document.frmSimpleCalculator.txtValue1.value = "0";
			document.frmSimpleCalculator.ddlOperator.value = "1";  
			document.frmSimpleCalculator.txtValue2.value = "0";  
			document.frmSimpleCalculator.txtTotal.value = "0";  
		}  
	</script> 

 

If I have to post the whole script, I will. I should mention that this is related to homework, so please don't give me the answer right off the bat, hints are nice though. I already tried googling this problem for 5 hours and found no answer, so..... yeah. The thing related to homework is the math set-up (input a + input b = answer c) the IF..ELSE is my way of trying to set-up the drop-box list for the operations.

 

Oh right, I'm using Notepad++ to type this out, if that helps out in anyway.

 

 

 

 

 

 

 

 

 

 

 

Edit: Oh yeah, forgot I asked for help on the Flash button....... Oops..... ^^' The button went well, sadly, had to change it around a bit. Sorry for not replying to it, hated that term.

Share this post


Link to post
Share on other sites

The forms use HTML, right?

 

I thought I would write a version myself, hopefully this is something like what you were after:

<form id='myForm'>
  <input id="txtValue1" type="text" />
  <select id="operator">
     <option value='0'>+</option>
     <option value='1'>-</option>
     <option value='2'>*</option>
     <option value='3'>/</option>
  </select>
  <input id="txtValue2" type="text" />
</form>
<div onClick="doCalculate()">Calculate</div>
<div id='showvalue'></div>

<script type="application/javascript">
function doCalculate()
{
//Note: the parseFloat function turn strings into numbers 
var txtValue1 = parseFloat(document.getElementById('txtValue1').value);
var txtValue2 = parseFloat(document.getElementById('txtValue2').value);
var myoperator  = document.getElementById('operator').value;

if(myoperator==0)//plus
{
	var final_value=txtValue1+txtValue2;
}else if(myoperator==1)//minus
{
	var final_value=txtValue1-txtValue2;
}else if(myoperator==2)//multiply
{
	var final_value=txtValue1*txtValue2;
}else if(myoperator==3)//division 
{
	var final_value=txtValue1/txtValue2;
}

//if the calculation cannot reutrn an arithmetic operation then show an error
if(isNaN(final_value))
{
	document.getElementById('showvalue').innerHTML='The was an error with your calculation.';
}else{
	document.getElementById('showvalue').innerHTML=final_value;
}

}
</script>

 

I uploaded it for you to show how it in action: http://www.rmxpunlimited.net/calculator.html

Share this post


Link to post
Share on other sites

No matter how long I googled, nothing looked close to this. I do have a question, how do I show the answer in a textbox, like txtTotal?

 

	            <!-- Total -->
            <label for="txtTotal"> Total: </label>
            <input type="text" id="Total" maxlength="5" readonly="readonly" /></input>

 

I managed to get the rest to work, but that's the one problem I seem to be having. Other then that, the math works, yay! (<- Obviously google has failed me)

 

Maybe it would help more if I showed you what the thing looks like, one second.

 

Calculator.jpg

 

I'm also using Styles for input[type=text] and input[type=button], hopefully the Style tags aren't messing anything up.

Share this post


Link to post
Share on other sites
I do have a question, how do I show the answer in a textbox, like txtTotal?

Try this:

document.getElementById('Total').value=document.getElementById('txtTotal').value;

 

That's the only question in that post, right?

 

I would never write it like this though, I use JQuery, so I really have no idea with regards to regular syntax :P

 

As for googling, its definitely there. But sometimes you need to determine what level of abstraction your search times are, it can be hard to find if your search is too broad.

Share this post


Link to post
Share on other sites

Try this:

document.getElementById('Total').value=document.getElementById('txtTotal').value;

 

That's the only question in that post, right?

 

I would never write it like this though, I use JQuery, so I really have no idea with regards to regular syntax :P

 

As for googling, its definitely there. But sometimes you need to determine what level of abstraction your search times are, it can be hard to find if your search is too broad.

JQuery? Never heard of it before.

That was the only question, but I think I inserted

document.getElementById('Total').value=document.getElementById('txtTotal').value;

incorrectly in the code. Maybe the problem is in the other half.

 

		<script type="application/javascript" language="javascript">
		function btnCalculateTotal_Click()
		{
			//Note: the parseFloat function turn strings into numbers 
			var txtValue1 = parseFloat(document.getElementById('txtValue1').value);
			var txtValue2 = parseFloat(document.getElementById('txtValue2').value);
			var myoperator  = document.getElementById('ddlOperator').value;

		if(myoperator==0)//plus
		{
               var final_value=txtValue1+txtValue2;
		}else if(myoperator==1)//minus
		{
               var final_value=txtValue1-txtValue2;
		}else if(myoperator==2)//multiply
		{
               var final_value=txtValue1*txtValue2;
		}else if(myoperator==3)//division 
		{
               var final_value=txtValue1/txtValue2;
		}

			//if the calculation cannot reutrn an arithmetic operation then show an error
		if(isNaN(final_value))
		{
               document.getElementById('txtTotal').innerHTML='There was an error with your calculation.';
		}else{
               document.getElementById('Total').value = document.getElementById('txtTotal').value;
		}

		}
	</script>

 

	<body>


       <!-- Simple Calculator -->
    <form name="frmSimpleCalculator" id="frmSimpleCalculator" action="" method="get">
        <div>

            <!-- Value 1 name="txtValue1"-->
            <label for="txtValue1"> Value 1: </label>
            <input type="text" id="txtValue1" maxlength="5" /></input>

            <!-- Operator -->
            <select id="ddlOperator">
                <option value="0" selected="selected"> + </option>
                <option value="1" > - </option>
                <option value="2" > * </option>
                <option value="3" > / </option>
            </select> <br />

            <!-- Value 2 -->
            <label for="txtValue2"> Value 2: </label>
            <input type="text" id="txtValue2" maxlength="5" /></input>

               <!-- Line -->
               <hr width="95%"/>

            <!-- Total -->
            <label for="txtTotal"> Total: </label>
            <input type="text" id="txtTotal" maxlength="5" readonly="readonly" /></input>

	    <!-- Calculate Total -->
                   <input type="button" id="btnCalculateTotal" value="Calculate Total" onClick="btnCalculateTotal_Click( );"></input>

            <!-- Clear -->
            <input type="button" name="btnClear" id="btnClear" value="Clear" OnClick="btnClear_Click( );"/></input>

        </div>

    </form>

</body>

Share this post


Link to post
Share on other sites

As for googling, its definitely there. But sometimes you need to determine what level of abstraction your search times are, it can be hard to find if your search is too broad.

 

Agreed. Another trick with Google, or any search engine, is learning the proper syntax in which to use while doing a search.

The one that always helps is quotations. If you add quotations to something in your search field the search engine finds sites with that word as top priority, then uses the other word/words as secondary search parameters.

Sometimes Google will actually suggest a reworded sentence based on your quotations in order to better help you find what you are looking for.

I attempted to find an html calculator script using google this is how it went.

 

Searched: html calculator script

Results: lots of calculators, no scripts

Refine: So I decided to add quotations around "scripts"

Typed: html calculator "script"

Google Suggests: html script for a calculator

Results: First 5 clicks had scripts visible on the page.

 

My knowledge of scripts is very limited so I am unable to determine as to whether or not any of my found sites would have been direct help.

But I do believe that by adding quotations and possibly changing search fields based on information found while searching, would have gotten you a better result.

There is also a number of different syntax commands you may use to help your search needs. I do not know them all, as I never seem to have to do more then quotations to refine my searches appropriately enough.

 

I hope that helped with your use of Goggle.

The trick isn't finding the right answer, it's finding the right question.

Cheers

Share this post


Link to post
Share on other sites

@Jon Bon: You sure do put a lot of work into your posts dont you? :P

 

That was just an example. Replace that line with this:

document.getElementById('txtTotal').value = final_value;

I tested your code and replacing this line worked. Though you clear button doesn't work. The value of our final number is stored in final_value, so we can set the value to that.

 

The syntax document.getElementById() allows you to get data from any element with that specified ID. ID's are supposed to be unique, so make sure you only have one per page. You can then use .value or .innerHTML to set, or retrieve that data. I assumed you don't know this coz you didn't change my line of code to suit yours, but I could be wrong.

 

Do you need help with your clear button?

 

JQuery is a javascript API. You basically add it to your head and then you can use syntax thats way more efficient and easy to use. Do you think you could use that for your class? I'm sure that'd impress your teacher :D I wrote the tileset maker and project cards using JQuery.

Share this post


Link to post
Share on other sites

@Jon Bon: Interesting google tips for Scripts, I'll have to try them out, thanks.

 

 

 

@Marked: The clear button works ok, it's the calculate that isn't. Maybe it's because I'm on Mozilla Firefox, let me try IE before I post this.

 

Wow, neither button works in IE, who knew? I probably should have left this comment in the script

	        <!-- Container for Box Method.  Use child selector so it applies to immediate descendants only -->
        <!-- Notice how clean and straightforward the code without tables. -->

No idea if the Child Selector means anything....

 

You can then use .value or .innerHTML to set, or retrieve that data. I assumed you don't know this coz you didn't change my line of code to suit yours, but I could be wrong.
I didn't know at all.

 

Here's the entire script woth scripts, styles, and the form.

 

<html>

<head>


	<title> Simple Calculator with Styles </title>


	<script type="application/javascript" language="javascript">
		function btnCalculateTotal_Click()
		{
			//Note: the parseFloat function turn strings into numbers 
			var txtValue1 = parseFloat(document.getElementById('txtValue1').value);
			var txtValue2 = parseFloat(document.getElementById('txtValue2').value);
			var myoperator  = document.getElementById('ddlOperator').value;

		if(myoperator==0)//plus
		{
               var final_value=txtValue1+txtValue2;
		}else if(myoperator==1)//minus
		{
               var final_value=txtValue1-txtValue2;
		}else if(myoperator==2)//multiply
		{
               var final_value=txtValue1*txtValue2;
		}else if(myoperator==3)//division 
		{
               var final_value=txtValue1/txtValue2;
		}

			//if the calculation cannot reutrn an arithmetic operation then show an error
		if(isNaN(final_value))
		{
               document.getElementById('txtTotal').innerHTML='There was an error with your calculation.';
		}else{
               ddocument.getElementById('txtTotal').value = final_value;
		}

		}
	</script>
	<!-- ------------------------------------------------------------------- -->
	<!-- ------------------------------------------------------------------- -->
	<script type="text/javascript" language="javascript">  
		function btnClear_Click( )
		{ 
			document.frmSimpleCalculator.txtValue1.value = "0";
			document.frmSimpleCalculator.ddlOperator.value = "0";  
			document.frmSimpleCalculator.txtValue2.value = "0";  
			document.frmSimpleCalculator.txtTotal.value = "";  
		}  
	</script> 

	<style type="text/css">

           #frmSimpleCalculator > div
	    {
		    width: 180px;
		    border: outset 2px black;
		    text-align: center;
		    font-family: Arial;
		    line-height: 40px;          /* spaces out controls vertically */
		    padding: 5px;
		    background-color: #D0D0D0;
	    }
	    #frmSimpleCalculator label
	    {
		    display: inline-block;		/* Otherwise ignores width */
		    width: 70px;
		    text-align: left;
	    }
	    #frmSimpleCalculator input[type=text]
	    {
		    width: 90px;
		    text-align: right;
	    }
	    #frmSimpleCalculator input[type=button]
	    {
		    width: 150px;
		    margin-bottom: 8px;
	    }

       </style>

</head>

<body>

       <!-- Simple Calculator -->
    <form name="frmSimpleCalculator" id="frmSimpleCalculator" action="" method="get">	    
        <!-- Container for Box Method.  Use child selector so it applies to immediate descendants only -->
        <!-- Notice how clean and straightforward the code without tables. -->
        <div>

            <!-- Value 1 name="txtValue1"-->
            <label for="txtValue1"> Value 1: </label>
            <input type="text" id="txtValue1" maxlength="5" /></input>

            <!-- Operator -->
            <select id="ddlOperator">
                <option value="0" selected="selected"> + </option>
                <option value="1" > - </option>
                <option value="2" > * </option>
                <option value="3" > / </option>
            </select> <br />

            <!-- Value 2 -->
            <label for="txtValue2"> Value 2: </label>
            <input type="text" id="txtValue2" maxlength="5" /></input>

               <!-- Line -->
               <hr width="95%"/>

            <!-- Total -->
            <label for="txtTotal"> Total: </label>
            <input type="text" id="txtTotal" maxlength="5" readonly="readonly" /></input>

			<!-- Calculate Total -->
			<input type="button" id="btnCalculateTotal" value="Calculate Total" onClick="btnCalculateTotal_Click( );"></input>

            <!-- Clear -->
            <input type="button" name="btnClear" id="btnClear" value="Clear" OnClick="btnClear_Click( );"/></input>

        </div>

    </form>

</body>

</html>

 

 

 

I'm really stumped as to why the buttons aren't working in the form....

Share this post


Link to post
Share on other sites

You see that line I told you to replace? You didn't copy it right :P You have 2 d's there. I copied that entire code and went through all the variables only to find the typo being the issue... lol

Share this post


Link to post
Share on other sites

Really? -Checks line-

 

................. Once again, Typos are victorious today. Fixed it, and it works, except for when I try to run it in IE. Clear button works in IE, but not Calculate. Any ides why?

Share this post


Link to post
Share on other sites

IE is horrible, hence why I use Firefox, but since the teacher said to make sure it runs in IE (or something close to it) I have no choice. This computer has IE version 8, and same here.

Share this post


Link to post
Share on other sites

Same version as me. I'm working on it now lol but I'll head to bed soon coz i got class in 7 hours minus a 30 minute drive.

 

So are you sure you can't use JQuery? Just checking :D In the real world, you just wouldn't use this code.. oh and also, it will be real obvious if you pasted in code you got from websites. Is that ok? I mean, finding a solution for this by yourself requires an expert, so surely that wouldn't be the case.

 

However, maybe we should look for an alternate to getElementById. Back to google!

Share this post


Link to post
Share on other sites

Sleep is important.

 

I never hear of it, but I'll take a look at it.

 

oh and also, it will be real obvious if you pasted in code you got from websites. Is that ok? I mean, finding a solution for this by yourself requires an expert, so surely that wouldn't be the case.

 

Well, I think as long as I understand how it works (which I do a bit), he'll count it, I'll ask later just in case.

 

Back to Notepad++!

Share this post


Link to post
Share on other sites

@Jon Bon: You sure do put a lot of work into your posts dont you? :P

 

He he, I try to only ever post if its helpful or useful.

 

@Jon Bon: Interesting google tips for Scripts, I'll have to try them out, thanks.

 

No problem. I don't want to hijack the thread and wasn't originally going to post again, but I remembered the other really good tip for Google searching.

You can also add a minus sign then a word at the end of your search to omit results with that word.

Search: Html script calculator - download

The above search would search for it but omit any site that has the word download for a search parameter. This is an excellent way to search for common worded things.

 

-Cheers, and good luck on your homework.

Share this post


Link to post
Share on other sites

He he, I try to only ever post if its helpful or useful.

 

 

 

No problem. I don't want to hijack the thread and wasn't originally going to post again, but I remembered the other really good tip for Google searching.

You can also add a minus sign then a word at the end of your search to omit results with that word.

Search: Html script calculator - download

The above search would search for it but omit any site that has the word download for a search parameter. This is an excellent way to search for common worded things.

 

-Cheers, and good luck on your homework.

Thanks, I need some good luck right now ^^'.

 

A minus? Well if it works for a plus, then why not a minus. I'll have to try that on the next google search, arigato (thank you).

 

 

I did have a question on the homework, so while I was asking him I decided to show him the calculator. He liked it, but he did change it a bit, ok he wrote a whole new script for it.

 

 

function btnCalculateTotal_Click()
		{
			var sngValue1 = 0;
			var intOperator = 0;
			var sngValue2 = 0;
			var sngTotal = 0;

			// Get values from form
			sngValue1 = document.frmSimpleCalculator.txtValue1.value;
			intOperator = document.frmSimpleCalculator.ddlOperator.value;
			sngValue2 = document.frmSimpleCalculator.txtValue2.value;

			// Convert from string to number
			sngValue1 = parseFloat( sngValue1 );
			intOperator = parseInt( intOperator );
			sngValue2 = parseFloat( sngValue2 );

			// Do math
			switch( intOperator )
			{
				// +
				case 0:  sngTotal = sngValue1 + sngValue2;
						 break;
				// -
				case 1:  sngTotal = sngValue1 - sngValue2;
						 break;
				// *
				case 2:  sngTotal = sngValue1 * sngValue2;
						 break;
				// divide
				case 3: if( sngValue2 == 0 )
						{
							alert( "Only Chuck Norris can divide by 0" );
						}
						else
						{
							sngTotal = sngValue1 / sngValue2;
						}
						break;
			}

			// Update form
			document.frmSimpleCalculator.txtTotal.value = sngTotal;

		}

 

 

He told me why this was easier, but I plum forgot.

 

I do have a new question. How do you align check-boxes and radio buttons with the style setup? I can put them in, but they won't align correctly on the right.

 

Right now they're like this.....

Miscellaneous.png

But I need them to be align on top of each other like a list and on the right side. Hopefully having Caramel in that empty spot on the right of Toppings. I have more questions, but let's deal with one at as time.

 

Code for the Forum.

				<!-- chkToppings -->
			<label for="chkToppings"> Toppings: </label>
				<div class="LeftAlign">
					<input type="checkbox" name="chkToppings" id="chkToppings" value="caramel" /> Caramel
					<input type="checkbox" name="chkToppings" id="chkToppings" value="hotfudge" /> Hot Fudge
					<input type="checkbox" name="chkToppings" id="chkToppings" value="sprinkles" /> Sprinkles <br />
				</div>

Script for Checkbox.

			#frmCombos input[type=checkbox]
		{
			width: 25px;
			margin-top: 5px;
			margin-bottom: 5px;
		}

Script for Label (like Toppings).

			#frmCombos label
		{
			display: inline-block;		/* Otherwise ignores width */
			width: 170px;

		    text-align: left;

			border: solid 1px red; 
		}

Maybe I set up something incorrectly, I'm not really sure.

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...