Pass element ID to Javascript function - javascript

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
}
}

Related

How to remove event listeners attached with onclick [duplicate]

This question already has answers here:
Removing the event listener on a button programatically
(2 answers)
Closed 4 years ago.
I need a way to remove event listeners attached with onclick="func()" in javascript
below is sample code
<!DOCTYPE html>
<html>
<body>
<script>
function f1(){
alert("f1");
}
function f2(){
alert("f2");
document.getElementById("b1").removeEventListener("click",f1);
}
</script>
<button id="b1" type="button" onclick="f1()">B1</button>
<button id="b2" type="button" onclick="f2()">B2</button>
</body>
</html>
You just set the onclick property of the element to null.
<!DOCTYPE html>
<html>
<body>
<script>
function f1() {
alert("f1");
}
function f2() {
alert("f2");
document.getElementById("b1").onclick = null
}
</script>
<button id="b1" type="button" onclick="f1()">B1</button>
<button id="b2" type="button" onclick="f2()">B2</button>
</body>
</html>
This is because when you do onclick="f1()", the browser creates a new function for you, somewhat (but not entirely) equivalent to this:
elem.onclick = new Function("event", "f1()")
Which gives you a function, something like this:
elem.onclick = function(event) {
f1()
}
So setting that property to null simply overwrites the assigned function, setting it back to its default value.
You can change it:
document.getElementById("b1").removeEventListener("click",f1);
for it:
document.getElementById("b1").onclick = null;
<!DOCTYPE html>
<html>
<body>
<script>
function f1(){
alert("f1");
}
function f2(){
alert("f2");
document.getElementById("b1").onclick = null;
}
</script>
<button id="b1" type="button" onclick="f1()">B1</button>
<button id="b2" type="button" onclick="f2()">B2</button>
</body>
</html>
Setting the onclick to null works fine, but you might notice if you inspect the DOM your onclick is still there.
So another way is to use removeAttribute
eg.
<!DOCTYPE html>
<html>
<body>
<script>
function f1(){
alert("f1");
}
function f2(){
alert("f2");
document.getElementById("b1").
removeAttribute("onclick");
}
</script>
<button id="b1" type="button" onclick="f1()">B1</button>
<button id="b2" type="button" onclick="f2()">B2</button>
</body>
</html>
Add another blank listener to it as
document.getElementById("b1").onclick = function() {
return false;
}

JavaScript function doesn't run on click

Although I know a lot about these languages now such as arrays and functions, I'm having a basic problem to getting this JavaScript to run, here's the code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="submit" value="submit" onclick="click()" />
<script>
function click() {
alert("hey");
}
</script>
</body>
</html>
You're running into this problem: javascript function name cannot set as click?
You can fix this by changing the function name to something else like function myClick
<head>
</head>
<body>
<input type="submit" value="submit" onclick="myClick()" />
<script>
function myClick() {
alert("hey");
}
</script>
</body>
</html>
yes,like the comment above. you should use a different name instead of click()
function submit() {
alert("hey"); }
<html>
<head>
</head>
<body>
<input type="submit" value="submit" onclick="submit()" />
</body>
</html>

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

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

Redirecting using JS file instead of HTML event handler?

So currently I want to have my javascript in an attached JS file instead of using the 'OnClick' function attached to HTML objects. So far I've got:
<html>
<head>
</head>
<body>
<h1 id = '5' class = ''>6</h1>
<button id = '7' class = ''>8</button>
<script src = 'js/9.js'></script>
</body>
</html>
But unfortunately, I can't quite get the redirect going from clicking the button. It should have this source
document.getElementById('7').onclick = function () {
and then redirecting to a different page. Any tips on how I can improve this?
Please use strings as ID. I know you can now use numbers but it is not recommended
Use the load event handler
You MAY be submitting the page to itself when not giving the button a type so return false or preventDefault
what's with the spacing around = in the attributes? Not necessary nor recommended.
Like this
<html>
<head>
<script src="js/9.js"></script>
</head>
<body>
<h1 id="five" class="">6</h1>
<button id="seven" class="">8</button>
</body>
</html>
where js file has
window.onload=function() {
document.getElementById("seven").onclick = function () {
location.replace("page2.html"); // or just location="page2.html";
return false;
}
}
Using jQuery it would be
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/9.js"></script>
</head>
<body>
<h1 id="five" class="">6</h1>
<button id="seven" class="">8</button>
</body>
</html>
where js file has
$(function() {
$("#seven").on("click",function (e) {
e.preventDefault();
location.replace("page2.html"); // or just location="page2.html";
});
});
LASTLY you do not need script at all:
<form action="page2.html">
<button type="submit" id="seven" class="">8</button>
</form>

Newbie: hanging browser on function call

I just started learning JavaScript and am wondering why this simple snippet hangs when I click on the "Call function" button. What am I missing?
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.write("hello");
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>
You need to write inside an element or give an element a value, or you should use document write like that :
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.getElementById("lblMessage").innerText = "hello";
document.getElementById("txtMessage").value = "hello";
//document.write("hello");
}
</script>
</head>
<body>
<form>
<script type="text/javascript">
document.write("This is written while page processed by browser !<br />");
</script>
<input type="text" id="txtMessage" /><br />
<span id="lblMessage"></span><br />
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>
If you simply want to see your button doing something then try:
alert("Hello");
instead of the document.write.
Where do you expect the function to output its "hello"? Right into the button's source code? That makes no sense. The browser is confused and hangs.
Document.write doesn't magically insert something at the end of your document. It writes its stuff out right there where it is called.
Not too sure what you mean by "hang"... Try this out... The alerts can be removed, but will inform you of where it is at in execution...
<html>
<head>
<script type="text/javascript">
function myFunction() {
//for debugging
alert('Made it into function');
document.getElementById('MyOutputDiv').innerHTML = 'Word To Your Mom...';
//for debugging
alert('function complete');
}
</script>
</head>
<body>
<input type='button' onclick='myFunction();' value='Call Function'>
<br>
<div id='MyOutputDiv'></div>
</body>
</html>
document.write, but where? You have to specify this.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello</title>
</head>
<body>
<pre><script type="text/javascript">
function myfunction() {
d = document.getElementById('hello');
d.style.display = "block";
d = document.getElementById('callme');
d.style.display = "none";
}
</script>
</pre>
<div id="hello" style="display:none">
Hello
</div>
<div id="callme">
<input type="button"
onclick="myfunction()"
value="Call function">
</input>
</div>
</body>
</html>
I can't explain the "hang" but please take a look at this page for a primer on document.write: http://javascript.about.com/library/blwrite.htm I would also like to second that you probably want to write to a specific element in the page rather than just overwriting the entire page.

Categories

Resources