Get ID of the options of a select with JavaScript

1

I am working on a PHP project and I use the Laravel 5.4 framework, and I want to get the selected id of a select .

And that's how I have my select and how I fill it with the data:

<select name="location_id" id="addLocationIdReq" onchange="ShowSelected();">
    <option value="" disabled selected >Seleccione un inventario:</option>
    <option value="">Otro</option>
    @foreach($locations as $location)
        <option value="{{$location->id}}">{{$location->name}}
    @endforeach
</select>

Good and that's how it shows the different fields that I have in my database, but I want to know how to get the id of option , and save it in a variable and I want to show it in alert (this is only by way of proof).

I tried to do it with JavaScript, but it did not work:

function ShowSelected()
{
    var cod = document.getElementById("location_id").value;
    alert(cod);
}

And I want to get that id, to do a kind of validation: It depends on which location has been selected, this is how it will show the inventories that are associated with this location, and that is why I need to obtain the id of the location.

    
asked by Samuel Mena 03.07.2017 в 21:54
source

2 answers

3

Inside your JS file that references to your page, with JQUERY and smaller lines of code you can get the ID of the option that you select from your SELECT with this 2 lines of code

$(document).ready(function(){
var id = $('#addLocationIdReq').val();    //#addLocationIdReq es el identificador
                                          // de tu elemento
alert(id);
});

And with that you should display the ID of the selected option.

    
answered by 03.07.2017 в 23:15
1

Your select has the id addLocationIdReq

So your JS could be something like this:

var select = document.getElementById("addLocationIdReq"); /*Obtener el SELECT */
var valor = select.options[select .selectedIndex].value; /* Obtener el valor */
    
answered by 03.07.2017 в 22:07