views:

855

answers:

2

I have a form with a text area input. I'm using JQuery to submit the form via an AJAX request in order to update a database. My problem is that I'm having difficulty retrieving the data from the text area input. If the input has an id of "txtBody" I have tried:

var body = $("#txtBody").val(); // This adds 'undefined' to the database  
var body = $("#txtBody").text(); // This adds nothing to the database  
var body = $("#txtBody").html(); // This adds 'NULL' to the database

I can't think of how else to access the data. Any ideas?

+5  A: 

You say adds to the database. Have you debugged the actual code to make sure you're not just sending the data with one variable name and trying to add it with another? Because if you have a field like this:

<input type='text' id='txtBody' value='test'>

Or like this:

<textarea id='txtBody'>test</textarea>

Doing $('#txtBody').val(); will return the value "test". There's no ifs or buts about it.

Maybe you should post some more of your code so we can spot what is wrong, as I am guessing that's not the actual problem you are having.

Paolo Bergantino
Ok, I think I might have confused the issue. The id refers to an html <textarea> tag. This sort of tag cannot accept a value attribute. As such, it's not technically an input ie it is not an <input> tag. When you type in a textarea I'm assuming the data is held between the opening and closing tags, but I'm not sure.
musoNic80
jQuery is smart enough to figure out what you want, not to mention that natively textarea elements store their value the same way as input elements. Calling val() will correctly return the text between the textarea tags. As I said, your problem is probably elsewhere. You should post some more code or try to simplify what you are doing and you are probably going to spot what is wrong.
Paolo Bergantino
ok that's interesting. I wanted to make sure that calling val() was definitely the way to go. Now I know it is I'll have a look at what else might be going wrong. Thanks!
musoNic80
+3  A: 

The jQuery documentation suggests that val() was not available is older versions of jQuery. Is your version up to date?

jdigital