myol
myol

Reputation: 9858

Combobox default value from options

I have added a combobox to a wordpress custom post. When the user saves the page the combo boxes value is saved, and on page load the value is read and displayed on the page.

However, I would like the combobox to display the value as its 'default value' on page load. Currently the combobox simply displays the first option on page load. The only way I can think to do this is to 'move' the saved value to the 'top' of the combobox options.

Is there any other way to simply have the combobox 'select' a default value without rearranging the options?

Upvotes: 0

Views: 986

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23389

Check for the value you need and select it with PHP

<select name="mybox">
<option value="val1" <?php if("val1" == $_POST['mybox']){ echo "selected"; } ?>>val1</option>
<option value="val2" <?php if("val2" == $_POST['mybox']){ echo "selected"; } ?>>val1</option>
<option value="val3" <?php if("val3" == $_POST['mybox']){ echo "selected"; } ?>>val1</option>
</select>

Or if you don't feel like typing all that, use js:

        function setSelectedValue(selectObj, valueToSet) {
            //window.alert('function called');
            for (var i = 0; i < selectObj.options.length; i++) {

                if (selectObj.options[i].value == valueToSet) {
                    selectObj.options[i].selected = true;
                    return;
                }
            }
        }
        window.onload = function(){
            var em = document.getElementsByName("mybox")[0];
            setSelectedValue(em, "<?php echo $_POST['mybox']; ?>");
        }

Upvotes: 1

Related Questions