1

I have to make javascript, select from one of this options by the text that is written,(Small, Medium, Large, Xlarge) not by the value, can someone please help me :)

<option value="s">Small</option>
<option value="M">Medium</option>
<option value="L">Large</option>
<option value="XL">XLarge</option>
</select>
Denny callà
  • 115
  • 1
  • 6
  • Could you provide some context? Like how you want it? You want the exact same as this but generated in JS? – Nex Feb 19 '21 at 22:01
  • Add the javascript code that you have tried and explain what it is doing wrong. – Charlie Wallace Feb 19 '21 at 22:09
  • Does this answer your question? [Get selected option text with JavaScript](https://stackoverflow.com/questions/14976495/get-selected-option-text-with-javascript) – ikiK Feb 19 '21 at 22:39

2 Answers2

1

document.querySelectorAll("select option").forEach(option => {
  option.text === "Medium" ? option.selected=true  : option;
})
<select>
  <option value="s">Small</option>
  <option value="M">Medium</option>
  <option value="L">Large</option>
  <option value="XL">XLarge</option>
</select>
ikiK
  • 6,328
  • 4
  • 20
  • 40
-1

This creates the exact same that you provided, just add more options.

let options = [{ name: 'small', value: 's' }, { name: 'medium', value: 'm' }]
var dropdown = document.createElement('select');
document.querySelector('body').appendChild(dropdown)

function addOpt(option, parentElement) {
    var opt = document.createElement('option');
    opt.setAttribute('value', `${option.value}`)
    opt.innerText = option.name
    parentElement.appendChild(opt)
}

options.forEach(option =>
    addOpt(option, dropdown)
)
Nex
  • 92
  • 9