Monaca Onsen UI Discord Chat Github Repo

<ons-input> addEventListener function not firing



  • Hi,

    I have the following JavaScript code snippet to detect changes ons-input and clear text when X button is clicked, but it is not firing. It works with regular <INPUT> tag but not <ONS-INPUT>

     input1.addEventListener('input', conditionallyHideClearIcon2);
    

    In the following:

    Array.prototype.forEach.call(document.querySelectorAll('.clearable-ons-input'), function(el) {
    	var input1 = el.querySelector('ons-input');
        
        conditionallyHideClearIcon2();
              
       input1.addEventListener('input', conditionallyHideClearIcon2);
        
      el.querySelector('[data-clear-ons-input]').addEventListener('click', function(e) {
          
          input1.value = '';
          conditionallyHideClearIcon2();
          
    	});
      
    	function conditionallyHideClearIcon2(e) {
    	  var target = (e && e.target) || input1;
          target.nextElementSibling.style.display = target.value ? 'block' : 'none';
         
    	}
      });
    
    <div class="clearable-ons-input">
    	<ons-input type="text" value="Hi there!"></ons-input>
    	<span data-clear-ons-input></span>
    </div>
    
    <style>
    		.clearable-ons-input {
    		position: relative;
    		display: inline-block;
    		
    		}
    		.clearable-ons-input > ons-input {
    		padding-right: 1.5em;
    		font-size: 16px;
    		width: 200px;
    		height: 2em;
    	
    		   border: 0;
    			outline: 0;
    			/* background: transparent; */
    			border-bottom: 1px solid black;
    			border-radius: 1px;
    		
    		}
    		.clearable-ons-input >[data-clear-ons-input] {
    		display: none;
    		position: absolute;
    		top: 5px;
    		right: 0;
    		font-weight: bold;
    		font-size: 1.4em;
    		padding: 0 0.2em;
    		line-height: 1.4em;	
    		box-sizing:border-box;
    	
    		/* red X button */
    			width:20px;
    			height:20px;
    			border-width:3px;
    			border-style: solid;
    			border-color:grey;
    			border-radius:100%;
    			background: -webkit-linear-gradient(-45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%), -webkit-linear-gradient(45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%);
    			background-color:grey;
    			box-shadow:0px 0px 5px 2px rgba(0,0,0,0.5);
    			transition: all 0.3s ease;
    		}
    		/* .clearable-ons-input > ons-input::-ms-clear {
    		display: none;	
    		} */
    			
    	</style>
    
    

  • Onsen UI

    @jamal The event.target of the event is the native input element wrapped inside ons-input, not ons-input itself. Therefore, change var target = (e && e.target) || input1; to either var target = (e && e.currentTarget) || input1; or var target = input1; and it should work.



  • @Fran-Diox, Thank you!

    var target = (e && e.currentTarget) || input1;
    

    worked perfectly!