Home > Mobile >  How to connect div and javascript functions and event and create function that proceed value from dr
How to connect div and javascript functions and event and create function that proceed value from dr

Time:09-30

I created a drop-down list with car names. I want to create an event in javascript which after selecting some elements from the drop down list will be passed to the div block using that function. For example, I select an Audi from my drop-down list and in the div block to print it is an Audi. I want to create an event and a function that, after selecting one of the options from the drop-down list with that function, will be passed to the giant block. I've created a function that takes the value of an item from a drop-down list but I just don't know how to proceed to my goal Here is my code

function jsFunction(value) {
  var div1 = document.getElementById('div1')
  var newparagraph = document.createElement("p");
  newparagraph.innerText(value);
  div1.appendChild(newparagraph);
}
<select id="ddl" name="ddl" onmousedown="this.html='';" onchange="jsFunction(this.value);">
  <option id="Audi1" value='1'>Audi</option>
  <option id="Mercedes2" value='2'>Mercedes</option>
  <option id="BMW3" value='3'>BMW</option>
</select>
<div id="div1">

</div>

CodePudding user response:

[<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
    <script>
          document.getElementById("ddl").addEventListener("change", function() {
  if (!this.value) return 
  var div1 = document.getElementById('div1')
  var newparagraph = document.createElement("p");
  newparagraph.textContent = 'You chose '   this.options[this.selectedIndex].text;
  div1.appendChild(newparagraph);
})
        
        </script>
        
        <select id="ddl" name="ddl">
            <option value=''>Please select</option>
            <option value='1'>Audi</option>
            <option value='2'>Mercedes</option>
            <option value='3'>BMW</option>
          </select>
          <div id="div1">
          
          </div>


</body>
</html>][1]

CodePudding user response:

newparagraph.innerText = value; will show 1, 2 or 3

You need the text of the options

note I wrrap the code in a load event handler so we can place the code where we want including in the head

window.addEventListener("load", function() {
  document.getElementById("ddl").addEventListener("change", function() {
    if (!this.value) return
    var div1 = document.getElementById('div1')
    var newparagraph = document.createElement("p");
    newparagraph.textContent = 'You chose '   this.options[this.selectedIndex].text;
    div1.appendChild(newparagraph);
  });
});
<select id="ddl" name="ddl">
  <option value=''>Please select</option>
  <option value='1'>Audi</option>
  <option value='2'>Mercedes</option>
  <option value='3'>BMW</option>
</select>
<div id="div1">

</div>

  • Related