Ad

How To Select Multiple Elements With JQuery?

- 1 answer

My objective is making a function to toggle password visibility. The problem is that in the same Doc I have 3 different inputs that I also need the toggle visibility function, tho these inputs are not related to the password.

I tried with the name attribute, but it felt like over complicating, since I had names for each icon and input.I have no idea what to use to make the function, and I know there must be an easier way.

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
@Html.PasswordFor(m => m.Password, new { @class = "form-control", maxlength = 50 })
Ad

Answer

You can add an event handler on every fa-eye elements to toggle the opacity of its next element if it is an input.

And there would be nothing to change on your razor extention method call.

$(".fa-eye").on("click", function(){
  let nextInput = $(this).next("input");
  let visibility = nextInput.css("opacity") == "1" ? 0 : 1;
  $(this).next("input").css("opacity", visibility)
})
<link target="_blank" rel="nofollow noreferrer" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password" name="Password" type="password" class="form-control" maxlength="50" value="" /><br>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password2" name="Password2" type="password" class="form-control" maxlength="50" value="" /><br>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password3" name="Password3" type="password" class="form-control" maxlength="50" value="" /><br>


EDIT

I'm quite slow tonight... It took time before I figure out what you want even if it's obvious! Have a look now!

$(".fa-eye").on("click", function(){
  let nextInput = $(this).next("input");
  let visibility = nextInput.attr("type") == "password" ? "text" : "password";
  nextInput.attr("type", visibility)
})
<link target="_blank" rel="nofollow noreferrer" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password" name="Password" type="password" class="form-control" maxlength="50" value="Abc_123" /><br>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password2" name="Password2" type="password" class="form-control" maxlength="50" value="My_Password" /><br>

<i class="float-right fa fa-eye fa-lg" id="toggleVisibility"></i>
<input id="Password3" name="Password3" type="password" class="form-control" maxlength="50" value="Pr!vat3" /><br>

Ad
source: stackoverflow.com
Ad