Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected value jQuery dropdownlist

I am trying to set the selected value in a dropdownlist using jquery, I have this:

 $('.option_vehiculo', '#form_login').each(function() 
{
    if (this.id == tipo_vehiculo_def)
    {
         this.value = "option";
    };  
});

.option_vehiculo is a class that I give to all my dropdownlists so I can find them quickly.

I iterate through all my form dropdownlists until I find the one I want to modify. Finding the select I want to change works fine, but I can't set the selected value, I tried this as I am doing with my input fields:

this.value = "option";

where option is an option inside my dropdownlist, but all I get from this is my dropdownlist with no selected value, it just appears with no text inside and with the possibility to select one of my available options.

How do I set the selected value of a jQuery dropdownlist?


Attempts: I tried with this, but I am getting no results and I am not sure if I can use it with 'this' variable as the object I want to modify:

this.val("option");

tried this:

$('#tipo_vehiculo_1000').val("4");
var test = $('#tipo_vehiculo_1000').val();

selecting my dropdownlist by id and trying to change my selected option and outputting it later and it keeps giving me the default value "0".

like image 813
Albert Prats Avatar asked Dec 27 '22 23:12

Albert Prats


1 Answers

Instead of iterating through all of them you can simply use your id value in a jQuery selector

 $('#'+tipo_vehiculo_def).val('option')

This assumes that you have an option tag in the select with value="option". Also assumes that since ID's must be unique in a page you haven't duplicated any ID's

like image 188
charlietfl Avatar answered Jan 03 '23 11:01

charlietfl