TheProgrammer
TheProgrammer

Reputation: 1344

How to click an option value using javascript?

I want to click a certain option inside the div tag using Javascript .

Here is the HTML code:

<div class="sizes" data-info="product_sizes" id="select_size">
    <div id="sizes" style="display: block;">
        <select size="8" id="product_sizes">
            <option value="06.5" data-modelsize="06_5" data-sfs="false" class="">06.5</option>
            <option value="07.0" data-modelsize="07_0" data-sfs="false" class="">07.0</option>

I want to click the option value how would I go by doing this using Javascript.

Upvotes: 1

Views: 1582

Answers (3)

Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

Try with:

/**
* OPT ID
*/
var opt = 3;
/**
* SELECTED
*/
var elements = $('#product_sizes option');
$(elements[ opt ]).attr("selected","selected").prop("selected",true);

/**
* OR SET VALUE
*/
$('#product_sizes').val( 19.5 );

/**
* CATCH
*/
$("#product_sizes").change(function(){
    console.log( $( this ).val() );
});

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71939

You don't have to click it, just set the selectedIndex ir value of the <select>.

Without jQuery, this is how to do it:

var sel = document.getElementById('product_sizes');
sel.selectedIndex = 1; // selects 07.0
// Setting the value works too:
// sel.value = "07.0";

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Just target the select and set the value:

$("#product_sizes").val("06.5");

If you want to trigger the change event, add .change() to the above.

Upvotes: 5

Related Questions