Reputation: 55
i wrote this code for toggle password,but i have error: html:
<!--Hide/Show password-->
<button class="form-password__visibility" type="button"
onclick="$('#inputPassword').attr('type') = $('#inputPassword').attr('type') == 'password' ? 'text' : 'password'">
<i class="vi vi-eye-off"></i>
</button>
sccript:
$(":input[type=password]").click, function (e) {
const input = $(this).closest('input');
input.attr('type') == 'password' ? 'text' : 'password';
if (input.attr('type') == 'password') {
$(this).children("i").removeClass("vi-eye-off").addClass("vi-eye");
}
else {
$(this).children("i").removeClass("vi-eye").addClass("vi-eye-off");
}`
`
};
Error: I hqve error in html for this line" onclick="$('#inputPassword').attr('type') = $('#inputPassword').attr('type') "--->"Uncaught ReferenceError: Invalid left-hand side in assignment"
Upvotes: 0
Views: 506
Reputation: 24001
A lot of things need to consider here
You can use inline onclick
OR click
handler
$(this).closest('input')
means you have an element inside input and its totally wrong
$(":input[type=password]").click,
should be $(selector).on('click' , function
OR $(selector).click(function...
By using $(":input[type=password]")
you're using the click
to the input
and you should use it for the button
Your html structure for this should be an element holds both of input
and button
then use .closest().find()
to select the input
To set the attribute you need to use $(selector).attr('attribute name' , 'value')
that means input.attr('type') == 'password' ? 'text' : 'password';
won't work at all .. the right thing input.attr('type' , input.attr('type') == 'password' ? 'text' : 'password')
Finally, Your code should be something like this
$(".form-password__visibility").on('click', function (e) {
const input = $(this).closest('.form-password').find('input');
input.attr('type' , input.attr('type') == 'password' ? 'text' : 'password');
if (input.attr('type') == 'password') {
$('i' , this).removeClass("vi-eye-off").addClass("vi-eye");
}
else {
$('i' , this).removeClass("vi-eye").addClass("vi-eye-off");
}`
`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-password">
<input type="password"/>
<!--Hide/Show password-->
<button class="form-password__visibility" type="button">
<i class="vi vi-eye-off"></i>
</button>
</div>
Upvotes: 1