Soy bastante malo en JS, pero necesito ayuda en una tarea para prepararme para un pequeño examen sobre tecnología web.
La tarea:
Tengo que escribir un código donde se deben mostrar dos campos de entrada. La suma de ambos campos de entrada debe ser 100. Por lo tanto, los campos de entrada se utilizarán principalmente para escribir algunos números.
Cuando escribo un número en el primer campo de entrada entre 0 y 100, debe mostrarse la cantidad restante de 100 en el segundo campo de entrada después de escribir el último número del primer número. Esto también debería funcionar a la inversa. Por lo tanto, debería ser irrelevante qué campo de entrada escribo en el número. Nuestro profesor sugiere que usemos el controlador de eventos "onkeyup".
Un ejemplo:
Primer campo de entrada: 3 -> escrito
Segundo campo de entrada: 97 -> se mostrará automáticamente después de escribir 3
Por favor, no te rías, aquí está mi código:
<!DOCTYPE html> <meta charset="UTF-8"> <html> <head> <script> function calc() { var firstnum = document.getElementById("firstprop").value; var secondnum = document.getElementById("secondprop").value; var firstresult = 100 - parseInt(secondnum); var secondresult = 100 - parseInt(firstnum); if(firstnum >=0){ secondnum = secondresult; } if(secondnum >=0){ firstnum = firstresult; } } </script> <head> <body> <input type="text" onkeyup="calc()" id="firstprop"/> <input type="text" onkeyup="calc()" id="secondprop"/> </body> </html>Muchas gracias por su ayuda. Te lo agradezco, de verdad :)
Aquí estás
<!DOCTYPE html> <meta charset="UTF-8"> <html> <head> <script> function calc(value, index) { if (index == 1) { document.getElementById("secondprop").value = 100 - value; } else if (index == 2) { document.getElementById("firstprop").value = 100 - value; } } </script> <head> <body> <input type="text" onkeyup="calc(this.value, 1)" id="firstprop" /> <input type="text" onkeyup="calc(this.value, 2)" id="secondprop" /> </body> </html>function calc(e) { if (e.target.id === "firstprop") { var secondElement = document.getElementById("secondprop"); var value1 = e.target.value ? e.target.value : 0; secondElement.value = 100 - (parseInt(value1)); } if (e.target.id === "secondprop") { var secondElement = document.getElementById("firstprop"); var value2 = e.target.value ? e.target.value : 0; secondElement.value = 100 - (parseInt(value2)); } } </script>