Error function not defined in javascript - javascript

I have a sample code:
<input width="50" type="text" value="" name="application_id" id="text_input">
Test Name
And javascript
function addSelect(id, title) {
document.getElementById('text_input').value = title;
}
When I run code, result error is addSelect is not defined ? demo here , how to fit it ?

Your script has been defined to run onLoad, which means your function is not available in the global scope like you expect. It will be defined in a local scope of some onLoad method (whichever jsFiddle uses). With this setting, I think jsFiddle puts your code into this or something similar to:
window.onload = function () {
// Your code
};
(which is similar to onDomReady option)
This is so you don't have to worry about binding the right event and you can just test your script (making sure the page has loaded).
When you try to call the function, which you expect to be in the global scope, it won't work. Just change the setting on the left to no wrap (head) (or no wrap (body))
http://jsfiddle.net/TmLut/3/
And as mplungjan has pointed out, and I somehow didn't realize at all, when using the onclick of the anchor element, you'd probably want to prevent default behavior of the link (even if it's just to go to "#"), and can be achieved in several ways, but one is:
Text
Although at the same time, one might argue you shouldn't have inline handlers at all, and would want to be binding the event with Javascript completely. Depending on that case, you have options to prevent the default behavior still. In any case, you can still grab ahold of the event object (normalized per browsers...which jQuery does, by the way) and call event.preventDefault(); in the method.

Here its http://jsfiddle.net/TmLut/4/
I changed onload to head on the left side select box

Related

Changed data attribute not recognized in jquery selector

I've the following html structure
<body data-page="first">
<div class="start">Test</div>
</body>
and the following js
$('body[data-page="first"] .start').on('click',function (){
body.attr('data-page','second');
});
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
I would expect, that after the second click on .start, the console would show "Test", but it doesn't...
Can you tell me what I'm doing wrong?
Thanks in advance!
While you have your answer, I don't think the essential point has been made in any of the answers so far, and that is that the binding of an event handler must happen after the target element exists.
When you try to bind an event handler to a particular element in the DOM, the element must exist at the time. If it does not exist, the handler has nothing to bind to, and so the binding fails. If you later create the element, it's too late, unless you re-run the binding statement.
It will soon become second nature to call appropriate event handler binding statements after you create a new element (by modifying the HTML using javascript) that needs a handler.
For instance, in my current project I regularly make AJAX calls to a server to replace blocks of HTML as things happen on the page. Even if some of the new elements are exactly the same as the ones being replaced, they will not inherit any bindings from the replaced elements. Whenever I update the HTML I call a function that contains necessary statements to bind my event handlers to the new copy of the active elements.
Your code would work if you made the following change:
$('body[data-page="first"] .start').on('click',function ()
{
body.attr('data-page','second');
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
})
A couple of other (off-topic, but related) points:
It's possible to bind a handler to an element multiple times. The trick to avoiding this is to include the .off() method in the chain before binding (noting though that .off("click") will unbind all click handlers bound to that element, not just yours) e.g.
$("#mybutton").off("click").click(function(){myHandler()});
"the arrow function doesn’t have its own 'this' value" () so don't use arrow functions in event handlers if you plan to reference any of the element's properties via 'this'. e.g.
$("#mybutton").off("click").click(() => {console.log(${this.id})}); // >> "undefined"
The issue is that the page is rendered with the data-page set to first, and when you click again on it, that part of javascript still see "first", since is not rerendered, so you need a dynamic function, the read all the intereaction with that button, and than check wich value that attribute has. Like this you can make infinite cases, and still go on.
$('body .start').on('click',function (){
const attr = $('body').attr('data-page');
if(attr === 'first') {
$('body').attr('data-page','second');
} else {
console.log('second');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-page="first">
<div class="start">Test</div>
</body>
And if you don't like the fact that is targetting all the "body" wich is weird, becouse you should have only 1 body, you can use an ID to target the right one
PS: is never a good idea to duplicate your function, if you can set everything in a dynamic function, that reads everything, is easier to debug in the feature, and is lighter and more clean to work on
$('body[data-page="first"] .start').click(function (){
var body = $('body[data-page="first"] .start');
body.attr('data-page','second');
});
This method can help :
var timesClicked = 0;
$('.start').on('click',function (){
timesClicked++;
if (timesClicked>1) {
console.log('Test');
}
});

Prevent anchor tag to jump

It is my first post on SO, I am using it already quite a while, always found a solution via search. Now I'm starting to dig deeper into programming - right now learning Java Script - and I couldn't find the exact answer for my beginner problem:
I've created a simple photo gallery where the thumbnails point to the image via href. The images are not displayed by default. By clicking on a thumbnail, the corresponding image appears thanks to the :target pseudo element. This way I can bypass the cascading nature of my HTML structure and address elements higher in hierarchy.
See fiddle:
https://jsfiddle.net/ahu1kaqf/
The problem is, that this "hack" has the side effect of putting the image to the very top of the window due to its default anchor jump behavior.
So what I want to accomplish is to turn off or bypass just the jump behavior.
Therefore, solutions with JS like "preventDefault" or "return false" are not suitable as they turn off the complete anchor behavior.
My idea was to read the yScroll position just before the click and pass it to another function which triggers just after the page jump. By appending an onclick event on the anchor tag I found out that the function executes before the actual jump and I can read the current scrollY position:
function posY(){
console.log(window.scrollY);
scry = window.scrollY;
}
Then, after the anchor event has finished, I would like to pass the variable scry to another function which triggers just after the anchor jump to undo the jump:
function undoJump(){
window.scrollTo(0, scry);
}
It doesn't really work with a click event as the function triggers before the actual jump.
The js code in the fiddle is in script tags because putting just the functions into the js window (of course without script tags) shows an error in the console, I don't know why...
Sorry, I'm really a beginner, thank you all for your help!
https://jsfiddle.net/ahu1kaqf/1/
var classname = document.getElementsByClassName("thumb");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener("click", posY);
}
function posY(e){
e.preventDefault();
console.log(window.scrollY);
}
Remove the onclick as it's just not the best way to do it. Add a class to the links OR use querySelectorAll based on the parent class. The benefit here is, you don't have to remember to add a class or a onclick. It's less code to deal with and easier to manage.
https://jsfiddle.net/ahu1kaqf/2/
In either case, you can stop the normal event behavior with e.preventDefault();
For the second part, you'll probably just want to set a global in this case. Set a global outside all of the functions and change it on click. You could probably get more complex with objects, and promises and such, but, honestly, it'd be just as easy to set a global value. It's good to try to avoid them, but they can be simple useful solutions depending on the overall complexity of the application in question.
Yes, you need to prevent the default action (which is a navigation action).
In modern browsers, that means you can do this (note I'm passing the global event object as a parameter):
<div class="thumb">thumb1</div>
Then in your js code you can do this:
function posY(e){
e.preventDefault()
console.log(window.scrollY);
}

javascript function called with an onclick attribute on button

I don't understand why this is not working.
I'm sticking to the reference on w3schools.
Here the code :
HTML:
<button onclick="click()">Test</button>
Javascript:
function click() {
alert("Hello !");
}
It doesn't work because you have configured JSFiddle to wrap the JavaScript in a function and call it onload. This stops your function being a global so it isn't in scope for your intrinsic event handler attribute.
Additionally, after you fix that, the weird scoping rules for intrinsic event attributes (I have no idea where these are documented) means that click is resolved as the button's click property before the scope is searched far enough to find the global click function.
The quick and dirty solution is:
Rename the function to something that doesn't clash with existing property names
Pick a no wrap option from the menu on the left of JSFiddle
The proper solution is to attach your event handlers with JavaScript. This isn't the 1990s and we should avoid using the techniques of that era that fail to separate concerns. Keep your JS in one place and your HTML in another.
<button>Test</button>
<script>
document.querySelector('button').addEventListener('click', click);
function click(evt) {
alert("Hello !");
}
</script>
This code doesn't work because there's already a click native method and shadowing it prevents the normal click event handling. Give it another name and it will work.
A way to see that is to define your button as
<button onclick="console.log(click)">Test</button>
I think you cann't give a function name as click. Change your function name & it should work.
click seems to be reserved.
Try renaming the method: http://jsfiddle.net/qeCE5/1/
function clickMe() {
alert("Hello !");
}
you need to change the function name. 'click' might be a reserved keyword, so it wont recognize when you call it. rename it to other names eg. 'democlick()'. also don't forget to save your code with '.html. extension. please tell me if any issue exists. thanks.

calling outside javascript function within jquery code

$(function(){
function f1(){}
function f2(){}
}
<Input type = radio Name = radiobutton Value = "something" checked=checked onClick= //here call f1()//>
I try to get access to f1 function in OnClick
code like this doesn't work:
$.function.f1()
$.function().f1()
That's because you should be doing it something like this:
$(function () {
function foo () { }
function bar () { }
// bind
$('input').on('click', foo);
});
... instead of putting an onclick= attribute on your HTML markup.
EDIT
As requested, some quick notes on why you should do the jQuery bind instead of the onclick markup thing.
You're already using jQuery, plain and simple. Use it.
There should be significant effort made to separate your HTML, CSS and JS. HTML in HTML files, JS in JS files, blah. Putting in onclick=do_backflips() in your HTML markup violates that, and will lead to nightmarish maintenance issues in the future, among other things.
DOM0 onclick= syntax is inherently 1:1. Which means that naturally, for each event of each element, you only get to attach one single event handler. That definitely sucks balls.
By defining your f1 and f2 functions inside the document.ready handler function, you're limiting their scope within that function. This means that they can't be referenced outside that scope, which means that the script interpreter won't know about f1 where your HTML markup is. You have to attach event handlers where the handlers are known, and that's inside document.ready (if that makes sense).
The point of using $( function(){ ... } ) is that whatever inside is run only after the DOM has finished loading. There's no benefit to defining functions there unless the goal is to keep the namespace clean and use the functions in the local scope.
In this case you need the functions outside the scope so just move them outside the anonymous function or bind the event to the radio button inside the scope.

Sending click event to parent anchor

How do I send a click event (JS or JQuery) to a parent object that is an anchor? My basic HTML looks like:
<a href="javascript:myFunc(1,2,3)">
<img id="btn1" src="myimg.png">
</a>
So I can easily reference the anchor through button via:
document.getElementById('btn1').parentNode
However,
document.getElementById('btn1').parentNode.click
while it doesn't seem to raise an error in the console on firebug, the javascript function doesn't seem to be firing either. How do I send a click to this thing. By the way, I don't have control of the HTML so I can't just ad an ID to the anchor tag.
Gone are the days when it's okay to use the href="javascript:blah", especially if you're using a library like jQuery, Dojo, ExtJs or the rest. Event handlers should always be attached outside of the HTML.
$(function() {
$("#btn1").click(function() {
$(this).parent().click();
};
});
Here is a snippet that you can test on SO pages (copy+paste into Firebug)
$("#hlogo a").click(function() {
alert("a!");
return false;
});
$("#hlogo a img").click(function() {
alert("img!");
$(this).parent().click();
});
Normal Links with Normal HREF's
// assuming the link is always the immediate parent of #btn1
$("#btn1").parent().trigger("click");
Links with Javascript-Commands as HREF's
I note in your case though that your HREF value is a call to a javascript function, with parameters. For this, you may want to evaluate that HREF, rather than click the link:
// run the href-javascript from the parent anchor
eval($("#btn1").parent().attr("href"));
I've built a test-case and used firebug to try both methods. The first returns 1, showing the link was clicked, but the javascript is never executed. The second method actually executes the javascript found within the HREF value of the link itself. This should be an adequate solution to your specific need.
EDIT: ignore this answer as it's no good for links; see the comments below.
The click property of an a element is a function property, aka a method; all you are doing is referencing the property, not invoking it.
document.getElementById('btn1').parentNode.click();
(note the () to cause the method to be invoked) should do it, though if you are using jQuery already then Jonathan Sampson's answer will do what you need - there's no point in loading the library and then not using it :-)
Although Jonathan's answer can be shortened, as jQuery provides a click method:
$("#btn1").parent().click();
jQuery way maybe like this:
$(event.target).closest('a').trigger('click')
or in your words something like this
$('#bth1').closest('a').trigger('click')

Categories