简体   繁体   English

存在无效 class 时更改字段占位符文本

[英]Changing field placeholder text when invalid class exists

I have a simple form:我有一个简单的表格:

<form>
  <input type="text" name="firstname" placeholder="First name *" required>
  <input type="submit" value="Submit">
</form>

If the required field is empty, the class not-valid is added to the input type text.如果必填字段为空,则将 class not-valid添加到输入类型文本中。 If this not-valid class exists, I'm want to change the placeholder text to something else.如果这个not-valid class 存在,我想将占位符文本更改为其他内容。 So, a sample use case:因此,一个示例用例:

  • User see's first name textfield (placeholder at this point says "First name *".用户看到的名字文本字段(此时占位符显示“名字 *”。
  • User clicks submit, leaving textfield empty.用户单击提交,文本字段为空。
  • Class not-valid at this point is added to the textfield. Class not-valid at this point 添加到文本字段中。
  • Placeholder now says "Please complete field" (in place of default placeholder").占位符现在说“请填写字段”(代替默认占位符)。

Here's what I've got so far:这是我到目前为止所得到的:

(function( $ ) {  

    $( document ).ready( function() {

        $('form').find(".not-valid").each(function(ev){
            if(!$(this).val()) { 
                $(this).attr("placeholder", "Please complete field");
            }
        });

    }); 

})( jQuery );

Doesn't change the placeholder currently.当前不更改占位符。

Something like this?像这样的东西? (I didnt use the not-invalid class, no need for that, unless you want to add other style to the empty filed) (我没有使用非无效的 class,不需要,除非您想在空字段中添加其他样式)

 $('#submit').click(function() { if($('#firstname').val() == ''){ $('#firstname').attr('placeholder','Please complete field'); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="text" id="firstname" name="firstname" placeholder="First name *" required> <input type="submit" value="Submit" id="submit"> </form>

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

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