简体   繁体   中英

Can't force focus on input

I'm trying to focus an input after clicking in a span , the input isn't visible, but when I click in the span it becomes visible

<form action="{{ route('busca') }}" method="get">
    <span class="pesquisa-icon"></span>
    <input id="q" type="text" name="q" placeholder="Digite o que precisa e pressione ENTER..."/>
</form>

With jQuery I become the input visible

$(this).closest('.menu').addClass('pesquisa-open');
$(this).siblings('input').focus();

but it doesn't become focused, even in the browser, I tried $('#q').focus() in browser console (with the input visible) and it doesn't focus.

I'm using Opera Browser

SOLUTION

I checked Sebastian Speitel answer as correct answer cause it is helpful, but my problem actually was in css, my input was with the property visibility: hidden and even I changing to visibility: visible after clicking on span it didn't focus, removing this property solved my problem

It works using only .focus() .

See this demo:

 $('.pesquisa-icon').on('click', function(){ $(this).next().addClass('shown').focus(); }); 
 #q{ display: none; } #q.shown{ display: inline-block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="get"> <span class="pesquisa-icon">TEST</span> <input id="q" type="text" name="q" placeholder="Digite o que precisa e pressione ENTER..."/> </form> 

I think what you are trying to achieve is the same functionality, <label> s are for. You can simply implement one by enclosing your <span> and <input> in one.

Read more about them here: https://www.w3schools.com/tags/tag_label.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM