Andrew Evt
Andrew Evt

Reputation: 3689

jQuery variable (select in html)

I'm new in Jquery, and I have this code:

jQuery(document).ready(function(){
        var title = jQuery(".fullVisaImg").attr("inselect");

        var links = jQuery(".ff_elem>option");

        for(var i=0; i<links.length; i++) {
            if (title == links[i].value) {
                links[i].attr("selected", "selected"); // here is my problem
                alert(links[i].value);
                return;
            }
        }
    });

i have a select element on my pages, and want to make one of elements selected. if I comment line with // here... all works good, and i see all my option values.

Thanks for help!

Upvotes: 2

Views: 97

Answers (7)

Mehran Hatami
Mehran Hatami

Reputation: 12961

replace you for loop with:

jQuery(".ff_elem").val(title);

I have created this DEMO for you. Check it out.

Although You can iterate through all your option elements and find your option element, and then do this:

links[i].prop("selected", true);

but there is no need to iterate when you can simply let your select element do this for you as I have mentioned above.

Upvotes: 2

Andy
Andy

Reputation: 3012

This is actually how you can select an option based on the value your options have.

$('select').val('value of the option you want to select');

so use

$(".ff_elem").val(title);

Upvotes: 1

Zoltan.Tamasi
Zoltan.Tamasi

Reputation: 1391

It can be much simpler. Try something like this:

jQuery(document).ready(function(){
    var title = jQuery(".fullVisaImg").attr("inselect");

    jQuery(".ff_elem>option[value=" + title + "]").attr("selected", "selected");
});

Upvotes: 0

BlackPOP
BlackPOP

Reputation: 5737

if your jquery version is above 1.6+ then use this

links.eq(i).prop("selected", true);

else

   links.eq(i).attr("selected", "selected");

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

Following your code, you could use:

links.eq(i).prop("selected", true);

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

When you use [] to access an element in a jquery set, you get back the raw DOM element. So you can not use jquery methods on it directly..

You should also use .prop instead of .attr() when interacting with properties of the element

So use

links.eq(i).prop("selected", true);

Upvotes: 2

reergymerej
reergymerej

Reputation: 2417

links is a jQuery collection. When you loop through it, you're just getting the raw element, not a jQuery wrapped version, so you can't use .attr().

Use this instead at your problem line.

$(links[i]).attr("selected", "selected");

Upvotes: -2

Related Questions