文本框应只允许小数。

huangapple go评论69阅读模式
英文:

Textbox should allow only decimals

问题

我已经创建了一个动态的HTML表格,其中包含一些输入控件,我想要在这里只输入带有小数点后两位的十进制值。

例如:1111.22,44445454.33

HTML代码:

<div id="divdynamic"></div>

我将动态数据附加到此ID divdynamic

jQuery代码:

$(document).ready(function () {
    decimaldata();
});

function decimaldata() {
    var data = '<div class="closedata"><input type="text" class="fields" name="txtdecimal" autocomplete="off" onkeyup="decimalonly(\'txt1\', this)" value=""></div>' +
               '<div class="closedata"><input type="text" class="fields" name="txtdecimal1" autocomplete="off" onkeyup="decimalonly(\'txt2\', this)" value=""></div>';

    $("#divdynamic").append(data);
}

function decimalonly(n, t) {
    if (n == "txt1") {
        if (((event.which != 46 || (event.which == 46 && $(t).val() == '') ||
                $(t).val().indexOf('.') != -1) && (event.which != 45 || $(t).val().indexOf('-') != -1) &&
                (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }

        // 这里是我的逻辑
    } else {
        if (((event.which != 46 || (event.which == 46 && $(t).val() == '') ||
                $(t).val().indexOf('.') != -1) && (event.which != 45 || $(t).val().indexOf('-') != -1) &&
                (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }

        // 这里是我的逻辑
    }
}

在上面的方法 decimalonly(n, t) 中,我检查了输入的按键,但该代码不正常工作。但如果我输入任何(非数字值),alert('hit'); 消息会触发,但输入的非数字值会显示在UI上,这不应该发生,应该只接受小数。

请建议我如何实现这一点。

对不起,我的英语不太好。

英文:

I have created a dynamic html table with some input controls and here I want to enter only decimal values with two digits after dot(.)

ex: 1111.22 , 44445454.33

Html code:

&lt;div id=&quot;divdynamic&quot;&gt;&lt;/div&gt;

And I append dynamic data to this id divdynamic

jQuery code:


$(document).ready(function () {
decimaldata();
});

function decimaldata()
{
var data = `&lt;div class=&quot;closedata&quot;&gt;&lt;input type=&quot;text&quot; class=&quot;fields&quot; name=&quot;txtdecimal&quot; autocomplete=&quot;off&quot; onkeyup=&quot;decimalonly(&#39;txt1&#39;,this)&quot; value=&quot;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;closedata&quot;&gt;&lt;input type=&quot;text&quot; class=&quot;fields&quot; name=&quot;txtdecimal1&quot; autocomplete=&quot;off&quot; onkeyup=&quot;decimalonly(&#39;txt2&#39;,this)&quot; value=&quot;&quot;&gt;&lt;/div&gt;`

$(&quot;#divdynamic&quot;).append(data);

}

function decimalonly(n,t)
{
if(n == &quot;txt1&quot;)
{

if (((event.which != 46 || (event.which == 46 &amp;&amp; $(this).val() == &#39;&#39;)) ||
            $(this).val().indexOf(&#39;.&#39;) != -1) &amp;&amp; (event.which != 45 || $(this).val().indexOf(&#39;-&#39;) != -1) &amp;&amp;
            (event.which &lt; 48 || event.which &gt; 57)) {
            event.preventDefault();

            //alert(&#39;hit&#39;);
          }

 // here my logic 
}
else
{
if (((event.which != 46 || (event.which == 46 &amp;&amp; $(this).val() == &#39;&#39;)) ||
            $(this).val().indexOf(&#39;.&#39;) != -1) &amp;&amp; (event.which != 45 || $(this).val().indexOf(&#39;-&#39;) != -1) &amp;&amp;
            (event.which &lt; 48 || event.which &gt; 57)) {
            event.preventDefault();

            //alert(&#39;hit&#39;);  
        }

    // here my logic 


}


}


In the above method decimalonly(n,t) I'm checking the entered key but that code is not working fine but if I entered any (non digit value) the alert(&#39;hit&#39;); message is hitting but the entered non digit value is showing on the UI, it should not happen should only take decimals.

please suggest me how to achieve this.

Sorry for my bad English.

答案1

得分: 1

我已经删除了"decimalonly"函数,并为所有带有"class字段"的输入添加了事件监听器。

document.addEventListener('DOMContentLoaded', function() {
  decimaldata();
});

function decimaldata() {
  var data = `<div class="closedata">First Number <input type="text" class="fields" name="txtdecimal" autocomplete="off" oninput="decimalonly(event, 'txt1', this)" value=""></div>
  <div class="closedata"> Second Number <input type="text" class="fields" name="txtdecimal1" autocomplete="off" oninput="decimalonly(event, 'txt2', this)" value=""></div>`;

  document.querySelector('#divdynamic').innerHTML = data;
}

function decimalonly(event, n, t) {
  if (n === 'txt1' || n === 'txt2') {
    var value = t.value;

    // 只允许数字和一个小数点
    value = value.replace(/[^0-9.]/g, '');
    var dotCount = (value.match(/\./g) || []).length;

    if (dotCount > 1) {
      // 移除额外的小数点
      value = value.replace(/\./g, function(match, offset) {
        return offset ? '' : '.';
      });
    }

    // 限制小数点后的位数不超过两位
    var decimalIndex = value.indexOf('.');
    if (decimalIndex !== -1 && value.length - decimalIndex > 3) {
      value = value.substring(0, decimalIndex + 3);
    }

    // 更新输入值
    t.value = value;
  }
}
input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 3px solid #ccc;
  -webkit-transition: 0.5s;
  transition: 0.5s;
  outline: none;
}

input[type=text]:focus {
  border: 3px solid #555;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divdynamic"></div>

当用户在这些输入框中键入时,代码会删除任何不是数字或小数点的字符,然后确保输入中只有一个小数点,并且小数点后不超过两位数字。

英文:

I have removed the "decimalonly" function and added an event listener to all inputs with the .fields class.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.addEventListener(&#39;DOMContentLoaded&#39;, function() {
  decimaldata();
});

function decimaldata() {
  var data = `&lt;div class=&quot;closedata&quot;&gt;First Number &lt;input type=&quot;text&quot; class=&quot;fields&quot; name=&quot;txtdecimal&quot; autocomplete=&quot;off&quot; oninput=&quot;decimalonly(event, &#39;txt1&#39;, this)&quot; value=&quot;&quot;&gt;&lt;/div&gt;
  &lt;div class=&quot;closedata&quot;&gt; Second Number &lt;input type=&quot;text&quot; class=&quot;fields&quot; name=&quot;txtdecimal1&quot; autocomplete=&quot;off&quot; oninput=&quot;decimalonly(event, &#39;txt2&#39;, this)&quot; value=&quot;&quot;&gt;&lt;/div&gt;`;

  document.querySelector(&#39;#divdynamic&#39;).innerHTML = data;
}

function decimalonly(event, n, t) {
  if (n === &#39;txt1&#39; || n === &#39;txt2&#39;) {
    var value = t.value;

    // only allow numbers and one dot
    value = value.replace(/[^0-9.]/g, &#39;&#39;);
    var dotCount = (value.match(/\./g) || []).length;

    if (dotCount &gt; 1) {
      // remove any extra dots
      value = value.replace(/\./g, function(match, offset) {
        return offset ? &#39;&#39; : &#39;.&#39;;
      });
    }

    // limit to two decimal places
    var decimalIndex = value.indexOf(&#39;.&#39;);
    if (decimalIndex !== -1 &amp;&amp; value.length - decimalIndex &gt; 3) {
      value = value.substring(0, decimalIndex + 3);
    }

    // update the input value
    t.value = value;
  }
}

<!-- language: lang-css -->

input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 3px solid #ccc;
  -webkit-transition: 0.5s;
  transition: 0.5s;
  outline: none;
}

input[type=text]:focus {
  border: 3px solid #555;
}

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;divdynamic&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

When the user types in one of these inputs, the code removes any characters that are not digits or a period and then ensures that there is only one period in the input and that there are no more than two digits after the period.

huangapple
  • 本文由 发表于 2023年2月23日 20:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定