How to Include and Reference . JS in my project?

Asked

Viewed 454 times

2

Well here’s the thing, I have a file. JS in my project.

I’m calling him at HEAD LIKE THAT:

    <script type ="text/javascript" src="~/JS/validacao.js"></script>

within this validation.JS has a mask function.

and put in Textbox the following event.

this.TxtCEP.Attributes.Add("onkeypress", "Mascara(CEP, TxtCEP);");

<asp:TextBox ID="TxtCEP" runat="server" style="margin-left: 66px" Width="231px" TextMode="Number" MaxLength ="8"></asp:TextBox>

Mascara function

   function Mascara(formato, objeto) {
campo = eval (objeto);
// CEP
if (formato=='CEP'){
    var CodCar = event.keyCode;
    if (CodCar < 48 || CodCar > 57) {
        campo.focus();
        event.returnValue = false;
    }
    separador = '-'; 
    conjunto1 = 5;
    if (campo.value.length == conjunto1) {
        campo.value = campo.value + separador;
    }
  }
}

inserir a descrição da imagem aqui

But it’s not working.

I’m doing right ?

  • 2

    also put the function Mascara

  • 1

    Press F12 and look at the console and post the errors tbm

  • 1

    you have to use so src="~/JS/validation.js" where the ~ would be the root folder of your project.

  • How is your folder structure? Is the JS folder in the project root, or is it inside another folder? Most likely you have a script folder and the JS is inside it, then your reference has to be like this src="~/script/JS/validacao.js", recalling that the ~ is defined as root Operator by Asp.net

  • 2

    the wrong path ta follows @Pablotondolodevargas' solution

  • I already changed it, still nothing.

  • Updates the question with the modifications you have made and with the error message you are giving now

  • first I didn’t realize it was webforms, second mind I’m adding the answer

Show 3 more comments

1 answer

0


In Forms web project, to add the reference to a script, you can do it as follows.

<script type ="text/javascript" src="Scripts/JS/validacao.js"></script>

However, I prefer to do the following

<script type ="text/javascript" src="<%=ResolveUrl("~/Scripts/JS/validacao.js")%>"></script>

So I guarantee that if I publish the project in a subfolder of the main domain, it will get the correct reference to mine script

Another detail that you are missing, It is time to assign the event to your compoente, this is the correct way I did in the example I published in my github

this.TxtCEP.Attributes.Add("onkeypress", $"Mascara('CEP', {this.TxtCEP.ClientID});");

The difference to yours is I’m passing the zip code as string and using the Clientid that obtains the identifier of the control generated by ASP.NET.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.