1

I am pretty new in JavaScript and I have the following problem.

Into a page I have the following select dropdown:

<select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}" required="required" style="width: 55%;" onChange="nascondiBoxDocumentazione(this);">
    ......................................................................
    ......................................................................
    OPTIONS LIST
    ......................................................................
    ......................................................................
</select>

Then I have this JavaScript function that is performed when the user selects an option into the previous select:

function nascondiBoxDocumentazione(ruoloSelezionato) {
    alert("NASCONDI");
}

How can I obtain the value of the selected option into this JavaScript function?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    Possible duplicate of [Get selected value in dropdown list using JavaScript?](http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – nils Oct 07 '15 at 14:32

3 Answers3

3

function nascondiBoxDocumentazione(ruoloSelezionato) {
    alert(ruoloSelezionato.value);
}
<select id="selTipoRap" class="form-control"  style="width: 55%;" onChange="nascondiBoxDocumentazione(this);">
  <option>Option 1</option>
  <option>Option 2</option>
</select>
ram hemasri
  • 1,624
  • 11
  • 14
1

The below code should work for you.

 $('#selTipoRap').on('change' , function(){
       nascondiBoxDocumentazione($(this).val());
  });

for <select> usually i always use the change event.

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
1

I think you want something like this

EDIT: Following a comment from Alexander Solonik, my previous answer was not optimal, this should be much more efficient.

$('#selTipoRap').on('change', function() {
    alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selTipoRap">
  <option value="0">Zero</option>
  <option value="1 ">One</option>
  <option value="2 ">Two</option>
  <option value="3 ">Three</option>
</select>

A pure JavaScript solution:

var selTipoRap = document.getElementById('selTipoRap');

selTipoRap.onchange = function() {
  alert(selTipoRap.value)  
}
<select id="selTipoRap">
  <option value="0">Zero</option>
  <option value="1 ">One</option>
  <option value="2 ">Two</option>
  <option value="3 ">Three</option>
</select>
Ant
  • 462
  • 1
  • 4
  • 18