...

View Full Version : New to JavaScript - Need Some Help!



stahl7639
10-17-2008, 03:27 AM
Hello,
My name is Adam, and I am in a computer class that is utilizing JavaScript for our webpages.I know HTML, CSS, and a bit of Java, but JavaScript has always been a thorn in my side.

Forthe class, I need to write code that allows a user to input to number into an HTML form, and the program must return the higher number. So far, I have only been ableto write the form code,but I am really stuck on the JavaScript code.

<form>
<p>First Number:</p>
<input type="text" size="13" maxlength="12" name="firstnumber">
<br>
<p>Second Number</p>
<input type="text"size="13" maxlength="12" name="secondnumber">
<br>
<p>The Higher Number:</p>
<input type="text" size="13" maxlength="12"name="highernumber">
</form>

Also, I haveto convert the numbers from a string to an integer. I am kind of confused about this as well.

Any help would be GREATLY appreciated.

Thank you,
Adam

rangana
10-17-2008, 03:48 AM
<script type="text/javascript">
function findMax()
{
var names=['firstnumber','secondnumber'], // Place the name of the textboxes here for loop
num=0; // Initialize num variable to 0
output=document.getElementsByName('highernumber')[0];
for(var i=0;i<names.length;i++)
{
var el=document.getElementsByName(names[i])[0]; // Get those elements
num=Number(el.value)>num?Number(el.value):num; // Save the highest number
}
output.setAttribute('readonly','readonly'); // Set the textbox to readonly
output.value=num; // Show the highest number
}
</script>
<input type="button" value="Find Maximum Number" onclick="findMax()">

Philip M
10-17-2008, 07:32 AM
Perhaps more suitable for a beginner:-

Also, I have to convert the numbers from a string to an integer. I am kind of confused about this as well.

<form>
<p>First Number:</p>
<input type="text" size="13" maxlength="12" name="firstnumber" id = "firstnumber">
<br>
<p>Second Number</p>
<input type="text"size="13" maxlength="12" name="secondnumber" id = "secondnumber">
<br>
<p>The Higher Number:</p>
<input type="text" size="13" maxlength="12"name="highernumber" id = "highernumber" readonly>
<br><br>
<input type="button" value="Find Maximum Number" onclick="findMax()">
</form>

<script type = "text/javascript">

function findMax() {
var one = parseInt(document.getElementById("firstnumber").value);
var two = parseInt(document.getElementById("secondnumber").value);
if (one > two) {
document.getElementById("highernumber").value = one;
}
else {
document.getElementById("highernumber").value = two;
}
}
</script>


The Moving Finger writes; and, having writ,
Moves on: nor all your piety nor wit
Shall lure it back to cancel half a line,
Nor all your tears wash out a word of it.

-- Omar Khayyam



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum