Reading text values from selected fields in php

Viewed 20

When I try to read the dropdown with $data['fieldname'] , I expect to get back the text that’s displayed in the field, but that isn’t what happens. Dropdowns always point to either another record instance or an element of a list; these instances and elements all have an internal ID, and that internal ID is what I get back. But what if I actually want the text that’s displayed in the dropdown?

1 Answers

When submitting a form, what you get is just the value of the selected option, and not the text. However, there is a way to bypass it if you really need the text. The strategy is to add a hidden input to your form, and fill it with the text of the selected option whenever a new option is selected. It will be something like the following code:

<form action="somewhere.php" method="POST">
    <select name="field" id="field" onchange="document.getElementById('content1').value=this.options[this.selectedIndex].text]">
    <option value="1">First Value</option>
    <option value="2">Second Value</option>
    </select>

    <input type="hidden" name="fieldname" id="content1" value="" />
    <input type="submit" name="submit" value="submit">
</form>

Explanation: here we have a dropdown named field, and there is an onchange event for this dropdown. Whenever a new option is selected, we put the text of that option into the hidden input which is called content1. The name of this hidden input is fieldname, so when this form is submitted, you can get the text in the post variable: $_POST['fieldname'];

Related