Form field input number automatically convert to 3

2019-09-09 16:01发布

问题:

This question already has an answer here:

  • How can I pad a value with leading zeros? 69 answers

I am trying to make a form where users can input a pagenumber and jump to a certain page which is identified by its div ID.

<form id="gotopage" class="uniForm">
    <input id="pagenumber" name="pagenumber" value="" size="10" type="text" />
</form>
<script>
$(document).ready(function() {
     $('#gotopage').submit( function() {              
          goUrl = 'index.html#pg-' + $('#pagenumber').val().toLowerCase();
          window.location = goUrl;
          return false;  // Prevent the default form behaviour
     });
});
</script>

I can get this to work nicely except I named my ID's in a manner such that its 3-digits for example:

<div id="pg-001">, <div id="pg-002>, <div id="pg-003"> and so on and so forth.

Is there a way to tweak my above code such that I can tell it to add the relevant zeros to make up a 3 digit number for any number that the user inputs?

Thank you in advance.

回答1:

You could create a function for it like this:

function padNum(num,length)
{
    length = length || 3;num+="";
    while(num.length < length) num="0"+num;
    return num;
}

Examples:

var newid = padNum(3);//003
var newid = padNum(3,4);//0003

Shorter (but less legible) function if wanted

function padNum(num,length)
{
    return Array((length||3)-((num+"").length-1)).join("0")+num;
}

Note: functions are defaulting the length parameter to 3 when not specified



回答2:

used this code :

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

Output:

pad("12", 3);    // => "012"


<form id="gotopage" class="uniForm">
    <input id="pagenumber" name="pagenumber" value="" size="10" type="text" />
</form>
<script>
$(document).ready(function() {
     $('#gotopage').submit( function() {              
          goUrl = 'index.html#pg-' + pad($('#pagenumber').val().toLowerCase(),3);
          window.location = goUrl;
          return false;  // Prevent the default form behaviour
     });
});
</script>


回答3:

var num = $('#pagenumber').val().toLowerCase();
var len = num.length;
var result = [0, 0].slice(0, len < 4 ? 3 - len : 0).join('') + num;

Fiddle