THREADLY - set value to an empty string


#1

Hi guys, I am not quite sure how do I set value of id="comment" to an empty string AFTER it is submitted into comments. Could someone help me out?
Instructions:

After prepending html to the list, set the value of <input id="comment"> to an empty string "" to clear out the comment box.

And this is my code :

var main = function() {
  $('form').submit(function() {
    var comment = $('#comment').val();   
    var comments = $('.comments');
    if(comment !== "") {
      var html = $('<li>').text(comment);
      html.prependTo(comments);
    }

    return false;
  });
};

$(document).ready(main);

#2

Hey Martin,

Take a look at setting a value with jQuery val(). Using that, we could select #comment and call .val("") on it to clear out the input.
Like this:

$('#comment').val("");

I hope this helps! Feel free to ask any more questions you may have :)


#3

I tried exactly what you mentioned. Problem is, when I clicked submit button, page just refresh itself.

var main = function() {
  $('form').submit(function() {
    var comment = $('#comment').val();   
    var comments = $('.comments');
    if(comment !== "") {
      var html = $('<li>').text(comment);
      html.prependTo(comments);
      comment.val("");
    }

    return false;
  });
};

$(document).ready(main);

I am really sorry for bothering you :frowning:


#4

@devrockstar

No worries! I enjoy helping people out on here :)

So your problem is on line 8 - your comment variable is storing $('#comment')'s value, so by calling comment.val(""), you're essentially doing this:

$('#comment').val().val("");

...which makes no sense to the computer :) Try replacing line 8 with this instead:

$('#comment').val("");

and that way you won't be doing weird stuff the computer can't understand :smile:


#5

2 posts were split to a new topic: Why does val() work, but html() and text() don't?


#6

Hi! But why something like comment === ""; instead of $('#comment').val(""); doesn't work? How we can use variable comment ???? Thanks.


#7

@merril Sorry, would you try rephrasing your question please? I'm not sure I understand quite what you're asking.


#8

You recommended

to empty value of input.
My question is why not
comment === ""
??? (It doesn't work, I know)
How to use variable
comment
to empty input value?


#9

@merrii Ah, I see. Thanks for clarifying :slight_smile:
I don't think there's any way to do what you want, though. :confused:


#10

I'm not sure if this will help but...
When you use three equal signs together it is comparing, not changing. That is why in if then statements we use them, if this compared to that is the same then.... etc.
When you declare a variable and use the equals you are changing the value of something so you only use the one equals sign.

So you can't use what you were referring to as it is comparing the two and not changing anything.