Calling JS function by Select

Asked

Viewed 1,083 times

0

I have a function in JS and I intend to run it when changing the select, I call it so:

$("#table1 .td_select select").on("click select", function(){
    calcSub($(this).closest("tr"));
    calcTotal();
});
<div class="table1">
    <td class="td_select">			
	    <select name="id_lub" id="id_lub" class="btn-block">
		    <option value="">Nenhum</option>
            ...
		</select>
    </td>
</div>

If I change the option of select the function is not executed, but if I click on the select he performs the function. I believe I’m calling the function the wrong way up on JS. Following the same structure, which is the right way to insert the data between $()?

  • 1

    You could uasr the change like this: $(Document). on('change', '#table1 . td_select', Function(){ /code here/ });

2 answers

3


To call a function when changing the select you can use the onchange that will trigger the call whenever you select another option

function mudarSelect(valor){
  console.log(valor);
}
<select onchange="mudarSelect(this.value)">
    <option value="valorA">Valor A</option>
    <option value="valorB">Valor B</option>
    <option value="valorC">Valor C</option>
</select>

in your code, using Jquery, you are using the selector the wrong way. Your corrected code would look like this:

$("#id_lub").on("change", function(){ //usando o id do select
    calcSub($(this).closest("tr"));
    calcTotal();
});

<div class="table1">
    <td class="td_select">          
        <select name="id_lub" id="id_lub" class="btn-block">
            <option value="">Nenhum</option>
            ...
        </select>
    </td>
</div>

1

According to the Jquery documentation you can do so $(seletor).change(function() { logica da função }, try to use this way to the power of .on('change'). And preferably for selectors with id as I did in the example below:

$("#id_lub").change(function() {
   console.log('x');
})
    <script
   src="https://code.jquery.com/jquery-3.3.1.min.js"
   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
   crossorigin="anonymous">
</script>


        <div class="table1">
           <td class="td_select">			
        			<select name="id_lub" id="id_lub" class="btn-block">
        				<option value="">Nenhum</option>
                <option value="">Nenhum1</option>
                <option value="">Nenhum2</option>
                ...
      </select>
           </td>
        </div>

Browser other questions tagged

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