Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
¿Cómo tomar la entrada del usuario para el tamaño de una matriz y los elementos de la matriz usando dom en javascript?

Estoy construyendo un proyecto web que realizará varios algoritmos de clasificación para ordenar una matriz. Para este propósito, quiero tomar la entrada del usuario para el tamaño de la matriz y también la entrada del usuario para los elementos de la matriz del tamaño ingresado. No estoy obteniendo el resultado esperado por mi código.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="screen-body-item"> <div class="app-form"> <div class="app-form-group"> <input type="text" class="app-form-control" placeholder="enter size" id="size"> <input type="text" class="app-form-control" placeholder="enter element" id="ele"> <input type="button" value="" value="add value" class="app-form-button" onclick="addval()"> </div> </div> </div> </div> <script> function addval() { var inputArray = []; let size = document.getElementById('size').value; for (var i = 0; i < size; i++) { inputArray[i] = document.getElementById('ele').value; } } </script> </body> </html>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Está iterando sobre inputArray , pero no tiene elementos. Primero debe llenarlo con elementos.

En este caso, podemos simplificar el código usando la función Array para crear una matriz con una cierta cantidad de elementos y Array.fill para establecer cada elemento de la matriz en un valor específico:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="screen-body-item"> <div class="app-form"> <div class="app-form-group"> <input type="text" class="app-form-control" placeholder="enter size" id="size"> <input type="text" class="app-form-control" placeholder="enter element" id="ele"> <input type="button" value="" value="add value" class="app-form-button" onclick="addval()"> </div> </div> </div> <script> function addval() { let size = document.getElementById('size').value; let value = document.getElementById('ele').value; var inputArray = Array(+size).fill(value) console.log(inputArray) } </script> </body> </html>

about 4 years ago · Juan Pablo Isaza Report

0

Este código parece un poco largo, porque tengo una función de escritura para escribir solo el número y el elemento de espacio en las entradas. y agregó algunos filtros.

Por favor, pruebe este código usted mismo. Si no puede entender en alguna parte, escriba un comentario a continuación, me siento bien para explicárselo a alguien.

Tenga en cuenta: el usuario solo puede ingresar números en las entradas.

 let sizeInput = document.querySelector('#size'); let eleInput = document.querySelector('#ele'); // allow only numbers to type [eleInput, sizeInput].forEach(input=>{ input.addEventListener('keypress', function(event){ event.preventDefault(); let value = parseInt(event.key); if(!isNaN(value)) return input.value += value; if(input == eleInput && event.key == ' ') return input.value += event.key; }); }); // main function function addval(event) { event?.preventDefault(); // if button is in form element let inputArray = []; let size = parseInt(sizeInput.value); let elements = eleInput.value; if(isNaN(size)) return alert('Please enter valid size.'); // stop and show alert if size is invalid or empty elements = elements.trim(); // remove space from starting and end elements = elements.replace(/ +/g, ' '); // remove multiple spaces elements = elements.split(' '); // split by space if(elements.length != size) return alert(`Please enter ${size < elements.length ? 'only': ''} ${size} elements`); inputArray = elements; console.log(inputArray); // remove later return inputArray; }
 <input type="text" class="app-form-control" placeholder="enter size" id="size"> <input type="text" class="app-form-control" placeholder="enter element" id="ele"> <input type="button" value="add value" class="app-form-button" onclick="addval()">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!