banda
banda

Reputation: 402

how to select automatically first value of dropdown in select input?

I am working with laravel and in my form I am grab data to select input using some variable,

<label for="exampleFormControlSelect1">Vehicle Category</label>
  <select name="c_id" id="c_id" class="form-control input dynamic" data-dependent="b_id" >
    @foreach($model_list as $model) 
      <option value="{{$categories->id}}">{{$categories->id}}</option>
    @endforeach
  </select>

Now I am going to hide this select input and this select input is depend to other select inputs values. So, I need select automatically drop down values to above select input using some technology. How can I do this? (currently it should select manually using drop down list)

Upvotes: 0

Views: 695

Answers (3)

Mario
Mario

Reputation: 4998

If you need to select the first option of a select, you can do it in three ways

select.options select.values select.selectedIndex

For example having this form that contains the select that probably rendered blade

<form name="formName">
    <label>Categories</label>
    <select name="c_id">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>
</form>

You could try

const category = document.forms.formName.c_id;

console.log(category.value)
console.log(category.options[0].value)
console.log(category.options[category.options.selectedIndex].value)

This will show on the console:

'1' '1' '1'

Visit this link to try the example

To read more about select and some useful options visit this article in select and option section

Now, probably I misinterpret your question, in your comment you mention that this select is dependent on another, this is not clear to me, does it have any relation to the data attribute? If this is the case, please develop your question

Upvotes: 0

Marcelo Pereira
Marcelo Pereira

Reputation: 61

<select name="c_id" id="c_id" class="form-control input dynamic" data-dependent="b_id" >
{{$i = 1;}}
@foreach($model_list as $model) 

  <option value="{{$categories->id}}" {{($i == 1) ? "selected='selected' : ''"}}>{{$categories->id}}</option>
  $i++;
@endforeach

Upvotes: 0

memo
memo

Reputation: 1938

Add selected="selected" to the first option.

Upvotes: 1

Related Questions