Javascript Onclick

0

In the code below I get the option value selected and used as a link (href) , however 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 href="" is replaced by empty space with 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>
    
asked by anonymous 27.07.2017 / 16:01

1 answer

0

If the function is global, you can access it by the window object and place it directly in onclick of the element that you got by html.

A <optgroup> tag was missing as well as the onclick attribute of <a> is no longer needed to be 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 execute code from a javascript function then it is advisable not to be a link and become a <div> or <span> with the appropriate style.

    
27.07.2017 / 17:25