最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to set focus on dropdown by its name -javascriptjquery - Stack Overflow

programmeradmin4浏览0评论

I have a no of dropdown list as follows

<select name="dropname[0]">....</select>
<select name="dropname[1]">....</select>
<select name="dropname[2]">....</select>
<select name="dropname[3]">....</select>....

Now I want to set focus on second drop down list.I tried these

document.getElementsByName('dropname')[1].focus();

results this error

TypeError: document.getElementsByName(...)[1] is undefined

Thanks in advance

I have a no of dropdown list as follows

<select name="dropname[0]">....</select>
<select name="dropname[1]">....</select>
<select name="dropname[2]">....</select>
<select name="dropname[3]">....</select>....

Now I want to set focus on second drop down list.I tried these

document.getElementsByName('dropname')[1].focus();

results this error

TypeError: document.getElementsByName(...)[1] is undefined

Thanks in advance

Share Improve this question asked Oct 1, 2013 at 12:12 manuthalasserilmanuthalasseril 1,0647 gold badges20 silver badges33 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 7

Since you tagged your question with jQuery, try something like

$('select[name^="dropname"]').eq(1).focus();

// $('select[name^="dropname"]') < elements whos name starts with "dropname"
// .eq(1) < select one based on its index
// .focus(); < use jQuery's focus method to set the focus

Try using jquery focus like

$("#id2").focus();

You can use

var i = 0 //or 1,2,3

document.getElementsByName('dropname['+i+']')[0].focus();

hope this will help you

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script>
</head>
<body>
<select name="1">
    <option>1</option>
</select>
<select name="2">
    <option>2</option>
</select>
<select name="3">
    <option>3</option>
</select>
<select name="4">
    <option>4</option>
</select>
<select name="5">
    <option>5</option>
</select>
<script>
$(document).ready(function(){
 i=2;
 $('select[name="'+i+'"]').focus();
});
</script>
</body>
</html>

hope this will help you.!

Most easiest way to focus on element properly with click is

$('#nights').show().focus().click();
发布评论

评论列表(0)

  1. 暂无评论