开发者

jQuery select option with button

开发者 https://www.devze.com 2023-03-27 08:28 出处:网络
Is it possible to select special <option> item with jQuery by pressing button? For example : <a id=\"item1\" href=\"#\">Item 1</a>

Is it possible to select special <option> item with jQuery by pressing button?

For example :

<a id="item1" href="#">Item 1</a>
<a id="item2" href="#">Item 2</a>
<a id="item3" href="#">Item 3</a>

<form>
.......
<select id="items" name="items">
<option value="1">I dont know</option>
<option value="2">Item 1</option>
<option value="3">Item 2</option>
<option value="4">It开发者_StackOverflow中文版em 3</option>
</select>
.........

</form>

If you press the second button than in form automatically selects second option. Is it possible?


This is a simple jQuery way of doing it.

$('a').click(function() {
    var select_num = $(this).index() + 1;
    $('#items option').eq(select_num).attr('selected', 'selected');
});

Here is the example fiddle.


Try this:

$('#item1').click( function() {
   $('#items option[value="2"]').attr('selected', true); 
});

See here: http://jsfiddle.net/RVUDa/


Try this (item 2 link selects item 2 in list):

$('#item2').click(function(){
  $('#items option:nth-child(3)').attr('selected', 'selected');
});

And similar function for each button/link.


Wrap your tags in a block element with an id. This will help make it more efficient when you have a lot of items to click on because it is only one listener instead of one listener for each item in the list.

<div id="buttons">
  <a id="item1" href="#">Item 1</a>
  <a id="item2" href="#">Item 2</a>
  <a id="item3" href="#">Item 3</a>
</div>

Then for your jQuery code, you could do this:

$('#buttons').click(function(e)
{
   var num = $(e.target).index() + 1;
   $('option:nth-child(' + num + ')', '#items').attr('selected', 'selected');
});
0

精彩评论

暂无评论...
验证码 换一张
取 消