Reputation: 141
This is the smallest simplest start I could think of, and of course it errors. I'm running a .cshtml page. Here is the code for having function in the SAME file just lines apart:
@section head
{
<script>
function CheckPostalCode(form) {
if (form.postalcode.value.length < 5) {
alert("Please enter a Zip Code.");
form.postalcode.focus();
return false;
}
return (true);
}
</script>
}
Now in the webpage below:
<form onsubmit="return CheckPostalCode(this)" method="post" action="/search/index.cshtml">
<input type="text" name="postalcode" id="postalcode" size="30" maxlength="5" required/>
<input type="submit" name="submit" value="go" />
</form>
The original method I tried to use was having a separte file called checkFields.js and including the file in the pages section head as such:
<script type="text/javascript" src="/js/checkFields.js"></script>
Where the webpage code is the same. Can anyone help explain why even when the script is in the same file its undefined. But really I would like to be able to call the function from another file. I've seen many tutorials that all say, you can call functions like normal so long as you include them. Well I thought I did.
When viewing page source it's simply the form with a header tag above it
Upvotes: 2
Views: 280
Reputation: 756
If you are using @section head to include some raw javascript from your view, you need a RenderSection("head", false) in your _Layout.cshtml file ("head" is a name defined by yourself, you can change it to other name), in <head></head>
part, like:
<head>
//your other css link or js link here
@RenderSection("head", false)
</head>
If you use link, try to use "~"
<script src="~/js/checkFields.js" type="text/javascript"></script>
Or use:
<script src='@Url.Content("~/js/checkFields.js")' type="text/javascript"></script>
Upvotes: 2