title: Rails and jQuery: How to select input from a specific form
body: <p>I have a rails app with a job model, and on the index page, each job has a form. I need to be able to access the specific form everytime the submit button is selected, so I can take the input for the form and perform some jQuery validation with it.</p>
  
  <p>Here is some of my index.html page.</p>
  
  <pre><code>&lt;ul&gt;
    &lt;% @unassigned.each do |job| %&gt;
      &lt;li&gt;
              &lt;div class="row new-message"&gt;
                &lt;div class="small-12 columns"&gt;
                    &lt;%= form_for @message do |f| %&gt;
                      &lt;%= f.text_area :body, {placeholder: 'enter a new message...'} %&gt;
                      &lt;%= f.hidden_field :job_id, value: job.id %&gt;
                      &lt;%= f.submit 'send message', class: 'button small radius secondary message-button', "data-job-id" =&gt; job.id %&gt;
                      &lt;div id="message&lt;%= i %&gt;-validation-errors"&gt; &lt;/div&gt;
                    &lt;% end %&gt;
                &lt;/div&gt;
              &lt;/div&gt;
      &lt;li&gt;
    &lt;% end %&gt;
  &lt;ul&gt;
  </code></pre>
  
  <p>And here is the javascript/jQuery where I try to select the input from a specific form</p>
  
  <pre><code>var messages;
  
  messages = function() {
  
      $('.message-button').click(function(e) {
          var id = $(this).data('job-id');
          messageValidation(e, id);
      });
  
      function messageValidation(e, id) {
          var body = $('#message_body').val();
          var div = '#message' + id + '-validation-errors';
      if(body == "") {
        $(div).html('');
        e.preventDefault();
        $(div).html('&lt;small style="color:red"&gt; Message body empty &lt;/small&gt;');
      }
      };
  
  };
  
  $(document).ready(messages);
  </code></pre>
  
  <p>The index page will have a form for each job, and I want there to be front end validation that checks when the button is submitted, that the <code>body</code> field is not empty. It works fine the first time, but after going back to the index page, and trying to validate a second time <code>var body = $('#message_body').val();</code> always seems to be empty, whether I put anything in the body or not. I believe it has something to do with the fact that since there is the same form for each job, there are multiple <code>#message_body</code> id's on the same page, and it is selecting the incorrect one. I am new to jQuery and javascript can someone please help me</p>