简体   繁体   中英

Trigger onchange event by default

I have this script trimming leading and trailing spaces on input fields

function trim(el){el.value=el.value.replace(/(^\\s*)|(\\s*$)/gi,"").replace(/[ ]{2,}/gi," ").replace(/\\n +/,"\\n");return}

<input onchange="return trim(this)" type="text" value="">

and I have to add onchange="return trim(this)" in every instance of <input type="text" value=""> to trigger it. Is it possible to make this script triggered by default without having to add onchange="return trim(this)" everywhere? Maybe with some an additional script that tell all input fields to trigger it by default? I also run jquery on this site if that helps.

Try jQuery unobtrusive:

$("input[type=text]").on("change", function () {
    trim($(this));
}); 

$("input[type=text]") this selector will match all inputs of type text on your current page

fiddle sample

Try this

 $(document.ready(function(){
     $('input[type="text"]').change(function(){
          return trim(this);
       });
 });

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