【问题标题】:check input value and add class with jQuery检查输入值并使用 jQuery 添加类
【发布时间】:2015-09-25 10:35:16
【问题描述】:

我正在尝试为输入创建一些简单的验证。 如果输入的值为“abc”,我想在输入中添加一个红色类并将文本颜色更改为红色。 不知何故,我想停止提交表单。

到目前为止,这是我的代码:

$(document).ready(function () {
    $('#inputname').click(function () {
        if ($("#inputname").val('abc') {
            $("#inputname").addClass(red);
        } else {
            $("#inputname").removeClass(red);
        }
        });
    });

HTML:

<input type="text" value="abc" name="inputname" id="inputname" class="inputname"
  onblur="if (this.value == ``) {this.value = `abc`;}"
  onfocus="if (this.value == `abc`) {this.value = ``;}" />

CSS:

.red { color: #FF0000;}

JSFiddle: https://jsfiddle.net/n5x4q0bp/

【问题讨论】:

    标签: jquery validation input


    【解决方案1】:

    $(document).ready(function() {
      $('#inputname').focusout(function() {
        if ($("#inputname").val() == 'abc') {
          $("#inputname").addClass('red');
          $('#submit_button').attr('onclick', 'return false;');
    
        } else {
          $("#inputname").removeClass('red');
          $('#submit_button').removeAttr('onclick');
        }
      });
    });
    <input type="text" value="" name="inputname" id="inputname" class="inputname" onblur="if (this.value == '') {this.value = 'abc';}" onfocus="if (this.value == 'abc') {this.value = '';}" />
    <input type="submit" id="submit_button" />

    【讨论】:

    • 我必须将 $("#inputname").val() == 'abc') 更改为 $("#inputname").val() == '') 否则它是错误的与火狐。但现在一切都好!谢谢!
    • 为什么 OP 应该“试试这个”?一个好的答案总是会解释所做的事情以及这样做的原因,不仅适用于 OP,而且适用于 SO 的未来访问者。
    【解决方案2】:

    .val() 是一种设置值的方法。您需要获取当前值并检查它

         if ($("#inputname").val()=='abc') {
            $("#inputname").addClass('red');
        } else {
            $("#inputname").removeClass('red');
        }
    

    【讨论】:

      【解决方案3】:

      这是运行代码

        $(document).ready(function () {
      
          $('#inputname').focusout(function () {
      
              if ($("#inputname").val()=="abc") {
                  alert("value");
                  $("#inputname").css("color", "RED");
      
              } else {
                  $("#inputname").css("color", "black");
                  // your form submit code here
              }
              });
      
      
          });
      

      【讨论】:

        猜你喜欢
        • 2016-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多