使用jQuery从html表单的输入中获取元素的正确方法

b91juud3  于 5个月前  发布在  jQuery
关注(0)|答案(2)|浏览(64)

我尝试在jQuery的html表单中获取一个名为price input的元素,但没有成功:
// HTML代码:

<input type="text" id="priceID" name="price">

字符串
// jQuery代码:

jQuery(document).ready(function($){
      //  jquery('#priceID').on("keyup", function(){
        jquery('#priceID').on("keyup", function(){
          //  var priceStr = jquery('#priceID').val();
          var priceStr = document.getElementById('priceID');
         // var priceStr = document.getElementsByTagName("INPUT");

            var valid = /^\d{0,4}(\.\d{0,2})?$/.test(priceStr),
                val = priceStr.value;
            
            if(!valid){
                console.log("Invalid input!");
                priceStr.value = val.substring(0, val.length - 1);
            }
        });
    });


我使用此指南作为测试上述price字段的输入字符串/值的参考:
Price field validation using javascript either jquery?
我已经尝试了上述jQuery代码的形式在WordPress管理后台。HTML表单位于某处的子主题。这可能是一个问题?
请告知如何正确获取价格值。
欢呼

bxgwgixi

bxgwgixi1#

我对jQuery不太熟悉,但已经足够了解它的一些基本功能-keyup回调可以访问使用$(this)触发事件的元素,而原生jQuery方法val()可以用于获取和设置其中的值。
FYI:jquery拼写错误!

jQuery(document).ready(function($) {
  jQuery('#priceID').on("keyup", function() {
    /* 
      within the callback you can access $(this) to refer to the element
      and you can find the value of the input using val()
    */
    var price = $(this).val();

    var valid = /^\d{0,4}(\.\d{0,2})?$/.test(price);

    if (!valid) {
      console.log("Invalid input!");

      /* Using val() again to set the modified value */
      $(this).val(price.substring(0, price.length - 1));
    }
  });
});

个字符

carvr3hs

carvr3hs2#

固定:
我在下面插入了一行代码:

jQuery('#priceID').attr('required','required');

字符串
在Abronsius教授创建的函数内部,以引起我的wp主题的注意(哈哈),现在可以检索在Price字段中输入的字符串。

jQuery(document).ready(function($) {
      jQuery('#priceID').on("keyup", function() {
        jQuery('#priceID').attr('required','required');
        /* 
          within the callback you can access $(this) to refer to the element
          and you can find the value of the input using val()
        */
        var price = $(this).val();

        var valid = /^\d{0,4}(\.\d{0,2})?$/.test(price);

        if (!valid) {
          console.log("Invalid input!");

          /* Using val() again to set the modified value */
          $(this).val(price.substring(0, price.length - 1));
        }
      });
    });


欢呼

相关问题