Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value from <option><select> to form action

I need to pass a value in option select to action where I have agent_id=

Can anyone help?

<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select>
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
like image 924
mr.data1 Avatar asked Jan 03 '13 23:01

mr.data1


People also ask

How do you make an option value selected?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.

Does option have value attribute?

The value attribute for <option> tag in HTML is used to specify the value of the option element. Attribute Value: It contains single value value which has to be sent to the server.

Which method is used to retrieve the option values from dropdown?

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

Can Options Value string?

Yes, it is a string type, and could have any value. The value goes when you submit a form, and there are limitations.


2 Answers

You don't have to use jQuery or Javascript.

Use the name tag of the select and let the form do it's job.

<select name="agent_id" id="agent_id">
like image 152
Shoaib Avatar answered Oct 17 '22 16:10

Shoaib


Like @Shoaib answered, you dont need any jQuery or Javascript. You can to this simply with pure html!

<form method="POST" action="index.php?action=contact_agent">
  <select name="agent_id" required>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <input type="submit" value="Submit">
</form>
  1. Remove &agent_id= from form action since you don't need it there.
  2. Add name="agent_id" to the select
  3. Optionally add word required do indicate that this selection is required.

Since you are using PHP, then by posting the form to index.php you can catch agent_id with $_POST

/** Since you reference action on `form action` then value of $_GET['action'] will be contact_agent */
$action = $_GET['action'];

/** Value of $_POST['agent_id'] will be selected option value */
$agent_id = $_POST['agent_id']; 

As conclusion for such a simple task you should not use any javascript or jQuery. To @FelipeAlvarez that answers your comment

like image 19
mkungla Avatar answered Oct 17 '22 16:10

mkungla