CaitlinHavener
CaitlinHavener

Reputation: 1418

Make option selection based off text in option element

I am attempting to select the option in a dropdown list that has the text value passed into the function, get it's value, and then select the option with that value. Can you see why the this isn't working?

  function selectAndAddToCart(value)
    {
        console.log('The selectAndAddToCart onclick value is ' + value);
        var optionToSelect = $j('#attribute136').find('option[text="' + value + '"]').val(); //select the option with the node text that equals value
//select the option with the node text that equals value
        var vals = $j('#attribute136').val() || [];
        vals.push(optionToSelect);
        $j('#attribute136').val(vals);

        //initiate add to cart function
        productAddToCartForm.submit(this); 
    }

Upvotes: 2

Views: 74

Answers (3)

adeneo
adeneo

Reputation: 318182

It looks like you are using noConflict, renaming $ to $j, yet on the failing selector you are using $, and not $j!

I'd do :

var optionToSelect = $j('option', '#attribute136').filter(function() {
    return $(this).text().indexOf(value) != -1;
}).val();

But that's only because I don't much care for the contains() selector:

$("#attribute136 option:contains(" + value + ")");

Upvotes: 1

Barmar
Barmar

Reputation: 780788

$("#attribute136 option:content("+value")");

is the selector you want.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Put the value in quotes. Try

var optionToSelect = $('#attribute136').find('option[text="' + value + '"]').val();

Upvotes: 2

Related Questions