简体   繁体   中英

Prevent double on.click event Javascript

i'm still new in using java script, i try to make trigger time when first input field get click, then the function trigger will active, the problem every time i click input field, the triggger always active again, i try using

event.preventDefault();

but it's didn't work, please help me where i do it wrong? this my code

 $('#trigger').on("click", function(e) { e.preventDefault(); var timeleft = 1; var downloadTimer = setInterval(function(){ document.getElementById('countdown').value = `${timeleft} seconds`; timeleft += 1; }, 1000); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="trigger" class="form-control" required> <input type="text" id="countdown" class="form-control" required>

edit: i try it like this, but its still haunt me if is this the best method?

 function myFunction() { var timeleft = 1; var downloadTimer = setInterval(function() { document.getElementById('countdown').value = `${timeleft} seconds`; timeleft += 1; }, 1000); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="trigger" onclick="myFunction(); this.onclick=null;" class=" form-control" required> <input type="text" id="countdown" class="form-control" required>

You can use focusout event of Textbox

$( "#trigger" )
  .focusout(function() {
   myFunction();
  });

and after focusout you can disable Textbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM