landt5
landt5

Reputation: 23

How do I show option title from select menu in another spot

I am trying to get the title attribute from a selected Option in a Select menu. I have spent over a day on this and I am seeking help. I found a couple of ways to use the value attribute but now I need to use the title attribute somewhere else on the page.

Here is my current attempt although I have been through many iterations. I have listed two possible scripts although only one will eventually be used. The first possible script might include Jquery and if it does and it can be used here, can you translate it into Javascript, as I am not good at either? Do I have the elements in the correct order?

<select id="amount_id" onclick="function()">
<option value="" disabled="disabled">Amount</option> 
  <option value="0" title="None">0</option>
  <option value="1" title="One Quarter">1/4</option>
  <option value="2" title="One Half">1/2</option>
  <option value="3" title="Three Quarters">3/4</option>
  <option value="4" title="All">100%</option>
</select>
<textarea id="displayTitle"></textarea>
<script>
$(document).ready(function(){
    $(document).on('click','#amount_id',function(){
       var result = $("option:selected",this).attr('title');
       $("#displayTitle").text(result);
    });
});
</script>

OR

<script>
function run(){
  document.getElementById("displayTitle").value = 
document.getElementById("amount_id").value;}
</script>

Thank you.

Upvotes: 1

Views: 2108

Answers (1)

Djaouad
Djaouad

Reputation: 22776

Here is a JavaScript alternative of the first code :

<select id="amount_id">
<!-- removed onclick -->
<option value="" disabled>Amount</option> 
  <option value="0" title="None">0</option>
  <option value="1" title="One Quarter">1/4</option>
  <option value="2" title="One Half">1/2</option>
  <option value="3" title="Three Quarters">3/4</option>
  <option value="4" title="All">100%</option>
</select>
<textarea id="displayTitle"></textarea>
<script>
  document.getElementById("amount_id").addEventListener('change',function(){
     var eTitle = this.options[this.selectedIndex].getAttribute('title');
     document.getElementById("displayTitle").value = eTitle;
  });
</script>

Upvotes: 1

Related Questions