programing

JQuery를 사용하여 입력 필드에 포커스를 설정하는 방법

lastmoon 2023. 8. 10. 19:05
반응형

JQuery를 사용하여 입력 필드에 포커스를 설정하는 방법

다음 HTML 구조가 지정된 경우:

<div class="wrapper">
    <div class="top">
        <a href="http://example.com" class="link">click here</a>
    </div>
    <div class="middle">
        some text
    </div>
    <div class="bottom">
        <form>
            <input type="text" class="post">
            <input type="submit">
        </form>
    </div>
<div>

페이지에서 여러 번 반복될 것입니다. 어떻게 하면 입력 필드에 포커스를 설정할 수 있습니까?.bottom사용자가 링크를 클릭할 때 div.top디브?

저는 현재 제작 중입니다..bottomdiv는 아래의 JQuery 코드를 사용하여 클릭 시 성공적으로 나타나지만 동시에 입력 필드에 초점을 설정하는 방법을 파악할 수 없는 것 같습니다.

$('.link').click(function() {
    $(this).parent().siblings('div.bottom').show();
});

감사합니다!

포커스를 첫 번째 입력 필드로 설정하려면 다음을 수행합니다.

$(this).parent().siblings('div.bottom').find("input.post").focus();

입력이 부트스트랩 모달 대화상자에 있을 경우에는 답이 다릅니다.포커스 설정 방법에서 표시된 후 부트스트랩 모달의 첫 번째 텍스트 입력으로 복사하는 것은 다음과 같습니다.

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  

Justin의 답변은 저에게 통하지 않았습니다(Chromium 18, Firefox 43.0.1). jQuery's.focus()시각적 강조 표시를 만들지만 텍스트 커서가 필드에 나타나지 않습니다(jquery 3.1.0).

https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ 에서 영감을 받아 입력 필드와 voila에 자동 포커스 속성을 추가했습니다!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}
//$GLOBALS['sitename'] is our domain site URL
//$_GET['s'] is the search parameter of our search, and we want to highlight that term searched...    
jQuery(document).ready(function($){  
        let loc=location.href;
        switch(loc) 
        {

    case "<?php echo $GLOBALS['sitename'] ?>?s=<?php echo $_GET['s'] ?>":       
        {       
        let searchf= $("form.search-form").find("input[type='search']:first");
//searchf.val('').focus();      
//empty the value to allow a new search and focus on the field....this works but better to highlight the searched term to allow the user to decide if want to type in something else or just hit again search. In case we want to empty the searched term 
           setTimeout(function (){
           searchf.delay(1000).focus().select(); 
           }, 1000);    
        break;
//.... end of relevant code 
        }

            

언급URL : https://stackoverflow.com/questions/6738760/how-to-set-focus-on-input-field-using-jquery

반응형