Reputation: 15860
I am using parent()
and find()
method to access the textarea of the correspoding button.
But I get undefined each time. I have tried it in a jsfiddle, but that fiddle works. Here is the code
<div>
<textarea id="textarea"></textarea>
<button onclick="commentThis('10')">Post Comment</button>
<button onclick="neverMind('10')">Never Mind</button>
</div>
jQuery code is as
function commentThis(postId) {
var comment = $(this).parent().find("#textarea").val();
if (comment != "" || comment != null) {
$.ajax({
url: "/ajax_requests/post_comment",
data: "postId=" + postId + "&type=comment&comment=" +
comment + "&page=default",
success: function (result) {
$(".comments").append(result);
$("#textarea").val("");
$("#textarea").css("height", "20px");
}
})
}
}
But it always give me a console error of undefined, saying value cannot be taken from undefine attribute.
You can see the error message here:
here is the fiddle that I created and which works. http://jsfiddle.net/afzaal_ahmad_zeeshan/ZBcby/
Upvotes: 0
Views: 39
Reputation: 150030
When you call your function like this:
onclick="commentThis(@row.PostId)"
...it doesn't set the value of this
to the element that was clicked. this
will be window
. You could change it to explicitly set the value of this
:
onclick="commentThis.call(this,@row.PostId)"
You will also need to change the following line of your function:
if (comment != "" || comment != null) {
because that if condition will always be true because either comment != ""
will be true or comment != null
will be true. You probably meant to use &&
instead of ||
:
if (comment != "" && comment != null) {
...but you can simplify that to this:
if (comment) {
(And in practice given that comment
is the result of calling .val()
it won't ever be null
anyway, it will either be a string or undefined
- and if you get the selector right it won't be undefined
.)
Upvotes: 1
Reputation: 237865
if (comment.value != "" || comment.value != null) {
You got the value with val()
. You therefore have a string. You are attempting to get the value
property of a string. This won't work.
This will:
if (comment != "" || comment != null) {
Or, in fact, even simpler:
if (comment) {
Upvotes: 2