Javascript Onclick

Asked

Viewed 575 times

0

In the code below is caught the option value selected and used as link (href), but I need it to be used as onClick:

<form action="" method="POST" role="form">
  <li>
    <select id="bens" name="bens" class="form-control" 
            onChange="alterarComboVeiculo(this.value); ">
      <option value='' selected>Selecione</option>
      <option value='86764554'>867</option>
      <option value='88564554'>885</option>
    </optgroup>
    </select>                
  </li>
</form>
<span id="alex">Selecione</span><a onclick="" href="" id="url"></a>

here where you are href="" the empty space is replaced by the option value selected

<script type="text/javascript">
var select = document.getElementById('bens'),
output = document.getElementById('alex');

select.addEventListener('change', function() {
output.textContent =  '' ;

var index =  this.selectedIndex;
var prefix = "";
var suffix = "";

prefix = 'addOverlay_' + select.options[select.selectedIndex].text + "();";

var link = document.getElementById("url");

link.href = prefix;

link.innerHTML = "Alex";
});
</script>
  • 1

    You couldn’t do it link.addEventListener("click", prefix)?

1 answer

0

If the function is global you can access it from the object window and put it directly into onclick the element you obtained by html.

Also missing was a label of <optgroup>, as well as the attribute onclick of <a> no longer need to be it is created dynamically.

var select = document.getElementById('bens'),
  output = document.getElementById('alex');
  
var link = document.getElementById("url"); //capturado só uma vez

select.addEventListener('change', function() {

  var prefix = 'addOverlay_' + select.options[select.selectedIndex].text; //sem o ();

  link.href = prefix;  
  link.onclick = window[prefix]; //atribuir a função correta ao onclick do link

  link.innerHTML = "Alex";
});

function addOverlay_867(){
  console.log("overlay 867");
  return false; //para nao navegar quando clica no link
}

function addOverlay_885(){
  console.log("overlay 885");
  return false; //para nao navegar quando clica no link
}
<form action="" method="POST" role="form">
  <li>
    <!--select sem onchange pois o evento change ja está a ser interpretado em javascript-->
    <select id="bens" name="bens" class="form-control">
     <optgroup> <!-- faltava esta etiqueta-->
      <option value='' selected>Selecione</option>
      <option value='86764554'>867</option>
      <option value='88564554'>885</option>
    </optgroup>
    </select>
  </li>
</form>
<span id="alex">Selecione</span>
<a href="" id="url"></a>

If the link does not navigate to any url and simply executes code from a javascript function then it is most advised not to be a link and become a <div> or <span> with the appropriate style.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.