简体   繁体   中英

How can I obtain the selected option into a select dropodown tag using JavaScript?

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 usere select 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?

 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> 

The below code should work for you.

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

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM