0

Estoy trayendo un info de una api, escribo un numero en la barra de búsqueda y me muestra 3 elementos correctamente, ahora necesito reiniciar el value de ese input porque si cambio el numero digamos por 5 me mostraría 8 elementos en total, tres anteriores + cinco de la nueva búsqueda, como puedo reiniciar la variable?

he tratado así news_quantity_val = "";

pero me sigue mostrando los resultados de la antigua búsqueda + los de la nueva búsqueda

como podría hacer para que no acumule los resultados.

Gracias.

var news_quantity = document.getElementById("quantity");
var searhing_button = document.getElementById("searching_btn");

searhing_button.addEventListener("click", ()=>{

    var news_quantity_val = news_quantity.value;
    if(news_quantity_val !== ""){
        
        async function chuck(url){
            var getting_phrases = await fetch(url);
            var json_transform = await getting_phrases.json();
            
            var new_news = document.getElementById("news");
            var new_element = document.createElement("div");
            new_element.classList.add("news", "d-flex", "justify-content-around", "align-items-center", "mt-5", "rounded", "p-2", "shadow-sm", "mb-5"); 
            new_element.innerHTML = `<div data-toggle="modal" data-target="#exampleModal"><img src="chuck-norris-logo.png" alt=""></div>
            <p class="m-0">id: ${json_transform.id}</p>`
            
            new_news.appendChild(new_element);    
        }

        
        for(i=0; i<news_quantity_val; i++){
            chuck("https://api.chucknorris.io/jokes/random");
        } 
     
    } 

});
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

#news h4{
    font-size: 1.5rem;
}

#date {
    font-size: .7rem;
}

#news_id {
    font-size: .5rem;
}

*{
    margin: 0;
    box-sizing: border-box;

}

.img-hero{
    height: 300px;
    width: 500%;
    object-fit: cover;
}

footer{
    text-align: center;
    margin-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chuck Norris</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <nav class="navbar navbar-expand p-0">
            <button class="navbar-toggler"  type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
          
            <div class="collapse navbar-collapse" id="navbarSupportedContent" style="margin-top: 30px;">
              <form class="form-inline my-2 my-lg-0 w-100">
                <input id ="quantity" class="form-control mr-sm-2" type="number" placeholder="Search" style="width:92%" aria-label="Search">
                <button id="searching_btn" class="btn btn-outline-success my-2 my-sm-0" type="button">Search</button>
              </form>
            </div>
        </nav>


        <div id="news">
            
        </div>
        <!-- <div class="news d-flex justify-content-around align-items-center mt-5  rounded p-2 shadow-sm">
            <div data-toggle="modal" data-target="#exampleModal"><img src="chuck-norris-logo.png" alt=""></div>
            <p class="m-0">created_at: "2020-01-05 13:42:28.664997"</p>
        </div> -->


        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="exampleModalLabel">id: 123456789</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                </div>
                <div class="modal-body pt-5 pb-5 pl-5 pr-5">
                    <p id="news_id" class="text-center text-muted font-italic">updated_at: 2020-01-05 13:42:25.352697</p>
                    <div class="d-flex justify-content-center mt-5 mb-5">
                        <img src="chuck1.jpg"  alt="">
                    </div>
                    <h4 class="text-center">Chuck Norris solo-ed Everest in shorts and a tank-top.</h4>
                </div>
                <div class="modal-footer border-0">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                </div>
            </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <script src="script.js"></script>
</body>
</html>

3 respuestas 3

1

Debes limpiar el contenido de tu lista, dado que el metodo appendChild lo que hace es agregar nuevo hijos a la lista, estonces debes desaparecer los hijos anteriores con new_news.innerHTML = "" para que queden solo los nuevos.

Ademas que no es necesario tener tu función chuck declarada dentro del evento, declara abajo o arriaba así podras llamarla sin problemas ( tambien así es más legible el código).

Código de Repuesta:

var news_quantity = document.getElementById("quantity");
var searhing_button = document.getElementById("searching_btn");

searhing_button.addEventListener("click", ()=>{

    var news_quantity_val = news_quantity.value;
    if(news_quantity_val !== ""){
        
        var new_news = document.getElementById("news"); 
        new_news.innerHTML = ''; /* <--VACIO EL LISTADO */           
        for(i=0; i<news_quantity_val; i++){
            chuck("https://api.chucknorris.io/jokes/random");
        } /* <-- AGREGA NUVOS ELEMENTOS */
     
    } 

});

 async function chuck(url){
            var getting_phrases = await fetch(url);
            var json_transform = await getting_phrases.json();
            
            var new_news = document.getElementById("news");
            var new_element = document.createElement("div");
            new_element.classList.add("news", "d-flex", "justify-content-around", "align-items-center", "mt-5", "rounded", "p-2", "shadow-sm", "mb-5"); 
            new_element.innerHTML = `<div data-toggle="modal" data-target="#exampleModal"><img src="chuck-norris-logo.png" alt=""></div>
            <p class="m-0">id: ${json_transform.id}</p>`

            
            new_news.appendChild(new_element); /* AGREGO NUEVOS ELEMENTOS*/
        }
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

#news h4{
    font-size: 1.5rem;
}

#date {
    font-size: .7rem;
}

#news_id {
    font-size: .5rem;
}

*{
    margin: 0;
    box-sizing: border-box;

}

.img-hero{
    height: 300px;
    width: 500%;
    object-fit: cover;
}

footer{
    text-align: center;
    margin-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chuck Norris</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <nav class="navbar navbar-expand p-0">
            <button class="navbar-toggler"  type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
          
            <div class="collapse navbar-collapse" id="navbarSupportedContent" style="margin-top: 30px;">
              <form class="form-inline my-2 my-lg-0 w-100">
                <input id ="quantity" class="form-control mr-sm-2" type="number" placeholder="Search" style="width:92%" aria-label="Search">
                <button id="searching_btn" class="btn btn-outline-success my-2 my-sm-0" type="button">Search</button>
              </form>
            </div>
        </nav>


        <div id="news">
            
        </div>
        <!-- <div class="news d-flex justify-content-around align-items-center mt-5  rounded p-2 shadow-sm">
            <div data-toggle="modal" data-target="#exampleModal"><img src="chuck-norris-logo.png" alt=""></div>
            <p class="m-0">created_at: "2020-01-05 13:42:28.664997"</p>
        </div> -->


        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="exampleModalLabel">id: 123456789</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                </div>
                <div class="modal-body pt-5 pb-5 pl-5 pr-5">
                    <p id="news_id" class="text-center text-muted font-italic">updated_at: 2020-01-05 13:42:25.352697</p>
                    <div class="d-flex justify-content-center mt-5 mb-5">
                        <img src="chuck1.jpg"  alt="">
                    </div>
                    <h4 class="text-center">Chuck Norris solo-ed Everest in shorts and a tank-top.</h4>
                </div>
                <div class="modal-footer border-0">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                </div>
            </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <script src="script.js"></script>
</body>
</html>

0

Lo único que debes hacer es "limpiar" el contenedor antes de agregar nuevos elementos:

var new_news = document.getElementById("news");
news_news.innerHTML = '';
// Aquí agregas los nuevos elementos
0

Debes limpiar el contenedor fuera de la funcion chuck dado que si lo limpias dentro de la función, siempre te estará mostrando un elemento

var new_news = document.getElementById("news");
new_news.innerHTML = "";

        async function chuck(url){
            var getting_phrases = await fetch(url);
            var json_transform = await getting_phrases.json();
            
            var new_element = document.createElement("div");
            new_element.classList.add("news", "d-flex", "justify-content-around", "align-items-center", "mt-5", "rounded", "p-2", "shadow-sm", "mb-5"); 
            new_element.innerHTML = `<div data-toggle="modal" data-target="#exampleModal"><img src="chuck-norris-logo.png" alt=""></div>
            <p class="m-0">id: ${json_transform.id}</p>`
            new_news.appendChild(new_element);    
        }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.