0

I have a input field

<input type="text" name ="something" id ="something"/>

I have written this one in my edit profile page .SO initially the field value is None(string) .

I want when user should not enter any thing except digits in the field

I have written the code below for that .

$(document).ready(function() {
 $("#something").keydown(function(event) {
  // Allow: backspace, delete, tab, escape, and enter
  if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
  // Allow: Ctrl+A
   (event.keyCode == 65 && event.ctrlKey === true) ||
  // Allow: home, end, left, right
   (event.keyCode >= 35 && event.keyCode <= 39)) {
  // let it happen, don't do anything
  return;
  }
  else {
   // Ensure that it is a number and stop the keypress
   if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
     event.preventDefault();
    }
   }
  });
});

But problem is when user will submit without altering the value of this box which is None bydefault. My program stopped working.

Please help me out.

How can I prevent user to not submit the form if the input box value is None or anything which is not digits.

Thanks

4

3 回答 3

0
$(document).ready(function() {

$.validator.addMethod("requiredField", function(value, element) {
    if(value == '')
        return false;       
    return true;
}, "Number is required");
});


 <input type="text" name ="somthing" is ="somthing"   class="requiredField"/>
于 2013-04-20T11:31:11.050 回答
0

You might set onfocus="this.value=''" on the input field, to remove the default value on focus.

To prevent to submit none digits you could check before the submit eg with:

function checkBeforeSubmit(){
    var val = fieldname.value;
    var reg = val.replace(/^[0-9]+$/,"");
    if( check !== '' ){ 
            alert('only numerical!');
            return false;
    }
    return true;
}

<form onsubmit="return checkBeforeSubmit()">..</form>
于 2013-04-20T11:35:22.160 回答
0
function validNumber(elem){
    var regex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
    var value = elem.val();
    return regex.test(value);
}

$("#form-id").submit(function() {
    if(validNumber($('#something'))){
        return true; // form is submitted
    }else{
        // add any error message code here
        return false; // form is stopped from being submitted
    }
});
于 2013-04-20T11:36:35.890 回答