Reputation: 335
I'm trying to place an onchange event in a select box but for some strange reason it does not work. This is my selectbox:
<%= f.label :Tipe, "Tipe:", class: "control-label col-md-1" %>
<div class="col-md-3">
<%= f.select :Tipe, ['Mont','Vol'],onChange: "myFunction()", class: "form-control"%>
</div>
and this is my javascript:
<script>
function myFunction() {
alert( "Handler" );
}
</script>
Upvotes: 0
Views: 786
Reputation: 814
Inline javascript is considered bad practice, for reason like this where it's difficult to debug. Perhaps you should try:
In your page js file, or script tags- whichever:
var myFunction = function(){
// do whatever
}
$('.form-control').on('change', function(){
myFunction();
});
The 'on' event listener allows to bind any even to an element class/ id. Better still, binding to the id of the parent element, you can insure events stay connected to child events that may be refreshed from time to time by ajax requests. For example
# parent html.erb file
<div id="container">
<%= render 'form' %>
</div>
# inside form partial
<%= f.label :Tipe, "Tipe:", class: "control-label col-md-1" %>
<div class="col-md-3">
<%= f.select :Tipe,
['Mont','Vol'],
onChange: "myFunction()",
class: "form-control"
%>
</div>
# then in JS
$('#container').on('change', '.form-control', function(){
//do something
});
Otherwise, I think your function as it stands doesn't work because you're missing the semi-colon:
"onChange: "myFunction();"
If not, check the 'onChange'/ 'change' binding. What constitutes a 'change'? You may be better using on 'click' if an action is to be performed after some user interaction.
Hope this helps.
Upvotes: 1