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

186
Views
Cómo llamar a getElementById() en múltiples identificaciones

Anteriormente hice una entrada onchange , hay varias entradas que tienen lo mismo llamado por id. ¿Cómo llamo a múltiples ID en una línea de código? Intenté escribirlo así pero fallé:

 function minmax() { const inp_field = document.querySelectorAll("#input1, #input2, #input3, #input4"); let val = parseFloat(inp_field.value), min = parseFloat(inp_field.min), max = parseFloat(inp_field.max); if (val < min) { inp_field.value = min; } else if (val > max) { inp_field.value = max; } else { inp_field.value = val; } }
 <input id="input1" type="text" onchange="minmax()" min="0.01" max="94.99"> <input id="input2" type="text" onchange="minmax()" min="0.1" max="99.99"> <input id="input3" type="text" onchange="minmax()" min="5" max="25"> <input id="input4" type="text" onchange="minmax()" min="1" max="10">

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Suponiendo que desea actualizar cada valor de entrada en función de sus atributos min / max a medida que cambia:

  1. No hay necesidad real de esas identificaciones. Si quisiera agruparlos, podría usar una clase en su lugar, pero aquí solo estoy seleccionando las entradas por nombre de elemento.
  2. Elimine el requisito de JS en línea y use addEventListener para adjuntar oyentes a cada entrada.
  3. Puede usar this (el contexto que se refiere al elemento en el que se hizo clic) en la función para que el código sea más conciso.
  4. Puede eliminar this.value = val ya que el valor de entrada ya está establecido.
  5. Finalmente, aunque max / min no se especifican como atributos en un que puede usar con type="text" , aparentemente aún puede usarlos. Pero es posible que desee cambiar a type="number" .

 const inputs = document.querySelectorAll('input'); inputs.forEach(input => { input.addEventListener('change', minMax); }); function minMax() { const val = parseFloat(this.value); const min = parseFloat(this.min); const max = parseFloat(this.max); if (val < min) this.value = min; if (val > max) this.value = max; }
 <input type="text" min="0.01" max="94.99"> <input type="text" min="0.1" max="99.99"> <input type="text" min="5" max="25"> <input type="text" min="1" max="10">

about 4 years ago · Santiago Gelvez Report

0

Si su objetivo es mantener todas las entradas sincronizadas cada vez que una de ellas cambia, entonces se requiere un ligero ajuste usando forEach . Tenga en cuenta, sin embargo, que querySelectorAll produce una NodeList , no una Array :

 function minmax() { const inp_fields = document.querySelectorAll("#input1, #input2, #input3, #input4"); inp_fields.forEach(inp_field => { let val = parseFloat(inp_field.value), min = parseFloat(inp_field.min), max = parseFloat(inp_field.max); if (val < min) { inp_field.value = min; } else if (val > max) { inp_field.value = max; } else { inp_field.value = val; } }); }

Solo asegúrese de cambiar el tipo de sus campos de entrada a number y establezca un value predeterminado adecuado (por ejemplo, 0 ), porque de lo contrario sus cálculos producirán que NaN se establezca en todos los demás campos al modificar cualquiera de ellos.

about 4 years ago · Santiago Gelvez Report

0

Dudo que realmente necesites todo eso... prueba esto y ve si satisface tus necesidades.

 function minmax(inp_field) { let val = parseFloat(inp_field.value), min = parseFloat(inp_field.min), max = parseFloat(inp_field.max); //below we call a function that checks if the value contains any scientific/engineering notation val = decimalCount(val) if (val < min) { inp_field.value = inp_field.min; } else if (val > max) { inp_field.value = inp_field.max; } else { inp_field.value = val; } } function decimalCount(val){ let valStr = val.toString(); //convert float to string //check if the value include e-... example 1e-7 if(valStr.includes('e-')){ //get the value before the scietific notation let beforeE = valStr.substr(0,valStr.indexOf('e')); //the following removes a comma. example 0.000000017 == 1.7e-7 beforeE = beforeE.replace('.','') //get the number of zeros after the scientific notation let decimalPlace = valStr.substr((valStr.indexOf('-') + 1)) - 1 //we set a variable for the zeros after the . let zeros = '.'; //assign the zeros to appear after the . for(let i=0;i<decimalPlace;i++){ zeros += 0; } //concatenate the results and return the value for display return 0 + zeros + beforeE; }else{ //else, we return the min/max as it is return val; } }
 <input id="input1" type="text" onchange="minmax(this)" min="0.01" max="94.99"> <input id="input2" type="text" onchange="minmax(this)" min="0.00000001" max="99.99"> <input id="input3" type="text" onchange="minmax(this)" min="5" max="25"> <input id="input4" type="text" onchange="minmax(this)" min="1" max="10">

about 4 years ago · Santiago Gelvez 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!