Reputation: 2364
I'm running into an issue in jquery where my selected field isn't getting properly checked with jquery change()
= select_tag 'selector-email',
options_for_select([['Mailer', 0], ['Invite Student', 1], ['Invite Visitor', 2]])
Above is what my html is parsed as and then in jquery i select the id and use its index to find the value.
function mailerChange() {
$("#selector-email").change(function() {
console.log($('#selector-email')[0].selectedIndex)
})
}
this works completely fine when I try on codepen but for some reason in rails I just get 0 back as a value. Even when I try in console on my webpage. It can find the selector field but it can't tell what's selected properly.
What's going on here is there a valid reason for this?
Upvotes: 1
Views: 1002
Reputation: 20646
According to your codepen, you are defining the handler on DOM ready and your element is added later.
$(document).ready(function() {
mailerChange();
})
Try event delegation using jQuery .on()
,
function mailerChange() {
$(document).on("change","#selector-email",function() {
console.log($('option:selected',this).index())
})
}
Upvotes: 2