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

140
Views
Cómo hacer un botón con 2 estados que, al hacer clic, active una función diferente según el estado

Me gustaría tener un botón que actúe como un filtro en una tabla, cuando se hace clic ejecuta una función que filtra, pero cuando se vuelve a hacer clic, se deshace el filtro. si se hizo clic por tercera vez, filtra la tabla nuevamente, y así sucesivamente.

el HTML es solo un simple selector de botones:

 <button id="filterButton">Click here to filter</button>

y tengo esta función Javascript:

 window.onload = function() { document.getElementById('filterButton').onclick = function() { FilterTable(); //this function is the one that actually does the filtering, basically setting the tr[indexOfRow].style.display="none" on some specific rows. };

Me gustaría hacerlo de modo que si se vuelve a hacer clic en el botón, llamará a una función diferente que deshará el filtrado.

Intenté agregar una línea al final de esta función, cambiar la ID del botón a filterButtonClicked usando document.getElementById("filterButton").setAttribute("id", "filterButtonClicked"); y luego tenga otra función JS que manejará el evento document.getElementById('filterButtonClicked').onclick , que deshará el filtrado, y luego, al final de esta función, volverá a cambiar la ID del botón a fiterButton . En teoría, esto hará que si se hace clic en el botón por tercera vez, se active la primera función JS, que volverá a filtrar y cambiará la ID a filterButtonClicked . pero en la práctica, lamentablemente esto no funcionó, solo cambiaría la ID a filterButtonClicked una vez, y los clics posteriores no la cambiarían de nuevo a filterButton .

Tal vez esto podría implementarse de manera que si el número de clics en el botón fuera impar, ejecutaría la primera función, y si era par, ejecutaría la segunda. pero no sé cómo implementar esto.

¿Hay una mejor manera de hacer esto?

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

0

Declarativamente, ocultaría / mostraría el botón necesario y vincularía el controlador onclick en cada

Aquí hay un ejemplo https://codesandbox.io/s/elegant-glitter-05s6pg

about 4 years ago · Juan Pablo Isaza Report

0

La respuesta que buscas es bastante fácil...

 var state = 0; //This will act as the status of the button, 0 means needs unfiltered and 1 means need filtered. It will remain one in starting to show it is unfiltered window.onload = function() { document.getElementById('filterButton').onclick = function() { buttonClickFunction() }; }; function buttonClickFunction() { //Run this function whenever the button is clicked if (state == 0) { FilterTable(); //this function is the one that actually does the filtering, basically setting the tr[indexOfRow].style.display="none" on some specific rows. state = 1; //Shows that it has been filtered } else { UnfilterTable(); //The function you want to run for unfilter state = 0; //Change it back to 0 to show its unfiltered } } function UnfilterTable() { //Whatever u wanna run to unfilter } function FilterTable() { //Whatever u wanna run to filter }
 <!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> <button id="filterButton">Click here to filter</button> </body> </html>

about 4 years ago · Juan Pablo Isaza Report

0

Algo como esto debería funcionar:

 let filterActive = { state: false, }; window.onload = function () { document.getElementById("filterButton").onclick = function () { if (filterActive.state === false) { FilterTable(); filterActive.state = true; } else { // Function to undo the filtering here filterActive.state = false; } }; };
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!