简体   繁体   English

HTML5输入类型=数字更改步骤行为

[英]HTML5 input type=number change step behavior

If I use an input field of type="number" with step="100". 如果我使用type =“number”的输入字段,其中step =“100”。 I don't want odd numbers to be invalid. 我不希望奇数无效。 I just want increase or decrease to be with a value of 1000. 我只想增加或减少值为1000。

<input type="number" min="100" max="999999" step="100" />

If the user enters the value "199" and submits, he/she gets an error because the value isn't dividable by 100. But all I want with the step-value is to control the behavior of the spinner, eg if the user click up I want the value 199 to become 200 and if he/she clicks down I want it to become 100. Or ideally I would like the value to be increased or decreased with a value of 100. 如果用户输入值“199”并提交,则他/她会收到错误,因为该值不能被100分割。但我想要的步骤值是控制微调器的行为,例如,如果用户点击我希望值199变为200,如果他/她点击,我希望它变为100.或者理想情况下,我希望值增加或减少值为100。

How do I do this? 我该怎么做呢? I tried using the invalid event (with jQuery 1.7.2) like this: 我尝试使用无效事件(使用jQuery 1.7.2),如下所示:

$( "[type='number']" ).bind( 'invalid', function( e ) {
    var el = $( this ),
      val = el.val( ),
      min = el.attr( 'min' ),
      max = el.attr( 'max' );

    if ( val >= min && val <= max ) {
        return false;
    }
} );

But this results in the form not being submitted. 但这导致表单未提交。

PS.: This is in Google Chrome 20.0.1132.57 on Fedora 16. PS。:这是在Fedora 16上的Google Chrome 20.0.1132.57中。

I don't think you can, the step and the validation are closely tied together . 我不认为你可以, step和验证是紧密联系在一起的 In the future you may be able to override the stepUp() and stepDown() functions to get the behaviour you describe but I've not researched if this is an intended use case for these things. 在将来,您可以覆盖stepUp()stepDown()函数来获取您描述的行为,但我还没有研究过这是否是这些事情的预期用例。 I would recommend posting on the WHATWG mailing list , asking specifically about those functions and describing your use case. 我建议在WHATWG邮件列表上发帖,具体询问这些功能并描述您的用例。

For current practical purposes have you tried setting step=1 and binding to a click event to capture? 出于当前的实际目的,您是否尝试过设置step=1并绑定到click事件来捕获? I can see there'll probably be an issue with distinguishing between 'up' and 'down' clicks but that might be surmountable. 我可以看到,区分“向上”和“向下”点击可能存在问题,但这可能是可以克服的。 It might be easier all round however to use a text input, set the pattern attribute appropriately and implement your own spinner. 然而,可能更容易使用text输入,适当地设置pattern属性并实现自己的微调器。

Well, first of all thank you for this very interesting question. 好吧,首先感谢你提出这个非常有趣的问题。 I've learned a lot about HTML5 validation by searching a solution to your problem. 通过搜索问题的解决方案,我学到了很多关于HTML5验证的知识。

My research led me to find that HTML5 form validation API has an interesting set of properties that are read-only, but very useful to do what you want. 我的研究让我发现HTML5表单验证API有一组有趣的属性是只读的,但对于你想要的东西非常有用。

My approach to your problem was to first add the novalidate attribute to the form element, so that I can control when to trigger the validation, then read the validity object attached to the input, so I can know exactly what validation errors are there, and if the only error is stepMismatch (this is what triggers invalidity of numbers such as 199), I can bypass all the validation process. 我对你的问题的处理方法是首先将novalidate属性添加到表单元素,这样我就可以控制何时触发验证,然后读取附加到输入的validity对象,这样我就可以准确地知道哪些验证错误,以及如果唯一的错误是stepMismatch (这是触发数字无效的原因,如199),我可以绕过所有的验证过程。 Else, I can show normal HTML validation behaviour with the reportValidity() method. 另外,我可以使用reportValidity()方法显示正常的HTML验证行为。

Here is the code I came up with that I hope does what you want : 这是我想出的代码,我希望能做到你想要的:

 var form = document.querySelector("form") // Get the form var input = document.querySelector("#myInput") // Get the input to validate form.addEventListener("submit", function(e) { e.preventDefault() // Catch the submit // Do the magic if(onlyStepMatters(input.validity)){ form.submit() }else { form.reportValidity() } }) function onlyStepMatters(validityState) { return !( validityState.badInput || validityState.customError || validityState. patternMismatch || validityState.rangeOverflow || validityState.rangeUnderflow || validityState.tooLong || validityState.tooShort || validityState.typeMismatch || validityState.valueMissing ) /* This is what the object looks like, notice I just skipped the stepMismatch */ /* { badInput, customError, patternMismatch, rangeOverflow, rangeUnderflow, stepMismatch, tooLong, tooShort, typeMismatch, valid, valueMissing, } */ } 
 <form novalidate> <input type="number" id="myInput" min="0" max="1000" step = "100" placeholder="Enter a number" required/> <button type="submit">Send</button> </form> 

I'm pretty sure this code could be refactored and become more concise based on the same logic, but I don't have enough time to think more about it. 我很确定这个代码可以重构,并且基于相同的逻辑变得更简洁,但我没有足够的时间来思考它。

Any constructive comment will be appreciated. 任何建设性的评论将不胜感激。

Hope this helps. 希望这可以帮助。

Only with step but you can use range and add marks to slider then use javascript to check the near value and set it 只有步骤但你可以使用范围并添加标记到滑块然后使用javascript检查近值并设置它

like 喜欢

 function updateTextInput(val) { if (val > 36) val = 50; else if (val > 26) val = 36; else if (val > 20) val = 26; else if (val > 15) val = 20; else if (val > 1) val = 15; document.getElementById('textInput').value = val; } 
 <input type='range' min='0' max='50' step='1' name='slide' list="settings" onchange="updateTextInput(this.value);"> <datalist id="settings"> <option>15</option> <option>20</option> <option>26</option> <option>36</option> <option>50</option> </datalist> <input type="text" id="textInput" /> 

I've been playing a little with your code, trying to achieve this: 我一直在玩你的代码,尝试实现这个目标:

ideally I would like the value to be increased or decreased with a value of 100 理想情况下,我希望值增加或减少值为100

… and ended-up with some script to: ...并以一些脚本结束:

  • Detect a step increase or decrease by keyboard or mouse, 通过键盘或鼠标检测步长增加或减少,
  • Use a remainder variable to store the result of the calculation: value % 100 , 使用remainder变量来存储计算结果: value % 100
  • Modify the step parameter and the value of the input , 修改step参数和input value
  • Add back the remainder variable when keyboard or mouse event has ended, and reset the step parameter back to 1 (needed to be able to submit). 键盘或鼠标事件结束时添加remainder变量,并将step参数重置为1 (需要能够提交)。

In this working snippet, try to modify the input value with the arrows (on keyboard or with the mouse), starting with a number not divisable by 100: 在此工作代码段中,尝试使用箭头(在键盘上或使用鼠标)修改输入值,从不可除以100的数字开始:

 var remainder = false; var stepbefore; $("[type='number']").bind('keydown mousedown', function() { // If keyboard Up or Down arrow keys or mouse left button on the arrows if (event.keyCode == 38 || event.keyCode == 40 || event.button === 0) { // If there is already a change running, exit the function if (remainder !== false) return; var myStep = this.getAttribute("stepcustom"); // Get my "stepcustom" attribute remainder = this.value % myStep; this.value = Math.floor(this.value / myStep) * myStep; stepbefore = this.step; this.step = myStep; } }); $("[type='number']").bind('keyup mouseup', function() { if (remainder !== false) { this.value = +(this.value) + remainder; this.step = stepbefore; remainder = false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <form> <input type="number" min="100" max="999999" step="1" stepcustom="100" /> <input type="submit" /> </form> 

Hope it helps. 希望能帮助到你。

Here is the needed code to achieve what you asked, I tried to avoid recalculations and changing standard behavior so this should be transparent to any other constrain one would set (required, pattern, ranges ...). 这是实现你所要求的所需代码,我试图避免重新计算和改变标准行为,因此这应该对任何其他约束设置(必需,模式,范围......)是透明的。

I only tested on Firefox and Chrome but I believe it should work on any recent browser. 我只在Firefox和Chrome上测试过,但我相信它应该适用于任何最近的浏览器。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disable validity constrains</title>
<!-- avoid highlight due to constrains -->
<style>#qty { box-shadow: unset; }</style>
</head>
<body>
<form>
        <input id="qty" name="num" type="number" min="100" max="1000" step="100">
        <input type="submit">
</form>
<script>
(function() {
        var el = document.getElementById('qty');
        el && el.addEventListener('invalid', function(event) {
                if ('validity' in el) {
                        for (var state in el.validity) {
                                if (state == 'stepMismatch') { continue; }
                                if (el.validity[state]) { return true; }
                        }
                        event.preventDefault();
                        el.form.submit();
                }
        }, true);
})();
</script>
</body>
</html>

inside "change" event round to nearest valid value . 在“更改”事件内部舍入到最接近的有效值

$( "[type='number']" ).change(function () {
   var value = $(this).val());
   var newValue = Math.round(value/100)*100
   if (newValue < 100) {
      newValue = 100;
   }
   if (newValue > 999999) {
      newValue = 999999;
   }
   if (newValue === value ) {
      return;
   }
   $(this).val(newValue)
})

Try using change() function ... 尝试使用change()函数...

<form>
    <input type="number" id="number" min="100" max="999999" step="100" />
</form>

$(document).ready(function(){
    $("#number").change(function(a){
        if ($(this).val() % 100 === 0) {
            /* Do something when the number is even */ 
            console.log("EVEN");
        } else {
            /* Or when it's odd (isn't dividable by 100), do ... whatever */ 
            console.log("ODD");
        }
    })
});

And I was testing it using bootstrap, like the example you want, when user click up the value will become 200 (from 199), when the user click down the value will become 100 而我正在使用bootstrap测试它,就像你想要的例子,当用户点击时该值将变为200(从199),当用户点击时该值将变为100

To change dividable : 要改变可分割:

if ($(this).val() % 100 === 0) { //Change 100 with what ever you want

This is a simple javascript function that could help you out 这是一个简单的javascript函数,可以帮助你
where prev_num is global variable 其中prev_num是全局变量
this will work for increment and decrement both 这将适用于递增递减两者

var perv_num=0;
function ax(z)
{

     let def;
     let mul=10;
     let valu;
     let valucopy=parseInt(z.value);
     let  frst;
     valucopy=((valucopy+100)%100);


         if (parseInt( z.value)<100) 
         {
                  document.getElementById("myNumber").value="";
                  document.getElementById("myNumber").value=100;
         }
         else if(parseInt( z.value)<perv_num)
        {
                  def=parseInt( z.value.length);
                  mul=Math.pow(mul,def-1);
                  frst=(parseInt(z.value[0])*mul);
                  document.getElementById("myNumber").value="";
                  document.getElementById("myNumber").value=frst;
         }
         else if(valucopy  ==0)
         {
                  document.getElementById("myNumber").value="";
                 document.getElementById("myNumber").value=parseInt(z.value)+100;
          }
          else{
                  def=parseInt( z.value.length);
                  mul=Math.pow(mul,def-1);
                  frst=(parseInt(z.value[0])*mul);
                  valu=Math.abs( parseInt(z.value)-frst);
                  valu=100-valu;
                  var number=(parseInt(z.value)+valu);
                  document.getElementById("myNumber").value="";
                  document.getElementById("myNumber").value= number;
              }
              perv_num=parseInt( z.value);
}

and html is like 和HTML一样

    <input type="number" id="myNumber" onchange="ax(this)">

fiddle is https://jsfiddle.net/ecpy5gr0/1 小提琴是https://jsfiddle.net/ecpy5gr0/1

I make script to change step attribute dynamically: 我制作脚本动态更改步骤属性:

 /* jQuery Optional Number Step Version: 1.0.0 Author: Arthur Shlain Repo: https://github.com/ArthurShlain/JQuery-Optional-Step Issues: https://github.com/ArthurShlain/JQuery-Optional-Step/issues */ (function ($) { $.fn.optionalNumberStep = function (step) { var $base = $(this); var $body = $('body'); $body.on("mouseenter mousemove", '[data-optional-step]', function () { $(this).attr("step", $(this).attr('data-optional-step')); }); $body.on("mouseleave blur", '[data-optional-step]', function () { $(this).removeAttr("step"); }); $body.on("keydown", '[data-optional-step]', function () { var key = event.which; switch (key) { case 38: // Key up. $(this).attr("step", step); break; case 40: // Key down. $(this).attr("step", step); break; default: $(this).removeAttr("step"); break; } }); if (step === 'unset') { $base.removeAttr('data-optional-step'); } if ($.isNumeric(step)) { $base.attr('data-optional-step', step); } } }(jQuery)); jQuery(function() { $('.optional-step-100').optionalNumberStep(100); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container mt-5"> <h1>JQuery Optional Number Step</h1> <div class="form-group" style="max-width: 300px"> <label>Example</label> <input type="number" class="form-control optional-step-100" value="0"> <small id="emailHelp" class="form-text text-muted">Dynamic step for this field is 100 <br>You can specify any numeric value on keyboard. <br>HTML5 step validation will not be applied.</small> </div> <a class="btn btn-dark btn-sm" href="https://github.com/ArthurShlain/JQuery-Optional-Step" target="_blank">View on GitHub</a> </div> 

https://codepen.io/ArtZ91/pen/omePje https://codepen.io/ArtZ91/pen/omePje

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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