Function

P

Philip WATTS

Can anyone tell me why the following script always returns my "failed test"
result. Surely if my input of "No1" is below 10 I should get the "Test1
past" message.

Thanks
Phil

function test1(data1){
if (data1>10){
return false
}
}

function tests(){
var no1=document.form1.number1.value
var no2=document.form1.number2.value

if (!test1(no1)){
alert("test failed"+no1)
}else{
alert("test1 passed")
}
}

</script>
</head>
<body>
<form name="form1">
<input type="text" name="number1">
<input type="text" name="number2">
<input type="button" value="test" Onclick="tests()">

</form>
</body>
</html>
 
R

Richard Cornford

Philip WATTS said:
Can anyone tell me why the following script always returns my
"failed test" result. Surely if my input of "No1" is below 10
I should get the "Test1 past" message.
function test1(data1){
if (data1>10){
return false
}
}

function tests(){
var no1=document.form1.number1.value
var no2=document.form1.number2.value

if (!test1(no1)){
<snip>

The value being passed to the function is a string and the comparisons
will tend to type-convert the number 10 to a string for comparison if
the data1 value is a string. And string comparison makes "10" smaller
than "2".

At some point you need to convert the string acquired from the value
properties of the form fields into a numeric value if you want to
compare that number with another.

<URL: http://jibbering.com/faq/#FAQ4_21 >

Richard.
 
J

Janwillem Borleffs

Philip WATTS said:
Can anyone tell me why the following script always returns my "failed test"
result. Surely if my input of "No1" is below 10 I should get the "Test1
past" message.

You have forgotton to return true on success:

function test1(data1){
if (data1>10){
return false
}
return true;
}


JW
 
E

Evertjan.

Janwillem Borleffs wrote on 07 nov 2003 in comp.lang.javascript:
You have forgotton to return true on success:

function test1(data1){
if (data1>10){
return false
}
return true;
}

Try:

function test1(x){
return !(+x > 10)
}

1 force the value to compare numeric

2 the if-testing of a boolean for extracting false/true is superfluous,
except in in a tutorial
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,477
Members
44,898
Latest member
BlairH7607

Latest Threads

Top