简体   繁体   中英

JavaScript Conundrum

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?

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/ .

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