1

It's possible to create a select input with a button or a link inside the options? I'd like to use it to list some values, and to have the option with a button to "Create Value" inside the options. I don't know if this is possible. I tried it with a href, but it treat it as text.

This would be the ideal scenario:

<select name="things">
    <option value="1">Thing One</option>
    <option value="2">Thing Two</option>
    <option value="3">Thing Three</option>
    <option value=""><button>New Thing</button></option>
</select>

I've search, but with no luck. Does somebody knows an jQuery plugin or something like might work?

1
  • 1
    No, you can't put any HTML inside of an option element, just text. You'll need to use either an list element to emulate a select, or use a change-handler on the select element. Commented Jan 17, 2014 at 23:47

2 Answers 2

9

Here's a simple implementation:

$('select[name=things]').change(function() {
    if ($(this).val() == '')
    {
        var newThing = prompt('Enter a name for the new thing:');
        var newValue = $('option', this).length;
        $('<option>')
            .text(newThing)
            .attr('value', newValue)
            .insertBefore($('option[value=]', this));
        $(this).val(newValue);
    }
});

Of course, this could be done better, and more cleanly, but it's a start.

Demonstration


After reading your comments, it appears you simply want to redirect the user to another form when they select a given option. In that case, you can simply do this:

$('select[name=things]').change(function() {
    if ($(this).val() == '')
    {
        window.location.href = 'CreateThingForm'; // Replace with the actual URL
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't do it this way, don't put button inside option.

alternatively you can :

<select name="things" onchange="checkAndAddOption(this)">

or

<select name="things" onclick="checkAndAddOption(this)">
.
.
.
</select>
<script>
function checkAndAddOption(selectElement) {
   if (selectElement.value === "") {
        var opt = document.createElement('option');
        opt.value = 'newVal';
        opt.innerHTML = 'textToDisplay';
        selectElement.appendChild(opt);
   }
}
</script>

2 Comments

I don't want to do this, what I need is to redirect the user to the "Create Thing Form", when they click on the link or button inside the select.
Then, simply change the code to create option to location.href = 'url-of-form'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.