Giorgos Papadopoulos
Giorgos Papadopoulos

Reputation: 11

<button> in to <option> for paragraph change

I have written the code you will see below but i would like to have a drop down menu like this ```

    <option value="sel">Select Paragraph</option>
    <option value="par1">Paragraph 1</option>
    <option value="par2">Paragraph 2</option>
    <option value="par3">Paragraph 3</option>
    </select> ``` 

I have tried using on click inside the but it didn't work, any help would be greatly appreciated.

<html>
<body>
</head>


<div class="topnav">
    <button onclick="myFunction()">change text on 1st paragraph</button>
    <button onclick="myFunction2()">change text on 2nd paragraph</button>
    <button onclick="myFunction3()">change text on 3rd paragraph</button>
    
</div>

<h1>1st Exercise</h1>



<p id="1">1st paragraph/p>

<p id="2">2nd paragraph/p>

<p id="3">3rd paragraph</p>

<script>
function myFunction() {
    var person = prompt("Please enter your text");
  document.getElementById("1").innerHTML = person;
}

function myFunction2() {
    var person2= prompt("Please enter your text");
  document.getElementById("2").innerHTML = person2;
}

function myFunction3() {
  var person3 = prompt("Please enter your text");
  document.getElementById("3").innerHTML = person3;
}
</script>
</body>
</html> ```

Upvotes: 1

Views: 37

Answers (1)

pavel
pavel

Reputation: 27082

Onclick doesn't work with option as you though...

You need to use onchange on select, you're looking for .selectedIndex and .value properties.

<select onchange="document.getElementById(this.selectedIndex).innerHTML = this.value">
    <option value="sel" >Select Paragraph</option>
    <option value="par1">Paragraph 1</option>
    <option value="par2">Paragraph 2</option>
    <option value="par3">Paragraph 3</option>
</select>

<p id="1">111</p>
<p id="2">222</p>
<p id="3">333</p>

Than you can change your paragraphs content as you need. Basic example to change paragraph with option's value is in my code snippet.

If you want just to select paragraph and set it's content from prompt dialog, it'd be

<select onchange="document.getElementById(this.selectedIndex).innerHTML = window.prompt()">

Upvotes: 1

Related Questions