HTML Snippet issues

0
I’m trying to add 2 seperate html snippet widgets to a page but I’m running into the issue than if I add the second snippet the first one stops functioning correctly. And if I take out the first one the second snippet still doesn’t work even though the code is correct. I’ve added alerts to the if statements on true values and the alert will fire but it always adds the character and never returns false for the second snippet. Has anyone else experienced this or have ideas on what could be the issue? I’m using the JQuery aspect of HTMLSnippet.   1) $(selector).on( "keyup", function(){ var th = $(this); th.filter( function(){ if ( th.val().length === 0 ) return th.val('0'); }) }) 2) $(selector).on( "keyup", function(e){ var th = $(this); th.filter( function(){ if ( e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) ) return false; }) })  
asked
3 answers
1

It's not really clear what your selector is in this case, but why create two of the same event handlers for one single selector? The second one might override the first one which can explain your issue.

In this case best is to prevent two HTML snippets on the same page with jquery enabled and create one single html snippet with one on("keyup") event handler combining both result functions.

$(selector).on( "keyup", function(e){
  var th = $(this);
  th.filter( function(){
    if ( th.val().length === 0 ) return th.val('0');
    if ( e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) ) return false;
  }
});

 

answered
1

What happens is you return true?

 

return false; will stop the event from bubbling up AND suppress the default action.

In otherwords, returning false is analogous to these two lines

event.stopPropagation();
event.preventDefault();

For events that bubble and are cancelable, at least.

answered
1

Thanks for your responses. To get the code to work I switched from the ‘JQuery’ radio to the ‘Javascript’ radio and did it that way. I did notice that you can’t use ES6 coding here in IE or the scripts won’t work.

 

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

document.querySelectorAll(selector).forEach( function(item){
  item.setAttribute("maxlength", "3")
  item.addEventListener( 'keyup', function(e){
    if ( item.value.length === 0 ) item.value = '0'
  })
  item.addEventListener( 'keypress', function(e){
    if (e.which > 31 && (e.which < 48 || e.which > 57))
      e.preventDefault(); return false;
  })
})
}, 100)

 

answered