0

I made a simple function that depending on the text of the item selected from a dropdownlist, a textbox will change its maxlength property.

function cambiarLength(drop, textbox) {
    var option = document.getElementById(drop);
    var texto = option.options[option.selectedIndex].text;
    var field = document.getElementById(textbox);
    if (texto == 'RUC') {
        field.maxLength = 3;
    }
    else {
        field.maxLength = 6;
    }
};

Codebehind:

TipoDoc.Attributes.Add("onChange", "javascript: cambiarLength(this, txtDoc);");

Error:

0x800a1391 - JavaScript runtime error: 'txtDoc' is undefined

Image

Popplar
  • 279
  • 5
  • 15

1 Answers1

0

If txtDoc is the literal id of the field, then it needs to be treated as a string. You should also remove the javascript: prefix as that will disallow this to be recognized in your routine.

TipoDoc.Attributes.Add("onChange", "cambiarLength(this, 'txtDoc');");

See here regarding the use of the javascript: prefix: When is the 'javascript:' prefix valid syntax?

UPDATE

If you're using WebForms then you will want to use the ClientID, for example, if txtDoc is literally your code-behind control, you should do:

TipoDoc.Attributes.Add("onChange", "cambiarLength(this, '" + txtDoc.ClientID +"');");
Napoli
  • 1,389
  • 2
  • 15
  • 26
  • Hi, thanks for the help. I have tried a few things. TipoDoc.Attributes.Add("onChange", "cambiarLength(this.id, 'TxtDoc');"); var option = document.getElementById(ddl); this now does return the correct value. var field = document.getElementById(txtbox); this is returning null/undefined. For some reason I can't get the client.id from that textbox id 'txtDoc'. – Popplar Apr 30 '18 at 18:53
  • @Popplar see my update, if you're using WebForms, your rendered txtDoc Id may end up looking something like this `ct100_MainContent_txtDoc`, etc, in which case you'd want to use the `.ClientID` prop. – Napoli Apr 30 '18 at 19:11
  • I wanted to ask this, if possible, when passing "this" it is passing the object who called the function, is there a way to pass the object txtDoc instead of passing the clientID? – Popplar Apr 30 '18 at 19:33
  • `this` will refer to the object from with the method was invoked. in this case; the only way you'd be able to pass txtDoc as a DOMElement would be to be to do this (which i don't advise) `cambiarLength(this, document.getElementbyId('" + txtDoc.ClientID +"'));` – Napoli Apr 30 '18 at 19:38
  • Ok, got it. Thanks a lot for the help! – Popplar Apr 30 '18 at 19:40