-1

The code below is for a dropdown in html:

<html>
<body>

    <select id="demo1" name="demo2" type="text">
      <option value="london">London</option>
      <option value="paris">Paris</option>
      <option value="tokyo">Tokyo</option>
    </select>

</body>
</html>

How to make the option with value "paris" selected? Please consider it is not possible to change anything in the code above.

The code was edited to give more details because unfortunately the answers did not work on this question.

The below code did not work as well:

<script>
        var selectedtext = "paris";
        document.getElementById("demo1").selected = selectedtext;
</script>
dxb
  • 273
  • 2
  • 13
  • `document.querySelector('option[value=paris]').selected = true;`? – Aluan Haddad Feb 25 '21 at 18:24
  • 1
    @AluanHaddad it is not name ;) – epascarello Feb 25 '21 at 18:25
  • There is no reason that either of the approaches I've shown in my answer below wouldn't work, as I've shown it working in my answer. However, your `select` has `type=text`, which is invalid since a `select` can't have a `type` attribute. If it's not working, there is a different issue. – Scott Marcus Feb 25 '21 at 18:56
  • Are you getting any errors in your console? Have you made sure to add the `script` ***after*** the HTML has been parsed by placing it just before the closing `body` tag? – Scott Marcus Feb 25 '21 at 19:00
  • Also, the code you've shown that you tried that didn't work is not code that anyone here has suggest you use. – Scott Marcus Feb 25 '21 at 19:07

3 Answers3

3

If you know what position the option you want selected will always be in, you can use either of the following approaches:

  1. To modify the DOM object property of the option, set the .selectedIndex property (which starts counting from 0) on the element.

document.querySelector("select").selectedIndex = 1;
<html>
<body>
    <!-- A select element can't have a type attribute -->
    <select id="demo1" name="demo2" type="text">
      <option value="london">London</option>
      <option value="paris">Paris</option>
      <option value="tokyo">Tokyo</option>
    </select>
</body>
</html>
  1. If you do want to alter the HTML state of the element, you can use the setAttribute() method on the element:

document.querySelector("select").options[1].setAttribute("selected", "selected");

// Just for demo purposes:
console.log(document.querySelector("select").outerHTML);
<html>
<body>
    <!-- A select element can't have a type attribute -->
    <select id="demo1" name="demo2" type="text">
      <option value="london">London</option>
      <option value="paris">Paris</option>
      <option value="tokyo">Tokyo</option>
    </select>

</body>
</html>

But, if you only know the text of the option that should be selected and not its position, then you can use the following CSS selector with .querySelector to isolate the right option and select it:

let input = "paris";

// Either one of these will work:

// To affect the HTML state:
document.querySelector("option[value='" + input + "']").setAttribute("selected", "selected");

// To affect the DOM Object property:
document.querySelector("option[value='" + input + "']").selected = true;

// Just for demo purposes:
console.log(document.querySelector("select").outerHTML);
<html>
<body>
    <!-- A select element can't have a type attribute -->
    <select id="demo1" name="demo2" type="text">
      <option value="london">London</option>
      <option value="paris">Paris</option>
      <option value="tokyo">Tokyo</option>
    </select>

</body>
</html>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Probably because it's brittle. I didn't down vote however – Aluan Haddad Feb 25 '21 at 18:27
  • @AluanHaddad The requirement is brittle, not the solution. – Scott Marcus Feb 25 '21 at 18:29
  • Fair enough, sir – Aluan Haddad Feb 25 '21 at 18:30
  • Where did you get (1) from? The code in the question is a simplify version of the main code. So the answer also can be simple too. – dxb Feb 25 '21 at 19:08
  • @dxb The 1 represents the index of the `option` that should become selected. In your example "Paris" is the second `option`. Indexes start counting from 0, so the second one would be 1. You did not indicate in your question that what you are showing is a simplified version of the code. Are you saying that it may not always be the second `option`, but it will always be the `option` with `Paris` as the text? – Scott Marcus Feb 25 '21 at 19:11
  • It was only an example, and not always the same number for the choice to put 1 or 2 for the index. The point is to make the option selected based on the text from other input that can be different each time. This is why I used a variable for the text. – dxb Feb 25 '21 at 19:14
  • @dxb Ok (that really should have been stated in the question), but I have updated my answer. What you're looking for is at the bottom. – Scott Marcus Feb 25 '21 at 19:16
  • Thank you. Your answer works now. – dxb Feb 25 '21 at 19:27
1

You can do this in multiple ways:

if the options might change order you select the value itself

document.querySelector('[value=paris]').selected = true
<select>
  <option value="london">London</option>
  <option value="paris">Paris</option>
  <option value="tokyo">Tokyo</option>
</select>

Otherwise you can use selectIndex:

document.querySelector('select').selectedIndex = 1
<select>
  <option value="london">London</option>
  <option value="paris">Paris</option>
  <option value="tokyo">Tokyo</option>
</select>
dippas
  • 58,591
  • 15
  • 114
  • 126
-1

this way....

document.querySelector('select').value = 'paris';
<select>
  <option value="london">London</option>
  <option value="paris">Paris</option>
  <option value="tokyo">Tokyo</option>
</select>

Or, with full use in a form:

const myForm = document.forms['my-form']


myForm.city.value = 'paris'
<form  name="my-form">

  <select name="city">
    <option value="london">London</option>
    <option value="paris">Paris</option>
    <option value="tokyo">Tokyo</option>
  </select>

</form>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 1
    The OP is not even showing a `form` and no `form` is required in order to use a `select` in many cases, so not sure why you show that. Also, accessing a `form` via `document.forms` is considered a legacy approach, whereas a DOM method like `querySelector()` is the modern, standard approach. – Scott Marcus Feb 25 '21 at 18:28
  • 1
    Read the comment? – Scott Marcus Feb 25 '21 at 18:29
  • @ScottMarcus Another point of view is to think that the PO forgot to show its use of a form, without being aware of the importance of the usefulness of a hierarchy in this case, which avoids having to reference X times each of the multiple elements present in a form. What beginners are too rarely aware of. There are enough of you here to show this straightforward approach. a different point of view is always useful and does not deserve to be sanctioned with a negative vote. – Mister Jojo Feb 25 '21 at 18:37
  • The OP has stated that the HTML cannot be changed and your answer shows changed HTML. Also, as I said, even if you were to use a `form`, the modern, standard would be to use `.querySelector()` and not legacy approaches. Lastly, accessing the `form` doesn't save you anything when you then have to access different elements within the form, you still have to perform those queries, so whatever benefit you seem to be implying by using a `form` doesn't really exist. – Scott Marcus Feb 25 '21 at 18:40
  • @ScottMarcus OK, since you have everything answered, I improved my answer. – Mister Jojo Feb 25 '21 at 18:49
  • But you still have all that incorrect stuff? – Scott Marcus Feb 25 '21 at 18:52
  • Oh no, no, no! **"Working" code is in no way synonymous with correct or good code.** And out of date or poorly performant code is not useful to know. In fact, some of the biggest harm done here is by showing old, inefficient code. You are free to post whatever answer you like.... And I am free to vote on the quality of it, just as you are. That's how the site works. – Scott Marcus Feb 25 '21 at 18:58