简体   繁体   中英

How does <input> tag work in this example?

Beginner javascript question. I am trying to follow this tutorial on creating forms with restricted characters.

The code is as follows:

1. Function that limits text:

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}
</script>

2.Creation of Text area

<form name="myform">
<textarea name="limitedtextarea" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,100);" 
onKeyUp="limitText(this.form.limitedtextarea,this.form.countdown,100);">
</textarea><br>
<font size="1">(Maximum characters: 100)<br>
You have <input readonly type="text" name="countdown" size="3" value="100"> characters left.</font>
</form>

I understand how the code works apart from this line:

You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>

How/why does this display the remaining characters within the text area?

Sorry for a very simple question, I am only starting in JS/HTML and this has really confused me.

HOW

Every time you key up, or key down within the textarea, a function is executed. That function takes 3 parameters

  1. limitField is a reference to the actual field being typed in
  2. limitCount is a reference to another field which is ued to display the number of remaining characters
  3. limitNum - is a maximum number of characters you wish to allow in limitField

The logic of the method goes something like this (in pseudocode)

if the number of characters typed is greater than the mmaximum allowed characters
    truncate the field value back to the maximum allowed
otherwise
    display the number of remaining characters in the remaining count field

The last line there seems to be the root of your confusion, lets take that back to real code:

limitCount.value = limitNum - limitField.value.length;

In this line, limitCount is a reference to the field in the line you highlighted as your confusion in the question. limitNum is the maximum allowed characters, and limitField is the textarea being typed in to. Any input can have its text read/written using .value , so this line is literally saying "set the value of remaining characters field to the maximum allowed characters less the total number of characters already typed."

WHY

Because programming.

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