How to delete a term inserted in a form using jQuery?

Asked

Viewed 64 times

3

The code below is part of a function that uses a search term in a text field to extract images from the Flickr site. After typing the word to do the search, it inserts the text below the field, just to show that it is looking for that, but the problem is that whenever I enter a new term, it inserts the new term on the page, instead of zeroing out the images and the term.

var $tag,
    $status,
    $msg;

    if ($("main .container .busca input").val() !== "") {
        $status = $("<p>").text($("main .container .busca input").val());
        $tag = $("main .container .busca input").val();
        $msg = ("<p> Encontramos essas imagens para você:</p>");
        $("main .container .busca").append($msg).append($status);
        $("main .container .busca input").val("");
    };

Buscando fotos

I would like every time I typed a new term, it erased the previous one, as well as the images, and inserted the new term under the text box. Could someone give me a clue how to do this?

1 answer

4


Try this:

var $tag,
$status,$msg;

if ($("main .container .busca input").val() !== "") {
    $("main .container .busca p").text("");
    $status = ("<p>" + $(".busca input").val() + "</p>");
    $tag = $("main .container .busca input").val();
    $msg = ("<p> Encontramos essas imagens para você:</p>");
    $("main .container .busca").append($msg).append($status);
    $("main .container .busca input").val("");
};

or that, depending on your HTML code:

var $tag,
$status,$msg;

if ($("main .container .busca input").val() !== "") {
    $("main .container .busca p").remove();
    $status = ("<p>" + $("main .container .busca input").val() + "</p>");
    $tag = $("main .container .busca input").val();
    $msg = ("<p> Encontramos essas imagens para você:</p>");
    $("main .container .busca").append($msg).append($status);
    $("main .container .busca input").val("");
};
  • The first solution you presented has already solved, I even adjusted it to do the same with the images. Thank you! ^_^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.