I have the following function that is meant to get called after a form I submitted (this method is in my application.js folder in my rails app):
var addToTopics = function() {
var result = "";
var checkedTopics = $(".topic-checkbox:checked");
$.each(checkedTopics, function(i, topic) {
if(i == 0) {
result = result + $(topic).attr('value');
}
else {
result = result + ", " + $(topic).attr('value');
}
});
return result;
};
$("#new_comment").submit(function() {
var ListOfTopics = addToTopics();
$('#comment_topics').val(ListOfTopics);
alert($('#comment_topics').val());
return true;
});
HTML
<form method="post" id="new_comment" class="new_comment" action="/comments" accept-charset="UTF-8"><div style="margin:0;padding:0;display:inline"><input type="hidden" value="✓" name="utf8"><input type="hidden" value="8vLhtuco+TAkeB+9kQ0gERvA54BD/BnjJuguWxuXWHQ=" name="authenticity_token"></div>
<div class="field">
<label for="comment_comment">Comment</label>
<br>
<textarea rows="20" name="comment[comment]" id="comment_comment" cols="40"></textarea>
</div>
<div class="field">
<input type="hidden" value="28" name="comment[review_id]" id="comment_review_id">
</div>
<div class="field">
<input type="hidden" value="1" name="comment[user_id]" id="comment_user_id">
</div>
<div class="field">
<input type="hidden" value="" name="comment[topics]" id="comment_topics">
</div>
<div class="actions">
<input type="submit" value="Create Comment" name="commit" id="comment_submit">
</div>
</form>
But this dosen’t seem to be getting called as the alert dosent even go off when I submit my form.
Any idea why? Thanks
You need to ensure the code attaching the listener runs after the form has been rendered to the dom. this is one way of doing it: