0

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();
}

3 Answers3

8

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();
}
Ahmed Eid
  • 1,145
  • 8
  • 9
1

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.

momar
  • 171
  • 1
  • 7
0

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">
num8er
  • 18,604
  • 3
  • 43
  • 57
  • 1
    Sorry, it will work. It's just a bad idea to extend the `HTMLInputElement` prototype in this way. –  Jul 18 '15 at 13:25
  • 1
    yeah it works , but i am not getting how it works , i am new to javascript . can u please explain your code @num8er – john scott Jul 18 '15 at 13:26
  • @torazaburo, I know about it, I've updated my answer. (: – num8er Jul 18 '15 at 13:29
  • @johnscott every DOM object has it's set of functions, and it can be accessible and extendible through prototype. so, I've added to it's behavior up() function. that's all. but again, use jQuery realization, because it's safer than using HTMLInputElement. Also read about OOP part of JavaScript. It will be really helpful in future. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript – num8er Jul 18 '15 at 13:31
  • 1
    I actually preferred your first solution better. But in any case, it's standard do just do `onkeyup="up(this")` and `function up(elt)`. –  Jul 18 '15 at 13:42
  • I don't like to bind events to elements html code, always use javascript frameworks and place them in js file. For me it's cleaner to keep js, css part in separated files – num8er Jul 18 '15 at 13:48