which I use to clear the text. This x box always appear. I want this x box to appear only when input has focus and hide after word. Currently it appears all the time.
<div >
<div >
@Html.TextBoxFor(m => m.Amount)
<a id="searchclear3"
style="pointer-events:auto; text-decoration:none;
cursor:pointer;"
onclick="$(this).prev('input').val('');return false;">
</a>
</div>
</div>
CodePudding user response:
To hide the x box when input is not focused, you can add a CSS class to control the visibility:
.form-control-clear {
display: none;
}
And then add a JavaScript event listener to show the x box when input is focused:
var input = document.querySelector("input");
var clearBtn = document.querySelector("#searchclear3");
input.addEventListener("focus", function() {
clearBtn.style.display = "block";
});
input.addEventListener("blur", function() {
clearBtn.style.display = "none";
});
CodePudding user response:
You can use some fancy CSS to hide the “searchclear3" element when the text box isn’t focused. The trick is to use the CSS “Adjacent Sibling Selector”,
. (Ref: MDN)
HTML
<div >
<div >
<input id="txtInput" type="text"/>
<a id="searchclear3"
style="pointer-events:auto; text-decoration:none;
cursor:pointer;"
onclick="alert('click'); return false;">X
</a>
</div>
</div>
Notice that for convenience, I hard-coded the markup for the text box, put an “X” in the a
element and fudged the onclick
handler. You’ll have to figure out an appropriate selector for the text box and get rid of the other stuff.
CSS
input#txtInput a#searchclear3 {
visibility: hidden;
}
input#txtInput:focus a#searchclear3 {
visibility: visible;
}
Those rules say that an a
element with id
“searchclear3” that is a sibling of an input
whose id
is “txtInput” should be visible when the input
has focus, and hidden otherwise.