JavaScript function problems - javascript

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

Related

Razor Dropdown onchange event not firing always undefined

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=

Scope issue in html page with javascript

I believe this is a scope issue but I haven't been able to resolve it, you can see some of the things I have tried commented out, maybe you can solve it. I have a variable, for purposes of StackOverflow I have named it undefinedVar and I try to call a method owned? by that variable but when I do I get Uncaught ReferenceError: undefinedVar is not defined. Now, there is obviously a whole lot more in this .html file but none of that matters for this question.
<!DOCTYPE html>
<html>
<head>
<script>
varX.ready(functionName);
function functionName() {
varX.ready(unDefinedVar.itsFunction());
};
</script>
</head>
<body>
<div id="#stackOverflow">
<div id="demo"></div>
</div><!-- End of the #stackOverflowDiv -->
</body>
<script>
//$(document).ready( function () {
//$( function () {
unDefinedVar = kendo.observable({
randomVariable: [],
itsFunction: function () {
#blahblahblah
}
});
//}); //end $function
//}); //End Document.ready
</script>
</html>
..or what would be the proper way to make this work?
You need to put the function after you've defined undefinedVar, so it looks like this:
undefinedVar = kendo.observable({
randomVariable: [],
itsFunction: function () {
#blahblahblah
}
});
function functionName() {
varX.ready(undefinedVar.itsFunction());
};
varX.ready(functionName);
Also, you've defined undefinedVar, but are looking to reference unDefinedVar. Make sure the case matches!

JQuery Click() function executes only once

In the following code, CLICK() method runs only one time:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script>
$(function(){
var arr = ["test1", "test2", "test3"];
var i=0;
$("#btn").click( function () {
while(arr[i])
alert(arr[i++]);
});
});
</script>
</head>
<body>
<div id="btn">Click Me</div>
</body>
</html>
Whats the problem?
I read all the other subjects but didn't help.
It does: - Just reset your i to 0. In your handler the condition fails second time because your i becomes array.length from your previous execution and it fails, since there is no item at arr[array.length] i.e3 in your case.
$("#btn").click(function () {
while(arr[i])
alert(arr[i++]);
i = 0; //here reset it
});
or just move it to the scope of the function.
$("#btn").click(function () {
var i = 0;
while(arr[i])
alert(arr[i++]);
});
The click method runs on every click, but after the first one it doesn't enter while loop anymore, because i === 3.
try this:
$("#btn").on('click', function () {
while(arr[i])
alert(arr[i++]);
});
I think the problem is caused by variable i, please move i to click function, such as:
$("#btn").bind('click', function(){
var i = 0;
while(arr[i])
alert(arr[i++]);
});

Why is nothing logged?

I tried to make it so that a string gets logged in the console every time I click on a button. However, nothing is logged. Why so?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function log_a_string_plz() {
console.log("some string i want logged");
}
document.onload = function() {
document.getElementById("my_wonderful_button").onclick = log_a_string_plz;
}
</script>
<title>logging a string test</title>
</head>
<body>
<button id="my_wonderful_button">log a string!</button>
</body>
</html>
I've tried changing event handlers to no avail.
Try:
window.onload = function () {
document.getElementById("my_wonderful_button").onclick = log_a_string_plz;
}
jsFiddle example

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.

Categories

Resources