Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$("#select option:second").val() jquery - keep select second value of select box option

Tags:

jquery

I am able to keep select the first and last value of a select box

$("#selbox").val($("#sel_selbox option:last").val());

$("#selbox").val($("#selbox option:last").val());

How can i keep select the second value ?

$("#selbox").val($("#selbox option:second").val());

THis is giving error. Is there any option to keep select by giving index ?

like image 948
zod Avatar asked Jul 15 '11 21:07

zod


People also ask

What does $( this mean in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

What does $( div p select?

Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.

What does 0 mean in jQuery?

According to the jQuery documentation the $() returns a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. By adding the [0] you take the collection wrapper off the element and just return the actual DOM element when dealing with an id.

What does the jQuery (' P ') line of code do?

<p>This is a paragraph selected by a jQuery method. </p> <p>This is also a paragraph selected by a jQuery method. </p> $("p").


2 Answers

Yes, you want the special jQuery eq() selector.

    $("#selbox").val($("#selbox option:eq(1)").val());
like image 72
Michael Edenfield Avatar answered Oct 02 '22 07:10

Michael Edenfield


The selector way of doing this is :eq(), as already suggested.

However, this is not the best method. Because eq is a non-standard, jQuery-specific extension, the whole query has to be parsed by jQuery's selector engine. None of the selection is handled by the browser's native selection capabilities. This means that the selection will be much slower.

If you make a simple selection and then cut it down with jQuery methods, you will get much better performance, because the browser's native selection function (called querySelectorAll) will handle everything that it can, which will provide a big speed boost.

$('#selbox option').eq(1).val();
$('#selbox option').last().val();
$('#selbox option').first().val();     // same as .eq(0).val();

See:

  • .eq()
  • .last()
  • .first()
like image 31
lonesomeday Avatar answered Oct 02 '22 06:10

lonesomeday