简体   繁体   中英

Javascript: select option value --> button name

I need the selected value to my form submit button.

The reasion is because when the value is "yes" there is a post called if (isset($_POST['yes']) and for "no" there is another if (isset($_POST['no']))

So all i need is:

<select>
<option value"yes">Yes</option>
<option value="no">No</option>
</select>

And this value must be updated here:

<input type="submit" value="Send form" name="Value from the select option">

Simply add name attribute to select element

<select name="userSelected">
  <option value"yes">Yes</option>
  <option value="no">No</option>
</select>

Now use in php:

<?php
  if(isset($_POST['userSelected'])){
    if($_POST['userSelected'] == 'yes'){
      /* code for yes */
    }else{
      /* code for no */
    }
}

Use onChange event in the select to get and change the button name

 function updateBtn(sel) { document.getElementById('sendForm').setAttribute('name', sel.value); }
 <select onChange="updateBtn(this)"> <option value"yes">Yes</option> <option value="no">No</option> </select> <input type="submit" id="sendForm" value="Send form" name="Value from the select option">

Here is one way

 document.querySelector('form').addEventListener("submit", function(e){ e.target.querySelector('input[type=submit]').name = e.target.querySelector('select').value; });
 <form action=""> <select> <option value="yes">Yes</option> <option value="no">No</option> </select> <input type="submit" value="Submit" name=""> </form>

And if you really want it on the select , do like this instead of inline script

Note: Make sure you have set the input's name to the default of the select or else if no one change it, it has no value

 document.querySelector('select').addEventListener("change", function(e){ e.target.form.querySelector('input[type=submit]').name = e.target.value; });
 <form action=""> <select> <option value="yes">Yes</option> <option value="no">No</option> </select> <input type="submit" value="Submit" name="yes"> </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