Sebb_T
Sebb_T

Reputation: 1

How do i select the nearest <input>?

I have an icon 'inside' of an input field. When I hover, I want the icon to change and the "type" of the input field where it is inside of (I have 3 fields like this, so I want to select this specific one)

HTML:

<div class="change_subtitle">Enter Password</div>
<input id="pw_old" class="change_input" type="text"><i class="fa fa-eye-slash" aria-hidden="true"></i></input>
<div class="change_subtitle">Enter new Password</div>
<input id="pw_new1" class="change_input" type="password"><i class="fa fa-eye-slash" aria-hidden="true"></i></input>
<div class="change_subtitle">Confirm new Password</div>
<input id="pw_new2" class="change_input" type="password"><i class="fa fa-eye-slash" aria-hidden="true"></i></input>
<div class="button_confirm" onclick="inputIsValid()">Confirm</div> 

jQuery:

$(".fa-eye-slash").hover(function(){
                    if($(this).hasClass('fa-eye-slash')) {
                        $(this).removeClass('fa-eye-slash');
                        $(this).addClass('fa-eye');
                        $(this).attr('type' = 'text'); // I want to select the input here and change the type of it
                    } else if($(this).hasClass('fa-eye')) {
                        $(this).removeClass('fa-eye');
                        $(this).addClass('fa-eye-slash');
                        $(this).attr('type' = 'password'); // I want to select the input here and change the type of it back
                    }
                })

CSS (just to understand what is ment by "inside"):

.fa-eye-slash{
    color: #34495e;
    margin-left: -20px;
}

.fa-eye{
    color: #34495e;
    margin-left: -20px;
}

So when I hover the icon it should change and change the type of my input field from "password" to "text" and back later on.

Upvotes: 0

Views: 114

Answers (2)

Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

Try this fiddle path https://jsfiddle.net/afckhbpo/

Problem is with

$(this).attr('type' = 'text') 

Use like this:

$(this).prev().attr('type', 'text')

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074268

In terms of the question in your title, since these icons are i elements that immediately follow the field they relate to, $(this).prev() will give you a jQuery object for the input.

So when I hover the icon it should change and change the type of my input field from "password" to "text" and back later on.

Once an input is created and has a type, you can't change that type (the spec allows it but some browsers don't handle it [yet]). Instead, you can have two inputs (one type="text", the other type="password"), and show/hide them as appropriate.

Upvotes: 0

Related Questions