0

I want to move a JavaScript function up to the <script> tag from a input tag and it's not working.

This works:

<input type="text" name="aaa" id="aaa" onkeyup="javascript:this.value=
  this.value.substring(0,1).toUpperCase()+
    this.value.substring(1,this.value.length);
  if (this.value=='') 
    document.getElementById('aaaLabel').innerHTML='AAA';"
/>

This doesn't:

<script type="text/javascript">
  function FieldOnKeyUp() {
    this.value=this.value.substring(0,1).toUpperCase()+
      this.value.substring(1,this.value.length);
    if (this.value=='') 
      document.getElementById('aaaLabel').innerHTML='AAA'; 
  }
</script>

<input type="text" name="aaa" id="aaa" onkeyup="FieldOnKeyUp()">

What's the difference?

10
  • @Downvoter: Please give a reason so that the OP can improve the question. Simple down-voting does not help. meta.stackexchange.com/questions/135/… Commented Nov 8, 2011 at 4:23
  • I would guess if you look in the javascript log, you'll see errors. Commented Nov 8, 2011 at 4:24
  • 4
    Perhaps the difference is that by moving the JavaScript code you've changed the definition of this. You may have better luck of you do onkeyup="FieldOnKeyUp(this)", and then use function FieldOnKeyUp(theField) to declare your function. Then replace every instance of this with theField. Commented Nov 8, 2011 at 4:25
  • Yea, I don't understand why I'm getting down voted, but I also don't remember how to make these code blocks look nicer when the post... Is it clear what I'm asking? Commented Nov 8, 2011 at 4:25
  • 1
    @aroth Make your comment an answer and provide a fiddle for some upvotes. Aside: I don't understand the downvotes on the question either. Commented Nov 8, 2011 at 4:30

1 Answer 1

5

The value of this is not passed to your separate function. In fact, this in your function is set to the window object. You need to change to this type of code in order to pass the right value to your function:

<input type="text" name="aaa" id="aaa" onkeyup="FieldOnKeyUp(this)">

and your code to this:

<script type="text/javascript">
function FieldOnKeyUp(el) {
     el.value=el.value.substring(0,1).toUpperCase()+el.value.substring(1); 
     if (el.value=='') {
         document.getElementById('aaaLabel').innerHTML='AAA'; 
     }
}
</script>

Here's a sample that shows this code working: http://jsfiddle.net/jfriend00/2dJ6x/.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.