Daniel Felipe
Daniel Felipe

Reputation: 79

Default select option by table column (with Javascript)

I'm about to perform a huge data input in a table with three select options divided by three columns.

I would like to have the First select with the first option selected by default; the Second select with the second option selected by default; and the Third select with the third option selected by default.

Something like:

     Select 1   | Select 2   | Select 3    
    ------------+------------+-------------
     *Option A* | Option A   | Option A    
     Option B   | *Option B* | Option B    
     Option C   | Option C   | *Option C*  

Those options selected by default in each select.

The problem is that each select has its own ID, there are many pages and more than 500 different selects... Each select is inside a column <td> that I think I can add an unique ID to each column (no matter how many pages, ending with three columns with three unique IDs)

I really have no idea how to achieve this; I was wondering if anyone could come up with a possible solution or orientation so I can take a look with more detail.

Thank you for your time, Regards

Upvotes: 0

Views: 198

Answers (1)

DinoMyte
DinoMyte

Reputation: 8858

You can target the selectedIndex javascript property and have the option selected via a variable that you can increment. This way, you don't have to assign individual id's to each select.

var i = 0;
    $('select').each(function()
    {
       $(this)[0].selectedIndex = i;
       i++;
    });

Working example : https://jsfiddle.net/4m18yzx6/

To select them inside the td,

$('table tr td').each(function()
{
   var i = 0;
   $(this).find('select').each(function()
   {
     $(this)[0].selectedIndex = i;
     i++;
   }) 
});

Example : https://jsfiddle.net/4m18yzx6/1/

Upvotes: 1

Related Questions