ineedahero ineedahero - 2 months ago 6
jQuery Question

JQuery won't pull text from text field within Rails Form

I'm new to Jquery and this is making me pull my hairout.

<table>
<tr>
<th> User Data </th>
<th> </th>
</tr>
<tr>
<td> <%= f.label :user_name, 'User name' %> </td>
<td> <%= f.text_field :user_name %> </td>
</tr>
<tr>
<td> <%= f.label :hobby, 'Hobby' %> </td>
<td id="takeme"> <%= f.text_area :hobby %> </td>
</tr>
</table>
<a id="send-thoughts" href="">Click</a>
<script>
jQuery("a#send-thoughts").click(function() {
var thought = jQuery("td#takeme").val();
alert(thought);
});
// $("td#takeme").val("monkey cheese");
</script>


This won't pull the value from the "takeme" field when I click the link....why not??

Note: changing

jQuery("td#takeme").val();


to

jQuery("td#takeme").hide();


does, indeed, hide the field -- so it does work for at least something. But I can't pull the contents!!!

RSB RSB
Answer

Use this instead, you are selecting the parent instead of the actual input

$("td#takeme > textarea").val();

or

assign an id directly to the text area

<%= f.text_area :hobby, id: 'hobby_text' %>

and then in JS

$("#hobby_text").val();

Hope that helps!