Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
jquery appended div onclick not work first time

this is my code

html :

<input type="text" class="js-input">  
<div class="js-autofill"></div>

jquery :

var myarray = ['apple' , 'orange'];
myarray.forEach(element => {
$('.js-autofill').append(
`<div class="js-item" data-value="`+element+`">` +element+ `</div>`
)
})

$(document).on('click','.js-item',function(){
$('.js-input').val($(this).attr('data-value'))
})

problem is .js-item onclick not working at firsttime - it's work when i doubleclick i can't find why

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to change .val() to .text() for the div click.

From Docs

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

$('.js-input').val($(this).text())

2 - Your div string in append has mismatch quotes, the correct order should be as below.

`<div class='js-item' data-value='` + element + `'>` + element + `</div>`

Also its helpful for you to read: When should I use double or single quotes in JavaScript?


Working code below

var myarray = ['apple', 'orange'];
myarray.forEach(element => {
  $('.js-autofill').append(
    `<div class='js-item' data-value='` + element + `'>` + element + `</div>`
  )
})

$(document).on('click', '.js-item', function() {
  $('.js-input').val($(this).text())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="js-input">
<div class="js-autofill"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda