简体   繁体   中英

How to customize the step of a number input field?

I have an input field of type number which ranges from 1 to 4096 as follows:


<input max="4096" min="1" name="size" step="2" type="number" value="4096">

类型编号的输入字段


Iam currently using a step = 2 , that result in numbers 2, 4, 6, 8, 10, ...

How can I modify the step to double the value 1 , 2, 4, 8, 16,... ?


Note :

The field can contain only these values (The user shoudn't be able to insert 3 , 5 , 6, 7, ... ). And it should work on both increment and decrement.

I would use javascript to change your step dynamically on change

<input max="4096" min="1" name="size" step="2" type="number" value="4096" id="foo">

<script type="text/javascript">
    $('#foo').change(function(){
        this.step=this.value;
    });
</script>

JSFiddle

The native stepper doesn't suit your requirements. Your best bet would be to implement a custom solution.

I put together an example. Have a look at it:

 $('.steps').text($('.steps').data('min')); $('.step').click(function() { if ($('.steps').text() == 1 && $(this).hasClass('down') || +$('.steps').data("max") == +$('.steps').text() && $(this).hasClass('up')) return; if ($(this).hasClass('up')) $('.steps').text($('.steps').text() * 2); else $('.steps').text($('.steps').text() / 2); });
 .stepper { width: 75px; height: 30px; border: 1px solid #C0C0C0; display: inline-block; } .steps { width: 55px; float: left; display: inline-block; text-align: center; line-height: 30px; } .step { font-size: 8px; width: 20px; padding: 0px; float: right; } .step.up { vertical-align: top; } .step.down { vertical-align: bottom; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="stepper"> <span class="steps" data-min="1" data-max="4096"></span> <button type="button" class="step up">&#x25B2;</button> <button type="button" class="step down">&#x25BC;</button> </div>

This works.

 $("#numbercruncher").change(function(){ var a=parseInt($("#numbercruncher").val()); var b =a*2-1; $("#numbercruncher").attr("step",b); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" min="1" max="1000" id="numbercruncher"step="2">

Or this

 <input type="number" min="1" max="2000" onchange="this.step=this.value*2-1">

This thread is old, but nowadays, just put step in the html tag:

<!DOCTYPE html>
<html>
<body>

<h1>The input step attribute</h1>

<form action="/action_page.php">
  <label for="points">Points:</label>
  <input type="number" id="points" name="points" step="0.2">
  <input type="submit">
</form>

</body>
</html>

Source: W3CSchool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM