Razor Dropdown onchange event not firing always undefined - javascript

I am using dropdownlist helper in my razor view
#Html.DropDownList("Country", null, "Select Your Country", new { #class = "form-control", onchange = "clickMe()" })
I have placed my jquery file in the head section of Layout.cshtml
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Scripts.Render("~/bundles/jquery")
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
But when I placed my script in a razor view
<script>
$(document).ready(function () {
function clickMe() {
alert();
}
});
</script>
it gives Reference error : clickMe() is undefined.
When I try this code to popup an alert to check that my jquery file is loaded
this works fine
<script>
$(document).ready(function () {
alert();
});
</script>

The actual reason this doesn't work is because of Scoping. The following code:
#Html.DropDownList("Country",
null,
"Select Your Country",
new { #class = "form-control",
onchange = "clickMe()" })
Yields something like (I hope):
<select onchange="clickMe()">
// this is looking for a global `clickMe()` function
// but is it available?
</select>
I've annotated your code here:
// clickMe() is out of scope
// it is not available here
$(document).ready(function ()
// start of anonymous function scope
{
function clickMe()
// start of clickme function scope
{
alert();
}
// end of clickme function scope
// clickMe() is available here
// it was defined in this scope
});
// end of anonymous function scope
// clickMe() is out of scope
// it is not available here
</script>
I absolutely do not recommend this, but to understand how you could make it work horribly, you could do the following:
<script>
$(document).ready(function ()
{
window.clickMe = function()
{
alert();
}
});
</script>
By assigning the function to the window object you make it globally available.
The better way to do it, taking advantage of Matt Bodily's Answer might look like:
<script>
$(document).ready(function () {
function clickMe() {
alert('made it!');
}
$(document).on('change', '#Country', clickMe );
});
</script>

I much prefer putting the click events in the script. Try removing your on change event and replacing your function clickMe with
$(document).on('change', '#Country', function(){
alert('made it!');
});
this selects on the ID of the dropdown which I believe will be country in the rendered drop down

Here is another option:
<script>
$('#CountryID').change(function() {
var value = $('#CountryID').val();
<script>
Just make sure you give your dropdown name= or id=

Related

JavaScript function problems

I can't get this to display an alert fed as a function argument. I have compared to examples and can't see the problem causing it not to work. I have included my html and JavaScript below, any help in where I'm going wrong will be very gratefully received. Thanks A
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="testjs.js"></script>
</head>
<body>
<div id = "testbed">
<a id = "testlink" href = "#number1">Test click</a>
</div>
</body>
</html>
JavaScript:
$(document).ready(function() {
$.fn.newmodalcontrols = function(modelspec) {
alert(modelspec);
} // end newmodalcontrols
$('#testlink').click(function() {
$(this).parent().newmodelcontrols('number1');
}); // end testlink click function
}); // end ready
You just have a typo. Change newmodelcontrols to newmodalcontrols.
JavaScript
$(document).ready(function () {
$.fn.newmodalcontrols = function (modelspec) {
alert(modelspec);
}
$('#testlink').click(function () {
$(this).parent().newmodalcontrols('number1');
});
});
Update: added a jsfiddle example.
You have a typo: newmodalcontrols and newmodelcontrols are not equivalent (note the a/e): corrected the typo, in a JS Fiddle demo:
$(document).ready(function () {
$.fn.newmodalcontrols = function (modelspec) {
alert(modelspec);
} // end newmodalcontrols
// ^- Should be an 'e'
$('#testlink').click(function () {
$(this).parent().newmodelcontrols('number1');
// ^- Or this should be an 'a'
}); // end testlink click function
}); // end ready
Incidentally, in Chromium, this would have been shown in the Web Inspector's JavaScript console as:
Uncaught TypeError: Object [object Object] has no method 'newmodelcontrols'
Which should have drawn your attention to the name of the method you were using/defining.
You got a typo.
Check out fiddle
http://jsfiddle.net/AUEZJ/
$(document).ready(function () {
$.fn.newmodelcontrols = function (modelspec) {
alert(modelspec);
}; // end newmodalcontrols
$('#testlink').click(function () {
$(this).parent().newmodelcontrols('number1');
}); // end testlink click function
}); // end ready

jQuery + Module Pattern: When to declare/query elements?

Typically, you don't start querying the DOM until the $(document).ready().
In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
Would it be better to put this whole Widget definition inside the $(document).ready()?
Should I wait until the Widget.init() to query the elements?
Note: I'm brand new to JS design patterns, so please note if I'm missing something
Option1
Widget = {
ele : $('#ele'),
init : function(){ ... }
};
$(document).ready(function(){
Widget.init();
});
Option2
Widget = (function(){
var privateEle = $('#privateEle');
return {
publicEle: $('#publicEle'),
init: function(){ ... }
};
}());
$(document).ready(function(){
Widget.init();
});
What I would do:
var Widget = (function(){
var ele;
function init(_ele){
ele = _ele;
};
return {
init: init
};
})();
$(function(){
Widget.init( $('#foo') );
});
If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []
EDIT: btw.. put your <script> tags before </body> NOT within <head></head>
It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.
what would work though is on of the following:
create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.
Widget = {
ele : $("<div id='ele'>"),
....
}
or you can query the element on widget initialization.
Widget = {
ele : "#ele",
init : function(){
this.ele = $(this.ele);
...
}
}
You can include script just before body end tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<!-- my HTML -->
<script src="../js/vendor/jquery-1.9.1.js"></script>
<script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
<script src="../js/custom.js"></script>
</body>
</html>
DOM is ready (no need for $(document).ready):
/*custom.js */
var Widget = (function($){
var _$element;
return {
init: function(){
_$element = $('#myElementId');
// TODO - element is available from now on
};
};
}(jQuery));
Widget.init();

Calling a ajax function on page load and on click of button

I have a javascript file containing a ajax function with parameter x.
I cannot reveal the function.I want to call the function on page load and on a button click.Also there is a for loop on the function for displaying the variable 10 times i.e,
for(i=0;i<10;i++).
The code for that button is :
HTML file
<html>
<title>Call web service</title>
<head>
<script type="text/Javascript" src="jquery-1.9.1.js"></script>
<script type = "text/javascript" src="ajax.js"></script>
<script type="text/javascript">
window.onload=function()
{
Webservice(1)('onload'); //call 1 where webservice is ajax function
}
</script>
</head>
<body>
<input id="button" type = "button" name = "button" value = "Call Webservice" onClick = "Webservice(5)"/>
</body>
</html>
Right now what I am getting is the onload function is getting overridden when I click the button whereas I want the outputs of both the functions to be displayed simultaneously
So please help me.
Thanks in advance.
Try doing this:
function f1() {
//what you need to do
}
function f2() {
//Do the same thing here also
}
This being your JS, in onload, call f1() and for button click call f2(). If you want f1() to execute before f2(), i suggest you look into locks here:
How to implement a lock in JavaScript
Your javaScript code should be something like this:
var fn = function fn(x) {
// Do something
}
$(function() {
var someValue;
// someValue = ...
// Call function once document is loaded
fn(someValue);
// Bind function as a callback to button click
$('#button').on('click', function(event) {
fn(someValue);
});
});

I can't figure out how to get my javascript onclick event to work

When I click on the button nothing happens unless I call the function in the html. I am trying to remove all inline javascript. I have included the commented-out section of html that works. Thanks in advance for the help!
JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. Change this:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example.
You have to add your whole code inside load, like this
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or
document.getElementById("sayHi").onclick = writeOutput;
You have two issues.
The first being covered by jbabey.
The second is that firstScript.js appears before your button. This is problematic as when you are assigning the onClick handler to it. It doesn't exist in the dom.
Try putting the entire main script inside window.onload = function () { ... } or moving it to the bottom of the markup.

call javascript function on link click

I want to set a cookie value when user clicks on a link.
I am using the following code:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="../../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
function changeLang(lang) {
$.cookie('myCulture', lang);
window.location.reload();
return false;
}
});
</script>
HTML
<img src="../../Content/images/danishFlag.png" height="35px" width="35px"/>
<img src="../../Content/images/swedishFlag.png" height="35px" width="35px"/>
It looks like very simple code, but when I click on the link, there is an error in the browser.
It says.
ReferenceError: changeLang is not defined
changeLang("da-DK");
Where am I doing wrong??
you are defining the function inside the document ready scope, so it's not global therefore not available in the global scope
define it as a global simply by removing the var declaration or using window.changeLang = function
$(document).ready(function () {
changeLang = function(lang) {
document.cookie = 'myCulture' + lang;
window.location.reload();
return false;
}
});
define function outside of the jquery block
$(document).ready(function () {
});
function changeLang(lang) {
$.cookie('myCulture', lang);
window.location.reload();
return false;
}
Try moving the ChangeLang function to outside of the Document Ready section.
Also, if running in FireFox with Firebug you can experiment with executing the function directly from the Console.
Good luck
Please do not attach js functions in html like this.
You're using jquery so just do this:
$(document).ready(function () {
function changeLang() {
$.cookie('myCulture', $(this).data('lang'));
window.location.reload();
return false;
}
$('.link').on('click', changeLang);
});
and then in html:
...
$(document).ready(function () {
});
function changeLang(lang) {
document.cookie = 'myCulture=' + lang;
window.location.reload();
return false;
}
This will work for you.

Categories

Resources