2014-01-07 131 views
1

我想使用jquery來創建一個函數。而我想要做的是,我有一個文本字段和提交按鈕,所以當我插入數值從1到10它打開了一個鏈接,如果輸入值是從11-20按鈕上點擊它應該打開不同的鏈接。使用jquery從輸入檢查數字

HTML

<input type="text" Id="number" /> 
<input type="submit" id="button" /> 

jQuery的

$(document).ready(function() { 
    if ($("#number").val() >= 19200 && num <= 19276) { 
    $("#button").click(function() { 
     alert("u enterd the number "); 
    }); 
    } 
}); 

http://jsfiddle.net/2nppc/1/

+0

如何u想要打開鏈接?在提交按鈕點擊? – Developer

+0

您可以做的第一件事是檢查輸入的數據是否爲數字。檢查'isNaN()'(javascript)或'.isNumeric()'(jQuery)函數。 – TCHdvlp

+1

您應該將'if'語句移動到點擊處理程序。 – undefined

回答

3

你會需要這些方針的東西:

$(document).ready(function(){ 
    $('#button').click(function(){ 
     var number = $('#number').val(); 
     //check if number 
     if($.isNumeric(number)){ 
      if(number >= 1 && number <= 10){ 
       //1-10 action 
      }elseif(number >= 11 && number <= 20){ 
       //11-20 action 
      } 
     }else{ 
      //Not a number 
     } 
    }); 
}); 

編輯:對不起混了檢查數字的格式,現在:)

+0

獲得了我的+1。如果輸入的數據是數字,則爲唯一一個測試。謝謝 ! – TCHdvlp

+0

仔細檢查編輯我所做的,加上請記住這沒有測試,但我認爲是正確的 – James

+0

我檢查了它,但它不工作http://jsfiddle.net/2nppc/2/ –

1

使用此代碼:

$(document).ready(function() { 
    $("#button").click(function() { 
     var num = $("#number").val(); 
     if(!isNAN(num)){ 
     if (num >= 1 && num <= 10) { 
     window.location.href="your url for 1 to 10"; 
     } else if(num >= 11 && num <= 20) { 
     window.location.href="your url for 11 to 20"; 
     } else { 
     //your other code or action 
     } 
     } else { 
     alert("Enter the numeric value"); 
     } 
    }); 
}); 
+0

這裏是小提琴http://jsfiddle.net/2nppc/2/和它不工作我在做什麼錯 –

+0

@UmarKhan每一個這是罰款的小提琴,但是你的'alert'拼寫不正確。 –

0

排序未測試:

$(function(){ 
     $('#button').on('click', function(){ 
     if ($('#number').val() >= 0 && $('#number').val() <= 10) 
      location.href = 'blabla'; 
     else if ($('#number').val() > 10 && $('#number').val() <= 20) 
      location.href = 'blabla'; 
     }); 
    }); 
+0

如果輸入的字符串不是數字,該怎麼辦?你應該先測試'.isNumeric()'嗎? – TCHdvlp

+0

然後它不會做任何事情,因爲沒有'else'語句。 – GuyT

0
<script> 
     if (parseInt($("#number").val()) <11) { 
     window.location.href = '/link1'; 
     } 
     else{ 
     window.location.href = '/link2'; 
     } 
</script> 
+0

如果輸入的字符串不是數字,該怎麼辦?你應該先測試'.isNumeric()'嗎? – TCHdvlp

+0

你可以檢查,或者你可以限制一個輸入只能用keydown事件中的腳本編寫數字,如http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in -html-inputbox-using-jquery – edonbajrami

0
$(document).ready(function() { 
      $("#button").click(function() { // Replace with Id of the button 
      var num = $("#number").val();  // Replace with Id of the textbox 
      if(!isNaN(num)){ 
      if (num >= 1 && num <= 10) { 
      window.location.href="your url for 1 to 10"; 
      } else if(num >= 11 && num <= 20) { 
      window.location.href="your url for 11 to 20"; 
      } else { 
      //your other code or action 
      } 
     } 
    }); 
}); 
+0

正如你和其他人建議我這樣做,但它不在這裏工作是小提琴鏈接http://jsfiddle.net/2nppc/2/ –