views:

31

answers:

2

I figured enough jQuery to select this chunk out of a huge HTML document. I want to select the value of subject, body, and date_or_offset. (these are name attributes as shown below). How do I go about this. Assuming this print is from alert($(this).html()) inside a call back function.

<p><label for="first">Subject</label>  <br>
   <input class="input" name="subject" type="text">
</p>
<p><label for="textarea">Body </label> <br>
   <textarea class="textarea" name="body" id="textarea" rows="5" cols="30"></textarea>  
</p>
<p><label for="first">Date <span>(xx/xx/xxxx) or Offset</span></label>  <br>
   <input class="input" name="date_or_offset" id="first" type="text">
</p>
+3  A: 

You can get it via .find() and .val(), like this:

var subject = $(this).find('input[name=subject]').val();
var body = $('#textarea').val();
var date = $('#first').val();

Since IDs are unique, the last 2 can be selected via a #ID selector directly, the first we find by name="subject" using an attribute-equals selector. If the IDs aren't unique (and they should be, fix it if that's the case) you can use a simular [name=xx] selector for the others, just use textarea instead of input for the body element.

Nick Craver
Is the `find` really necessary?
Gert G
@Gert - It depends he has an element, without more context you can't say for sure...but it's more efficient in any case. A `$('input[name=subject]')` is *really* calling `$(document).find('input[name=subject]')` which searches the entire document, this searches a much narrower scope, so it's a much faster selector.
Nick Craver
+1 That makes sense. Thanks Nick.
Gert G
Thank you nick, it works!
+3  A: 
$("input[name=subject]").val();
$("#textarea").val();
$("#first").val();
Bang Dao