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

374
Views
¿Cómo edito las variables de javascript según lo indicado por la entrada del usuario?

Quiero mostrar una matriz de números, después de eso, si el usuario desea cambiar cualquiera de los números en la matriz, debe escribir el valor deseado en su lugar y hacer clic en el botón Enviar, la matriz se actualiza y muestra la matriz actualizada.

Lo intenté hasta ahora y revisé numerosos artículos para encontrar una solución, pero no pude encontrar uno que encajara aquí.

Así es como se ve mi código, es un poco largo, pero no sé cuánto código es adecuado, así que esto es todo... por favor, ayúdenme a conseguirlo.

haciendo que la cuadrícula sea editable
 <style> #container{ display:grid; grid-template-columns: repeat(9, 8%); margin-left: 35%; margin-right:25%; margin-top:10%; } </style> <body style="background-color:grey"> <div id='container'> </div> <input id="someInput" type="text" value=<p id="output"></p>> <input type="button" value="submit" onClick="doStuff()"> </body> <script> var myContainer = document.getElementById('container') grid=[0,1,4,6,3,0,9,3,2]; for(var i=0;i<9;i++){ var myInput = document.createElement('input') //we want to add position of an input box as id myInput.id= `${i}` var num=grid[i]; myInput.value=num; myContainer.appendChild(myInput) } var x = document.createElement("BUTTON"); function doStuff(){ var nameElement = document.getElementById("someInput"); a = nameElement.value b = nameElement.id new_grid=[]; for(var j=0;j<9;j++){ if(j==b){ new_grid[j]=a; } else{ new_grid[j]=grid[j]; } } for(var i=0;i<9;i++){ var myInput = document.createElement('input') //we want to add position of an input box as id myInput.id= `${i}` var num=new_grid[i]; myInput.value=num; myContainer.appendChild(myInput) } } window.onload = function() { //when the document is finished loading, replace everything //between the <a ...> </a> tags with the value of splitText document.getElementById("output").innerHTML=grid[4]; } </script>
'''

luego traté de agregar un cuadro de entrada para poder mostrar los números de matriz en el atributo de valor y cuando los usuarios lo actualizan y hacen clic en el botón Enviar, se actualiza, pero luego no pude obtener los números de matriz en el atributo de valor de la etiqueta de entrada .

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Esto actualizará los valores de su matriz de grid con los valores ingresados por el usuario al hacer clic en el botón.

 var myContainer = document.getElementById('container'); grid = [0,1,4,6,3,0,9,3,2]; for(var i=0; i < grid.length; i++){ var myInput = document.createElement('input') //we want to add position of an input box as id myInput.id = `${i}` myInput.value = grid[i]; myContainer.appendChild(myInput); } var x = document.createElement("BUTTON"); x.textContent = "UPDATE"; myContainer.appendChild(x); x.addEventListener("click", UpdateGridFromUserInput, false); function UpdateGridFromUserInput() { var allinputs = document.getElementById('container').getElementsByTagName('input'); for(var j = 0; j < allinputs.length; j++) { grid[j] = allinputs[j].value; } console.log(grid); }
 <div id="container"> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay un ejemplo. Solo uso campos numéricos de entrada. Puede establecer el mínimo máximo y agregar un evento onChange si desea cambiar el valor de la matriz nums.

 const nums = [1, 2, 3, 4, 5]; const container = document.querySelector(".container"); nums.forEach(num => { const numElm = document.createElement("input"); numElm.classList.add("number"); numElm.type = "number"; numElm.min = 1; numElm.max = 9; numElm.value = num; container.appendChild(numElm); });
 .container { display: flex; justify-content: space-between; } .number { padding: .5rem; width: 2rem; text-align: center; border: 2px solid grey; border-radius: 10px; }
 <div> <p>Selected numbers</p> <div class="container" /> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Creo que ya tiene soluciones relevantes, pero me gustaría mostrarle "un poco de otra manera" que ahorra algunas filas de código y es más óptimo con arreglos más grandes.

En lugar de la matriz iterativa cuando desea cambiar un solo número, puede agregarle un detector de eventos. Guarda una ID en el elemento por el índice de la matriz, por lo que es fácil acercarse a la posición real en la matriz.

Lo primero es lo primero, me gustaría comentar algunas cosas en su código, que podrían ser mejores (¡todos aprendemos!)

 for(var i=0;i<9;i++){var myInput = document.createElement('input') ...

Desea crear una entrada para cada elemento de la matriz. Como programador, sabe que habrá 9 elementos, pero (como programador :)) no siempre desea recordar y contar cuántos elementos tiene la matriz. Es mejor usar grid.length que devuelve la longitud real de la matriz.

 function doStuff(){...}

Siempre nombre sus funciones como lo que realmente están haciendo. ¡Realmente ayuda!

 var nameElement = document.getElementById("someInput"); a = nameElement.value b = nameElement.id

Siempre nombre sus propiedades como lo que realmente significan. Podría usar "entrada", "valor de entrada", "id de entrada". Ayuda también :)

En la función doStuff() , está creando otras entradas nuevamente. Creo que no es realmente necesario cuando ya los has creado.

En segundo lugar, en segundo lugar, veamos cómo se ve como lo describí antes. Aquí está el código (use y aprenda ES6 , es mejor, confíe en mí):

 let array = [0, 1, 4, 6, 3, 0, 9, 3, 2]; let container = document.getElementById("container"); let output = document.getElementById("arrayResult"); output.innerHTML = array; //create inputs for the array for (let i = 0; i < array.length; i++) { let inputElement = document.createElement("input"); inputElement.type = "number"; inputElement.id = i; inputElement.value = array[I]; //if an user change the value, update the array at its position inputElement.addEventListener("input", () => { let id = inputElement.id; array[id] = inputElement.value; }) container.appendChild(inputElement); } //create submit button let submit = document.createElement("input"); submit.type = "submit"; submit.value = "Change"; container.appendChild(submit); //update output submit.addEventListener("click", () => { output.innerHTML = array; });
 <div id="container"> </div> <div> <label>Result:</label> <label id="arrayResult"></label> </div>

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!