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

195
Views
jQuery previene el cambio para seleccionar

Quiero evitar que se cambie un cuadro de selección si se aplica una determinada condición. Hacer esto no parece funcionar:

 $('#my_select').bind('change', function(ev) { if(my_condition) { ev.preventDefault(); return false; } });

Supongo que esto se debe a que, en este punto, la opción seleccionada ya ha cambiado.

¿Cuáles son otras formas de hacer esto?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Prueba esto:

http://jsfiddle.net/qk2Pc/

 var my_condition = true; var lastSel = $("#my_select option:selected"); $("#my_select").change(function(){ if(my_condition) { lastSel.prop("selected", true); } }); $("#my_select").click(function(){ lastSel = $("#my_select option:selected"); });
over 4 years ago · Santiago Trujillo Report

0

En caso de que alguien necesite una versión genérica de la respuesta de Mattsven (como hice yo), aquí está:

 $('select').each(function() { $(this).data('lastSelected', $(this).find('option:selected')); }); $('select').change(function() { if(my_condition) { $(this).data('lastSelected').attr('selected', true); } }); $('select').click(function() { $(this).data('lastSelected', $(this).find('option:selected')); });
over 4 years ago · Santiago Trujillo Report

0

Si simplemente desea evitar la interacción con la selección por completo cuando my_condition es verdadera, siempre puede capturar el evento mousedown y hacer que su evento lo evite allí:

 var my_condition = true; $("#my_select").mousedown(function(e){ if(my_condition) { e.preventDefault(); alert("Because my_condition is true, you cannot make this change."); } });

Esto evitará que ocurra cualquier evento de cambio mientras my_condition sea verdadero.

over 4 years ago · Santiago Trujillo 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!