简体   繁体   English

检查何时输入类型文本被填充

[英]Check when input type text is filled

I have a form with input types text. 我有一个带有输入类型文本的表单。 Like this: 像这样:

<input type="text" placeholder="Voornaam" class="required" title="Voornaam" id="ctl00_ContentPlaceHolder1_tbFirstName" maxlength="255" value="Mike" name="ctl00$ContentPlaceHolder1$tbFirstName">

But now my question. 但是现在我的问题。 Normally the text is gray in the text fields. 通常,文本字段中的文本为灰色。 But when you have completed a field. 但是当您完成一个字段时。 The color must be black. 颜色必须为黑色。 How can i check this with javascript? 如何使用javascript检查此内容?

Thanks 谢谢

I think you meant that we need color field only when user finished writing.... If yes then you need to use this algorithm: 我认为您的意思是仅在用户完成书写时才需要色域。...如果是,则需要使用以下算法:

$('#ctl00_ContentPlaceHolder1_tbFirstName').blur(function () {
    var self = $(this);
    if (self.val() != "") {
        self.css('color','black'); // Set black fore color
    }
    else {
        self.css('color','gray'); // Restore code
    }
});

You could use the .change function in jquery to change the color to black when user type something and cursor moves out of the text field. 当用户键入某些内容并将光标移出文本字段时,可以在jquery中使用.change函数将颜色更改为黑色。

Ex: 例如:

$("input[type='text']").change(function(){

    $(this).css('color', 'black');
});
<input type="text" onblur="changeColor()" placeholder="Voornaam" 
 class="required" title="Voornaam" id="ctl00_ContentPlaceHolder1_tbFirstName" 
 maxlength="255" value="Mike" name="ctl00$ContentPlaceHolder1$tbFirstName">

define your changeColor() function, which will change color of text in the textbox. 定义您的changeColor()函数,该函数将更改文本框中文本的颜色。

The change event get triggered if you leave the input field (on blur). 如果您离开输入字段(处于模糊状态),则会触发更改事件。 If you would like to have instant check use keyup event: 如果您想进行即时检查,请使用keyup事件:

$('#ctl00_ContentPlaceHolder1_tbFirstName').bind('keyup', function(){
  if (someconditionistrue) $(this).css('color','black');
});

using the ID selector is faster than the attribute selector 使用ID选择器比属性选择器快

This will apply this rule to all elements with the required class. 这会将规则应用于所有具有必需类的元素。

$('.required').blur(function () {
    if ($(this).val().trim().length == 0) 
        $(this).css('color','black');
    else 
        $(this).css('color','gray');
  });

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

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