Reputation: 13
I am trying to use some Javascript from a Razor View page, but it is never activated and cannot figure out why. Any help will be highly appreciated!
Note: The View uses a shared layout that loads jQuery & Bootstrap for all views.
Here is my latest Razor View code, but I have tried even more methods to activate the textSubmit() function, such as using the button onclock() tag, the form onsubmit() event, etc. and NOTHING works!
<script type="text/javascript">
$("#submit").click(function (event) {
event.preventDefault();
textSubmit();
});
function textSubmit() {
alert("You CLICKED!");
}
</script>
<div id="workarea">
<div id="emptylog"></div>
<div id="chatbox">
<form id="inputForm" role="form">
<div class="form-group">
<label for="inputBox">Say something:</label>
<input name="inputBox" id="inputBox" type="text" class="form-control" required>
</div>
<button id="submit" type="button" class="btn btn-default btn-primary">Submit</button>
</form>
</div>
</div>
Upvotes: 1
Views: 89
Reputation: 6734
Your script block is being parsed and evaluated before the DOM is done being parsed, so $("#submit")
is finding no element with that id to attach the click event to.
Put your script inside jQuery's ready
function and it will execute "as soon as the page's Document Object Model (DOM) becomes safe to manipulate" ( https://api.jquery.com/ready/).
$(document).ready( function() {
$("#submit").click(function (event) {
event.preventDefault();
textSubmit();
});
function textSubmit() {
alert("You CLICKED!");
}
})
Upvotes: 1