我关注代码
<input type="text" id="max_marks" name="max_marks" value="100">
<input type="text" id="marks" name="marks" value="75" >
<script type="text/javascript">
$(document).ready(function(){
$('#marks,#max_marks').change(function(){
var mm=$('#max_marks').val();
var m=$('#marks').val();
if(parseInt(mm,10) > parseInt(m,10))
{
alert("Maximum marks greater than obtained marks");
}
}).change();
});
</script>
当最大标记小于获得的标记时,警报会触发。我在哪里做错了?
答案 0 :(得分:1)
有时我们无法预测客户端脚本语言(如jQuery和Javascript)的流程。如何尝试关注一个
<input type="text" id="max_marks" name="max_marks" value="100"><span></span>
<input type="text" id="marks" name="marks" value="50" ><span></span>
<script type="text/javascript">
$(document).ready(function(){
function isNumberInt10(n) {
return !isNaN(parseInt(n,10)) && isFinite(n);
}
function isValidMarks(m,n){
if(parseInt(m) <= parseInt(n))
{
return true;
}
}
$('#max_marks').change(function(){
var mm=$('#max_marks').val();
if (!isNumberInt10(mm)) {
$('#max_marks').next().text('Enter valid marks');
$('#max_marks').attr('value','');
$('#max_marks').focus();
}
else
{
$('#max_marks').next().text('');
$('#max_marks').attr('value','');
$('#max_marks').focus();
}
}).change(1000);
$('#marks').change(function(){
var mm=$('#max_marks').val();
var m=$('#marks').val();
if (!isNumberInt10(m)) {
$('#marks').next().text('Enter valid marks');
$('#marks').attr('value','');
$('#marks').focus();
}
else
{
$('#marks').next().text('');
}
if(isValidMarks(mm,m))
{
$('#marks').next().text('Enter Valid obtained marks');
$('#marks').attr('value','');
$('#marks').focus();
}
else
{
$('#marks').next().text('');
}
}).change(1000);
});
</script>
答案 1 :(得分:0)
您编写的代码很容易受到错误的数字字符串的影响。我建议像这样修改它:
function isNumberInt10(n) {
return !isNaN(parseInt(n,10)) && isFinite(n);
}
$(document).ready(function(){
$('#marks,#max_marks').change(function(){
var mm, m;
mm=$('#max_marks').val();
if (!isNumberInt10(mm)) {
alert("Max marks needs to be a number");
return;
}
m=$('#marks').val();
if (!isNumberInt10(m)) {
alert("Marks needs to be a number");
return;
}
if(parseInt(mm,10) > parseInt(m,10)) {
alert("Maximum marks greater than obtained marks");
}
}).change();
});