简体   繁体   中英

Access select option with multiple attributes via $_POST in php

I am trying to extract the attributes in the options tag for a select element. The select element is dynamically loaded.

The specific form level code is as below:

<form name='add'>
  Age: <select name='age[]'>
    <option value='1' stud_name='sre' st_address='address1'>23</option>
    <option value='2' stud_name='sam' st_address='address2'>24</option>
    <option value='5' stud_name='john' st_address='address13'>25</option>
  </select>
  <input type='submit' name='submit'/>
</form>

In my PHP file, I access the submitted data via: $_POST['age']; How can I get the other attributes and their value?

The best way is to create individual input fields and control their value by Javascript while select is changed.

But if you persist to pass a multiple values by a single select , you may consider to use json , here an example:

HTML:

<form name="add">
  Age:
  <select name="age">
    <option value='{"age":"1","stud_name":"sre","st_address":"address1"}'>23</option>
    <option value='{"age":"2","stud_name":"sam","st_address":"address2"}'>24</option>
    <option value='{"age":"5","stud_name":"john","st_address":"address13"}'>25</option>
  </select>
  <input type="submit" name="submit"/>
</form>

PHP:

<?php

  $age = json_decode($_POST['age']);

?>

you can't access attribute values in php. only you can access is post data. If you want to access attributes in php, you have to use javascript or jQuery.

ex : https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_attr_set

same as above you can set values to post in a hidden field and submit to php

You have missed the form's attribute; method="post" in order to use $_POST in php. Like: <form method="post" name="add"> ... </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