Andrei
Andrei

Reputation: 65

GET the content of an <option> in a <select> instead of the value

I have the following HTML select FORM:

<select name="quantity">
        <option value="0" >Select</option>
        <option value="125" >1</option>
        <option value="250" >2</option>
        <option value="375">3</option>
        </select>

I know how to GET the value of each option above but is there any way to GET the variable (1,2.3...)

Upvotes: 3

Views: 2253

Answers (5)

Hackerman
Hackerman

Reputation: 12305

Try this:

<select name="quantity" onchange="javacript: var valor = this.options[selectedIndex].text;  alert(valor); document.getElementById('shadow').value = valor;">
    <option value="0" >Select</option>
    <option value="125" >1</option>
    <option value="250" >2</option>
    <option value="375">3</option>
</select>
<input type="hidden" id="shadow" value="">

With this combination you can accomplish your task.....javascript + hidden input, and php $_GET['shadow'] ;)

Saludos.

Upvotes: 3

Iesus Sonesson
Iesus Sonesson

Reputation: 854

If you put in a hidden field called SelectedHTML you can achieve this with javascript.

<input type="hidden" id="SelectedHTML" name="SelectedHTML" />

for example with an onchange event on the select to put the innerHTML of the selectedIndex into the hidden field, when posted you will be able to use $_GET['SelectedHTML'] to retreive the data

<select onchange="document.getElementById("SelectedHTML").value=this.options[this.selectedIndex].text;" name=....>

Upvotes: 1

Glorious Kale
Glorious Kale

Reputation: 1313

You can't do that with PHP. You need javascript (jQuery).

Method text()

  $('option').text();

would return that for you and then you can send it with GET with window.location

  window.location = 'yoururl.php?value=' + $('option').text();

Upvotes: -2

Bart Friederichs
Bart Friederichs

Reputation: 33511

No, not in standard HTML.

You could use JavaScript to do it somehow.

Upvotes: 0

Quentin
Quentin

Reputation: 943560

Under normal circumstances, when a form is submitted, only the value(s) of the selected item(s) in a select element will be submitted. The label will not.

Your options:

  • Keep a map of values/labels on the server and use the submitted value to retrieve the label
  • Store the label in the value (possibly by encoding the existing value and the label as JSON)
  • Use JavaScript to add the label to the submitted data

I strongly suggest the first option.

Upvotes: 1

Related Questions