简体   繁体   中英

event handler that uses 'this' keyword not working as expected

Title may not be correct but i didnt know how to ask my question ! I have encountered a problem with this keyword . While using it as in this code <input type="text" onkeyup="this.value=this.value.toUpperCase();"></input> it works perfectly. But when i allot a function on input element that uses this keyword , it dont work as in
HTML

<input type="text" onkeyup="up();"></input>

Javascript

function up()
{   
    this.value=this.value.toUpperCase();
}

this here will not be the element, you need to pass this from the DOM, use it like this

<input type="text" onkeyup="up(this);"></input>

your function

function up(el)
{   
    el.value=el.value.toUpperCase();
}

You can also use the probably most horrible thing JavaScript offers:

onclick="up.call(this);"

call(...) basically sets the this inside a function to a specific value, in this case to the element.

Try to extend DOM elements prototype with function:

 HTMLInputElement.prototype.up = function() { if(this.type == "text") { this.value = this.value.toUpperCase(); } }; 
 <input type="text" onkeyup="up();" placeholder="type something" /> 


but I strictly recommend You to use jquery for this, because I don't think that HTMLInputElement will always persist on all browsers:


 $(function(){ $('input.to-uppercase') .on('keyup', function(){$(this).val($(this).val().toUpperCase());}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="to-uppercase" placeholder="write something"> 

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