doublestar2014 2016-11-23 11:05
浏览 38
已采纳

如果第一个数字为零,则不允许用户输入更多值

i am doing some custom validation on my front end using java script what i want to achieve is if user is entering any digit other than zero it should proceed what ever he enter's after wards but if the user has entered a zero as a first digit it should not allow the user to enter any value after that!! Just the 0 nothing else
there is a functionality over many websites that i saw if they have unwanted characters in an input field they just backspace it dynamically!! like on many payment processing websites on card number field! so in my case if first digit is zero i will backspace everything that comes after that and if not zero then do nothing let it process..something like that i am looking for here's the initial code i am working on

<?php $numbers_var='REAR_PRICE_'.str_replace(" ","_",$buttonloop[$i]);?>
<input onkeyup="checknumbers('<?php echo $numbers_var?>')" onkeypress='return event.charCode >= 48 && event.charCode <= 57' name="REAR_PRICE_<?php echo str_replace(" ","_",$buttonloop[$i]);?>"style="color: black;width: 100%;" value="<?=$rear?>" type="input"/>

and here's the javascript

function checknumbers(i){
    if($("input[name="+i+"]").val()=='0'){
        //what to do?
    }
 }
  • 写回答

3条回答 默认 最新

  • doushi8599 2016-11-23 11:23
    关注

    You can do it all in your keypress event

    function checknumbers(event) {
      if(event.target.value === '0' || !(event.charCode >= 48 && event.charCode <= 57)) {
        event.preventDefault()
        return false
      }
    }
    <input 
      type="input"
      onkeypress='checknumbers(event)' 
      name="REAR_PRICE_1"
      style="color: black;width: 100%;"
      value=""
    />

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?