最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change the color of text dynamically? - Stack Overflow

programmeradmin0浏览0评论

I want "Password Matched" in Green Color & "Password Don't Match" in Red Color

I'm Trying these lines of codes but not happening. But the main problem is Both "Password Matched" & "Password Don't Match" is ing.

<script type="text/javascript">

function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();

if (password == confirmPassword)
    $("#divCheckPasswordMatch").html("Password Matched");
else
    $("#divCheckPasswordMatch2").html("Passwords Don't Match.");
}

$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
}); 
</script>

And this is my HTML Code

<input type="password" class="form-control" placeholder="Password" required="required" name="txtNewPassword" id="txtNewPassword">
<br />
<input type="password" class="form-control" placeholder="Confirm Password" required="required" name="txtConfirmPassword" id="txtConfirmPassword" onChange="checkPasswordMatch();">
<div id="divCheckPasswordMatch2" style="color:red">
<div id="divCheckPasswordMatch" style="color:green">

I want "Password Matched" in Green Color & "Password Don't Match" in Red Color

I'm Trying these lines of codes but not happening. But the main problem is Both "Password Matched" & "Password Don't Match" is ing.

<script type="text/javascript">

function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();

if (password == confirmPassword)
    $("#divCheckPasswordMatch").html("Password Matched");
else
    $("#divCheckPasswordMatch2").html("Passwords Don't Match.");
}

$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
}); 
</script>

And this is my HTML Code

<input type="password" class="form-control" placeholder="Password" required="required" name="txtNewPassword" id="txtNewPassword">
<br />
<input type="password" class="form-control" placeholder="Confirm Password" required="required" name="txtConfirmPassword" id="txtConfirmPassword" onChange="checkPasswordMatch();">
<div id="divCheckPasswordMatch2" style="color:red">
<div id="divCheckPasswordMatch" style="color:green">
Share Improve this question edited Feb 21, 2017 at 16:57 Vivek Saha asked Feb 21, 2017 at 16:47 Vivek SahaVivek Saha 1011 silver badge10 bronze badges 7
  • 2 if (password = confirmPassword) is wrong. That should be == not =. There are a bunch of other things wrong here too like if my passwords don't match, then I try again and they do, both messages will be displayed. – dmeglio Commented Feb 21, 2017 at 16:48
  • 1 or even better: if (password === confirmPassword) { – Pablo Lozano Commented Feb 21, 2017 at 16:49
  • = is not used for parisons. Also always explain what happens and what should happen rather than being vague. – Sami Kuhmonen Commented Feb 21, 2017 at 16:49
  • What errors are you getting in the console? What debugging have you done? Are you including jQuery? – j08691 Commented Feb 21, 2017 at 16:50
  • 2 You're not closing your divs, so it may be that your divCheckPasswordMatch is nested under your divCheckPasswordMatch2 and is therefore wiped out if the passwords don't match. – Heretic Monkey Commented Feb 21, 2017 at 16:51
 |  Show 2 more ments

3 Answers 3

Reset to default 3

The <div>'s in your html need to be closed. Your browser does not know how to structure broken html, so it will likely render your html as nested <div>'s like this:

<div id="divCheckPasswordMatch2" style="color:red">
   <div id="divCheckPasswordMatch" style="color:green">
   </div>
</div>

This means that when you replace the html with the javascript line:

$("#divCheckPasswordMatch2").html("Passwords Don't Match.");

That the browser removes the other <div> to put in the string "Passwords Don't Match". The result is:

<div id="divCheckPasswordMatch2" style="color:red">
   <!-- This other div is removed -->
   Passwords don't match
</div>

Now, any attempt to replace the text on #divCheckPasswordMatch will fail, because that element does not exist any more.

Here is how to fix that problem: add closing tags

<div id="divCheckPasswordMatch2" style="color:red"></div>
<div id="divCheckPasswordMatch" style="color:green"></div>

By adding closing tags, you are telling the browser where to end your block, and you are telling the browser that the blocks are next to each-other and not containing each other. With this change, you will now be able to add and remove text freely to both div's and it will never affect the other div.

Now, let us take this fix a little farther.

@dman2306 correctly pointed out that your code will show both the error message and the success message as written. Let's fix that by using just one div and changing the class.

Use the following:

//HTML5 does not require type tags on your script blocks
    function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();
        var div = $( "#messageBlock" );
    
        if (password == confirmPassword){
            $(div).removeClass( "bad_password" );
            if( password == "" && confirmPassword == "" ){
                /* 
                    We do not delete the div. 
                    We set the html content to 
                    an empty string. This way 
                    we can use the DIV again in the future */
                $(div).html(""); 
            }else{
                $(div).html("Password Matched");
            }
        }
        else
        {
            $(div).html("Passwords Don't Match.");
            $(div).addClass("bad_password");
        }
    }
    
    $(document).ready(function () {
        $("#txtConfirmPassword").keyup(checkPasswordMatch);
    });
#messageBlock { color: green; }
    #messageBlock.bad_password { color: red; }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Example</h1>
<p>Please enter passwords to check the behavior of the message div</p>
<input type="password" class="form-control" placeholder="Password" required="required" name="txtNewPassword" id="txtNewPassword">
    <br />
    <input type="password" class="form-control" placeholder="Confirm Password" required="required" name="txtConfirmPassword" id="txtConfirmPassword" onChange="checkPasswordMatch();">
    <div id="messageBlock"><!-- this is where ALL messages appear, and the color is based on the class name --></div>

Run the code above to see a live example of the new code.

This code has the following benefits:

  1. By using a single message div, you show only one message at a time. All new messages replace the preceding message.
  2. The color is not hard-coded into the element, so you can change the look of your page just by changing your css, which now sits in a <style> element.
  3. Your javascript bees a little more simple, you only need to worry about adding the right message and then adding or removing a single class name. The default text color is green, and with the class name bad_password, the text color changes to red.

You can still make several improvements on this design, but I have made remendations based on your submission so that you can grow and improve as a coder. Keep up the good work and soon you will be building amazing things!

Try something like below to have persistent color:

if (password == confirmPassword)
    $("#divCheckPasswordMatch").html("Password Matched").css("color", "green");
else
    $("#divCheckPasswordMatch2").html("Passwords Don't Match.").css("color", "red");
}

If I were doing this, I would only have one div for the message and then style it accordingly. And then I would clear the message if a new password is being typed.

<style>
    .green {
        color: green;
    }
    .red {
        color: red;
    }
</style>

<script type="text/javascript">
    function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();

        if (password == confirmPassword) {
            $("#divCheckPasswordMatch").text("Password Matched");
            $("#divCheckPasswordMatch").css("color", "green");
        }
        else {
            $("#divCheckPasswordMatch").text("Passwords Don't Match");
            $("#divCheckPasswordMatch").css("color", "red");

        }
    }

    function clearMessage() {
        $("#divCheckPasswordMatch").text("");
    }

    $(document).ready(function () {
        $("#txtNewPassword").keyup(clearMessage);
        $("#txtConfirmPassword").keyup(checkPasswordMatch);
    }); 
</script>

<input type="password" class="form-control" placeholder="Password" required="required" name="txtNewPassword" id="txtNewPassword">
<br />
<input type="password" class="form-control" placeholder="Confirm Password" required="required" name="txtConfirmPassword" id="txtConfirmPassword" onChange="checkPasswordMatch();">
<div id="divCheckPasswordMatch"></div>
发布评论

评论列表(0)

  1. 暂无评论