As I said in my remark, you don't need server-side code to do this. Here's a fiddle to do it with jQuery. Very easy :
HTML :
<input type="text" id="myInput"/>
Javascript (supposing you included jQuery) :
$('document').ready(function() {
$('#myInput').on('change',function(){
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var myNumber = parseInt(this.value);
if(myNumber > a) alert("yay!");
else if (myNumber == a) alert("equals!");
else alert("boooo!");
}
});
});
I think the code is quite easy to understand. Note that you have to leave the text field for the "change" event to trigger, and it supposes you actually changed something. You could use blur
event if you want to trigger each time and not only when value changed.
If you want or need to do that kind of check server-side (it may not be that easy than comparing 2 numbers), you can indeed use AJAX. But in that case I would advise to return XML , JSON or even an unformatted string from your server-side code, and treat the response in javascript. For example, you could return simply 'bigger', 'smaller','equal' , and act accordingly in the success
event of your AJAX call. But that's for another lesson ;-)
EDIT following remark of OP :
HTML
<input type="text" id="input1" /><br/>
<input type="text" id="input2" /><br/>
<input type="text" id="input3" /><br/>
<input type="text" id="myInput" readonly="readonly"/>
Javascript :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
And if you wish to calculate and alert only when all 3 fields have been filled :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
if($('#input1').val().trim() !== "" && $('#input2').val().trim() !== "" && $('#input3').val().trim() !== "")
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
}