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 ?
$(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.
Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
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.
<p>This is a paragraph selected by a jQuery method. </p> <p>This is also a paragraph selected by a jQuery method. </p> $("p").
Yes, you want the special jQuery eq()
selector.
$("#selbox").val($("#selbox option:eq(1)").val());
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With