Reputation: 553
I am using javascript to hide the post button until text has been entered into the form. It works fine but when i have the form being rendered for each post in a loop it only works for the first post and the button isn't hidden for the rest.
Here is the javascript:
$(function(){
$("#button").hide();
$("#inputBody").keyup(function() {
var val = $(this).val();
if (val.length > 0) {
$('#button').show();
}
else {
$('#button').hide();
}
});
});
Here is the form:
<%= f.input :body, input_html: { :id => "inputBody" } %>
<%= f.submit "Answer", { :id => "button", class: "button5" } %>
and here is the view:
<% @questions.each do |question| %>
<%= question.body %>
<%= render :partial => "answers/form" %>
<% end %>
Here is the html for the first form in the loop vs the second.
<form accept-charset="UTF-8" action="/questions/61-the-best/answers" class="simple_form answer" id="new_answer" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="opkAO1vlXgbqHebqee839dtFv1lsA/osUexmGTU2x7k=" /></div>
<div class="input text optional"><textarea class="text optional hello3" id="inputBody" name="answer[body]" placeholder="Answer" rows="1">
</textarea></div>
<input class="button5" id="button" name="commit" type="submit" value="Answer" />
</form>
Second (button is showing):
<form accept-charset="UTF-8" action="/questions/62-this-is-a-test-question/answers" class="simple_form answer" id="new_answer" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="opkAO1vlXgbqHebqee839dtFv1lsA/osUexmGTU2x7k=" /></div>
<div class="input text optional"><textarea class="text optional hello3" id="inputBody" name="answer[body]" placeholder="Answer" rows="1">
</textarea></div>
<input class="button5" id="button" name="commit" type="submit" value="Answer" />
</form>
Upvotes: 1
Views: 359
Reputation: 482
It looks like you reuse the same id (inputBody) multiple times. If you want to identify multiple similar elements, use a class. Ids are supposed to identify a single element.
Try using inputBody as a class and $(".inputBody") to select it. Apply the same principle to selecting the buttons. One way to select the appropriate button is to look at the siblings of inputBody's parent.
Here's the JS Fiddle: http://jsfiddle.net/4JDxS/
And the code snippet (just the javascript) for quick reference. See the JS fiddle for the HTML changes:
$(function(){
$(".myButton").hide();
$(".inputBody").keyup(function() {
var val = $(this).val();
if (val.length > 0) {
$(this).parent().siblings('.myButton').show();
}
else {
$(this).parent().siblings('.myButton').hide();
}
});
});
Upvotes: 1