简体   繁体   中英

fire on change event if value of multiple input elements are changed in jQuery

I have two file input elements. I want that the change event to only fire if the event occurs on both elements.

Right now the event is fired immediately if one of each gets a file

$(function (){
  $(".main_input, .second__input").on("change", ()=>{
     // do stuff 
  });
});

I tried to implement an and operator but don't know how to rewrite it to jQuery syntax

if ($(".main_input") && $(".second__input")).on("change", ())

The change event does not hang around. You will need to count

 $(function () { const events = [] $(".main_input, .second_input").on("change", (e)=>{ const tgt = e.target; const isMain = $(tgt).hasClass("main_input"); const isSecond = $(tgt).hasClass("second_input"); if (isMain) events.push("main") if (isSecond) events.push("second") console.log(events) if (events.length === 2) { console.log("both have been changed") } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> #1 <input type="file" class="main_input"><br/> #2 <input type="file" class="second_input"><br/>

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