how to add what is written in input to an array? [closed]

3

let arrayPaises= ['eeuu', 'colombia', 'noruega', 'islandia', 'peru']

arrayPaises.map((e, key)=>{
   jQuery('ul').append('<li>'+e+'</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="pincipal"></ul>
<input type="text" id="contenido">
<button id="insertar()">insertar</button>
    
asked by steven 27.11.2017 в 21:52
source

2 answers

2

To fill your array and keep feeding the list of countries you could do the following:

let arrayPaises= ['eeuu', 'colombia', 'noruega', 'islandia', 'peru']

function llenarLista(){
  $('ul').html('');
  
  arrayPaises.map((e, key)=>{
   $('ul').append('<li>'+e+'</li>');
  });
}

$("#insertar").click(function(){
  let valor = $("#contenido").val();
  
  arrayPaises.push(valor);
  
  llenarLista();
  
  $("#contenido").val('');
})

llenarLista();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="pincipal"></ul>
<input type="text" id="contenido">
<button id="insertar">insertar</button>

With the .push() method, we add values to the array and execute a function that traverses those values and prints them in <ul> .

If you have questions, I will gladly answer them.

    
answered by 27.11.2017 в 22:02
1

Your main error is that you are trying to call a function by assigning it to the button as a id . You should use the attribute onclick failing.

On the other hand, the body of your function should be with the form:

function nombreFuncion(){
    //Código
}

Once you have made the function, you can refer to the input using the function document.getElementById (Javascript method) or $("#id") (JQuery method) and obtain its value by referring to the attribute value or the function val() respectively.

Finally, assign that new value to your list.

Your modified example:

Using Javascript

let arrayPaises= ['eeuu', 'colombia', 'noruega', 'islandia', 'peru']

arrayPaises.map((e, key)=>{
   $('ul').append('<li>'+e+'</li>');
});

function insertar(){
  var contenido = document.getElementById("contenido").value;
  $('ul').append('<li>'+contenido+'</li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="pincipal"></ul>
<input type="text" id="contenido">
<button onclick="insertar()">insertar</button>

Using JQuery

let arrayPaises= ['eeuu', 'colombia', 'noruega', 'islandia', 'peru']

arrayPaises.map((e, key)=>{
   $('ul').append('<li>'+e+'</li>');
});

function insertar(){
  var contenido = $("#contenido").val();
  $('ul').append('<li>'+contenido+'</li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="pincipal"></ul>
<input type="text" id="contenido">
<button onclick="insertar()">insertar</button>
    
answered by 27.11.2017 в 22:14