Why wrap JavaScript in this "(function($){ ... JavaScript code ..})(jQuery);"? - javascript

I use mvc5. Do not include jQuery in test.
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title></title>
</head>
<body>
#RenderBody()
</body>
</html>
Test.cshtml:
<script type="javascript/text">
function myFunction() {
alert("its is working");
}
</script>
<button onclick="myFunction()">Click me</button>
In result I have an error: ReferenceError: myFunction is not defined
and the result code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title></title>
</head>
<body>
<button onclick="myFunction();">Click me</button>
<script type='text/javascript' >
(function($){
function myFunction() {
alert("I am working");
};
})(jQuery);
</script>
</body>
</html>
I have read a lot about this error and have not founded the answer. Could you clarify, who wrap JavaScript code? Is there any flag to cancel it? Is there any other way to resolve the problem?

Something (probably MVC5) is wrapped your code for you, but with good reason. Putting onclick handlers on elements pointing at a globally declared function is how JS was written in the '90s.
To resolve it, put an id attribute on your button and remove the inline event handler:
<button id="mybutton">
and then use jQuery to register the event handler:
$('#mybutton').on('click', function () {
alert("I am working");
});
or, since you mentioned in later comments that you have a loop generating these elements, use a class and a data- attribute instead:
<button class="myclass" data-id="...">
with code:
$('.myclass').on('click', function() {
var id = $(this).data('id');
...
});

<script>
function myFunction() {
alert("its is working");
}
</script>
<button onclick="myFunction()">Click me</button>
This will work. cheers

Related

It does not show me any output on console screen. What may be the problem

When I click The button it does not show me any output on the console window
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click me">Click me</button>
<script type="text/javascript" src="script.js">
</body>
</html>
->js
var printNumber=document.getElementById('Click me');
printNumber=document.addEventListener('Click',showNo);
function showNo() {
console.log('I was Clicked');
}
You have a few issues with your code.
Firstly you need to close your <script> tag in your HTML:
<script type="text/javascript" src="script.js"></script>
Secondly, your id shouldn't have spaces in it. You can change it to something like btn-click:
<button type="button" id="btn-click">Click me</button>
And then make sure to target it properly in your Javascript:
var printNumber=document.getElementById('btn-click');
Thirdly, your event name should be lowercase (as Javascript is case-sensitive), so change "Click" to "click"
Lastly, you want to add the click event listener to your button, which is stored in the variable printNumber. At the moment you are adding the event listener to your document and not the button. To add it to your button you can use:
printNumber.addEventListener("click", showNo); // add click event listener to button
See working example below:
var printNumber = document.getElementById('btn-click'); // change id selector
printNumber.addEventListener('click', showNo); // change 'Click' to 'click'
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title>Awesome button</title>
</head>
<body>
<button type="button" id="btn-click">Click me</button> <!-- change id -->
<script type="text/javascript" src="script.js"></script> <!-- close script -->
</body>
</html>
It should be click not Click!
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
var printNumber=document.getElementById('Click me');
printNumber=document.addEventListener('click',showNo);
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click me">Click me</button>
</body>
</html>
You had one typo Click which is supposed to be click.
`printNumber=document.addEventListener('Click',showNo);`
^^^^^^^^
you should add event listener to that particular element not to the complete document.
var printNumber=document.getElementById('Click_me');
printNumber.addEventListener('click',showNo);
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click_me">Click me</button>
</body>
</html>

JQuery trigger click event not working

I'm having trouble getting the following to work:
$('#elem').trigger('click');
When I run it, it doesn't trigger a click but it doesn't show any error logs in the console either.
I've also tried the following with no luck:
$('#elem')[0].click();
Any ideas as to what could be going wrong or a solution for this?
Update: Jquery is working and when I inspect the element, #elem does appear (it's an id for a button)
HTML:
<a:button id="elem">My Button</Button>
JQuery:
P.when('A', 'jQuery').execute(function (A, $) {
//when this function is called, it should trigger a button click
triggerButtonClick = function() {
$('#elem').trigger('click');
};
});
Try it in document.ready function, then all dom loads when the document is ready.You can do something like this based on your requirement.
$( document ).ready(function() {
$('#radio').click(function(){
$('#elem')[0].click();
})
});
i have tried this code and it works
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("chk1").click(function(){
$('#usr').trigger('click');
});
});
</script>
</head>
<body>
<form action="sample.php">
<button id="chk1">click</button>
<input class="form-control" type="submit" id="usr">
</form>
</body>
</html>
this code works for me:
$(window).load(function() {
$('#menu_toggle').trigger('click');
});
$(document).ready(function () {
$('#elem').click(function () {
alert('clicked');
$(this).css('color', 'red');
});
$('#elem').trigger('click');
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div id="elem" >test</div>
</body>
</html>

Pass element ID to Javascript function

I have seen many threads related to my question title.
Here is HTML Codes :
<button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
<button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
<button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
<button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
And a very simple JS function is here :
function myFunc(id){
alert(id);
}
You can see in JsFiddle.
The problem is :
I have no idea, maybe doesn't pass this.id to myFunc function, or some problem else.
What's the problem ?
Any help would be appreciated.
This'll work:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function myFunc(id)
{
alert(id);
}
</script>
</head>
<body>
<button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
<button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
<button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
<button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
</body>
</html>
In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:
<script type='text/javascript'>//<![CDATA[
window.onload = function () {
function myFunc(id){
alert(id);
}
}
//]]>
</script>
Because of this, your function myFunc is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head> as Sergio suggests your code isn't wrapped:
<script type='text/javascript'>//<![CDATA[
function myFunc(id){
alert(id);
}
//]]>
</script>
and so the function is in the global scope and available to your html buttons.
you can use this.
<html>
<head>
<title>Demo</title>
<script>
function passBtnID(id) {
alert("You Pressed: " + id);
}
</script>
</head>
<body>
<button id="mybtn1" onclick="passBtnID('mybtn1')">Press me</button><br><br>
<button id="mybtn2" onclick="passBtnID('mybtn2')">Press me</button>
</body>
</html>
Check this: http://jsfiddle.net/h7kRt/1/,
you should change in jsfiddle on top-left to No-wrap in <head>
Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.
The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.
This worked:
validateSelectizeDropdown('#PartCondition')
This did not:
validateSelectizeDropdown("#PartCondition")
And the function:
function validateSelectizeDropdown(name) {
if ($(name).val() === "") {
//do something
}
}

Alert message wont work

html embedded with javascript
<html>
<head>
<title>Example</title>
<script type ="text/javascript">
have I called this function correctly????
function displayatts()
{
document.getElementById("buttonone").onclick = saysomething;
}
is there something wrong here???
function saysomething()
{
alert("I am 28 years old");
}
</script>
<body>
<input type="button" id="buttonone" value="me" >
</body>
</head>
</html>
Here is the full example.
This will work for sure.
Test it if you want.
Copy and paste the below code into W3Schools test environment, "Edit and Click me" to test.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type ="text/javascript">
function saysomething()
{
alert("I am 29 years old");
}
function displayatts()
{
document.getElementById("buttonone").onclick = saysomething;
}
</script>
<body onload="displayatts();">
<input type="button" id="buttonone" value="me" >
</body>
</head>
</html>
Your script runs before the document is parsed.
Therefore, getElementById returns null.
Move the <script> to the bottom.
"have I called this function correctly????"
You haven't called the displayatts() function at all. Add the following to the end of your script:
window.onload = displayatts;
That way displayatts() will be called automatically once the page finishes loading. It will, in turn, setup the click handler on your button.
Also, include the closing </head> tag just before the opening <body> tag.
Demo: http://jsfiddle.net/nnnnnn/rxDXa/
window.onload = displayatts;
Paste this code before </body> tag in your page.So you can be sure if element is null or not or the code is try to work before your html element is rendered.
Hope this helps your situation..
<script>
var element = document.getElementById("buttonone");
if(element){
element.setAttribute("onclick", "saysomething();");
}else
{
alert("element null, move the code to bottom or check element exists");
}
</script>

How can I access JavaScript defined in <head> from <body>

For example suppose I have
function myTest() {
return "test";
}
defined in <head>
In body if I try to call myTest() it fails. How can I make functions and variables accessible from body?
Script in the head tag will get parsed first, so your variables and functions are accessible from script in the body tag. Your problem must be elsewhere, because the following example works:
<!doctype html>
<html>
<head>
<script type="text/javascript">
function myTest() {
return "test";
}
</script>
</head>
<body>
<script type="text/javascript">
alert(myTest());
</script>
</body>
</html>
You need to place all JavaScript into <script>...</script> tags, OR, place it in event handling attributes (like onclick).
<html>
<head>
<script type="text/javascript">
function myTest() {
alert("hi");
}
</script>
</head>
<body>
<input type="button" onclick="myTest();" />
</body>
</html>
This is Your function in Head..
function myFunction(a)
{
return (a)
}
Then call like below
<script type="text/javascript">
myFunction(12);
</script>

Categories

Resources