0

I have read Links in dropdown options and using href links inside tag and several other questions in SO, however my question is a bit different.

I would like to have BOTH text AND href inside a select combo-box. Something like

<select id="mySelect">    
    <option value="-1" selected>choose an option to test</option>    
    <option value="1">Book 1 <a href="http://example.com/23?id=12">open site</a></option>    
    <option value="2">Book 2 <a href="http://example.com/11?id=10">open site</a></option> 
</select>

The idea is that the user can select from a combo-box, but also can go to an external site by clicking open site to view the Books before selecting them.

Something like this ie: clicking on the left-side of the <option> is a regular select, while clicking on the right-side of the <option> will send the user to another page

Is that possible? Running the code either ignores completely the href or complains Warning: validateDOMNesting(...): <a> cannot appear as a child of <option>.

Rob
  • 14,746
  • 28
  • 47
  • 65
rafahoro
  • 1,237
  • 13
  • 19

2 Answers2

2

Is that possible?

Not using using <a> element as child element of <option> element; <a> element is not a valid child node of HTML <option> element.

Permitted content Text, possibly with escaped characters (like é).

You can set the URL at the element data-* attribute and navigate to the URL at change event of <select> element

document.getElementById("mySelect")
.onchange = function() {
   var url = this.selectedOptions[0].dataset.href;
   if (url && confirm("Navigate to " + url + "?")) {
     location.href = url;
   }
}
:target {
  color: blue;
}
<select id="mySelect">    
    <option value="-1" selected>choose an option to test</option>    
    <option value="1" data-href="#Book1">Book 1 </option>    
    <option value="2" data-href="#Book2">Book 2 </option> 
</select>

<div id="Book1">Book 1</div>
<div id="Book2">Book 2</div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • but that will not enable to use the `select` both as `option` AND as `link`. IE: clicking on the left-side of the `option` is a regular select, while clicking on the right-side of the `option` will send the user to another page – rafahoro Jan 21 '18 at 05:15
  • @rafahoro You can alternatively use `
      ` and `
    • ` elements to achieve requirement, see [Displaying color in dropdown control using Javascript](https://stackoverflow.com/questions/35692330/displaying-color-in-dropdown-control-using-javascript)
    – guest271314 Jan 21 '18 at 05:41
0

You can use Fit.UI's Drop down control for that. The display value may contain HTML elements such as a link.

http://fitui.org/Control-DropDown.html

Jimmy Thomsen
  • 471
  • 3
  • 9