简体   繁体   中英

Change selected option of an HTML Select element and submit as if I click on it

I have a select with four option elements, and I want to change the value using javascript and then submit it, as if I click on that option.

<select name="MainContent_GVTrabajadores_length" aria-controls="MainContent_GVTrabajadores" class="form-control input-sm">
    <option value="10">10</option>
    <option value="25">25</option>
    <option value="50">50</option>
    <option value="100">100</option>
</select>

This is my try but the problem is that it doesn't get the results like if I actually clicked on it (it just changes the value with no effect):

document.getElementsByName('MainContent_GVTrabajadores_length')[0].value = '100';

You can add the onchange event as shows:

 // function that receives the selected value in your SELECT element. function submitSelection (vlr) { alert("You will submit '" + vlr + "' selected value."); // Add the rest of our code for submit this value. } 
 <select name="MainContent_GVTrabajadores_length" aria-controls="MainContent_GVTrabajadores" class="form-control input-sm" onchange="submitSelection(this.value);"> <option value="10">10</option> <option value="25">25</option> <option value="50">50</option> <option value="100">100</option> </select> 

This will change the value the SELECT's value to "100" and then submit the form. You just need to attach the function to some event to trigger it or modify it to suit your needs.

 function submitMyForm() { document.getElementsByName("MainContent_GVTrabajadores_length")[0].value = "100"; document.myForm.submit(); } 
 <form name="myForm"> <select name="MainContent_GVTrabajadores_length" aria-controls="MainContent_GVTrabajadores" class="form-control input-sm"> <option value="10">10</option> <option value="25">25</option> <option value="50">50</option> <option value="100">100</option> </select> </form> 

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