简体   繁体   中英

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?

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.

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.

The change event get triggered if you leave the input field (on blur). If you would like to have instant check use keyup event:

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

using the ID selector is faster than the attribute selector

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');
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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