What does "this" return in JS? - javascript

I have 2 questions
What does this refer to? I understand that it is some kind of container for the object in question.
I am trying to pass a variable using a form due to lack of better options. My idea was to have a <a onclick> and in the onclick, to have this.form.submit();
<form action="/justtesting/" method="post">
<a onclick="this.form.submit();" href="">click this</a>
<input name="pageid" value="12" type="hidden">
<input name="mid" value="5" type="hidden">
</form>
And that way I pass the variable.
I have seen this before but instead of <a> they used a button.

The short answer:
this refers to the object that called the function that is currently executing
The long answer:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/this

"this" without any context always refers to the -window- object.
var test = 123;
alert(test); // 123
alert(this.test); // 123
You'll want to have some sort of jQuery click event for that , searching for whatever value you want to pass along with the form submit.

this refer to the current element , in your case it refers to the A tag
if you use <Button type="Submit">click this</Button> then it will work without javascript
And if you use A tag then don't leave href attribute as it can cause problem
click this

inside of an in-line binding (e.g. onclick or onload attribute of an element), this refers to the element itself. So, for example:
Click me
<!-- Alerts "http://google.com" -->
<img src="foo.jpg" width="50" height="50" onload="alert(this.width+'x'+this.height);" />
<!-- Alerts "50x50" -->
So by saying this.form you're saying "grab the form that this element belongs to (if any)", then you're calling the form element's submit() method.

this when passed to an event
say refers to the anchor object passed to the function as param.

In the case of an event handler, 'this' refers to the target event in question
Example:
<div onclick="console.log(this) id="me">click me</div>
2. In the case of an object, it refers to the object in question
Example:
x = { hi: function(){console.log("Hi "+this.name)}};
x.name= "Bill";
x.hi(); // Hi Bill
3 Both these behaviours can be altered by calling a so-called binding, either by using bind, apply or call (bind is implemented here)
var bind = function(obj, fn){ return function(){ return fn.apply(obj, arguments)}
y.name = "Joe";
x.hi = bind(y, x.hi);
x.hi(); //Hi Joe
4 When no such is specified, this refers to a global object, which equals to window in browsers in compatibility mode, and to undefined in so-called strict mode.

In normal Javascript events, this refers to the element which the handler is bound to. However, if your event was bound with attachEvent in IE, this refers to the window. In your code, this refers to the clicked anchor tag. Here's how to properly implement your desired functionality in jQuery:
$("a").click(function() {
$(this).closest("form").submit();
});

Related

Accessing element attributes before Polymer element registration

I'd like to declare attributes directly on a Polymer element, which are then passed inside the element and are readable/accessible outside of the element script.
I'd like to use the values of such attributes for deciding how to register the element.
tl;dr
I'm having an issue where I need to register an element some time after the whole page has loaded - i.e I want to manually register the element.
A solution for registering elements on demand:
<dom-module id="foo-element">
<template>
<span> Foo element </span>
</template>
</dom-module>
<script>
window.addEventListener("app-ready", function() {
"use strict";
Polymer({
is: "foo-element",
properties: {
//..... rest of element properties, methods, etc
Explaining what I'm doing above:
Instead of using HTMLImports.whenReady(<element-registration-code>), I use addEventListener(event, <element-registration-code>
I broadcast app-ready when I want the registration to happen
This allows me to register the element, on-demand
The reusability problem of the above solution
This poses a severe reusability problem - while this element in one of context needs to be registered at some specific point in time, in other context it might not - it should register itself using the standard HTMLImports.whenReady(<elementCode>) method.
An ideal example:
<!-- Registers automatically when `HTMLImports` are ready, the "regular" way-->
<foo-element></foo-element>
<!-- Registers only when it picks up an `app-ready` event-->
<foo-element no-auto-register register-on-event="app-ready"></foo-element>
and the element could look something like this:
<dom-module id="foo-element">
<template>
<span> Foo element </span>
</template>
</dom-module>
<script>
// if `no-auto-register` is set on the element,
// do not use `HTMLImports.whenReady()` and use
// `addEventListener` to register when an event
// with the value of `register-on-event` property fires.
</script>
Long story, short
Is there any way to declare a flag/property/attribute directly on the element which would decide how the registration should happen?
Passing an attribute to element might not work as element needs to be in ready state for that. Below are three ways that might help you with what you are trying
One way to lazy register your elements in Polymer is to use Polymer.Class instead of Polymer constructor. This way until you register your element manually it will not get rendered. Below is an working example of same.
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="polymer/polymer.html">
<dom-module id="poly-form">
<template>
<style></style>
I am parent Element
<div>
<button onclick='register()'>Save</button>
</div>
<show-form></show-form>
</template>
</dom-module>
<script>
Polymer({
is: 'poly-form',
});
//element to lazy register
var showForm = Polymer.Class({
is: 'show-form',
ready: function() {
this.textContent = 'I am working...';
}
});
function register() {
var form = document.querySelector('poly-form');
//lazy register the element
document.registerElement('show-form', showForm);
}
</script>
<poly-form></poly-form>
In this example show-form element does not render until the button is clicked.
Note I've never really tried this with element containing dom.
Second way this should also be possible with importHref method.
Third way is global setting lazy-register where element gets register only when its first instance is called.
Sorry, the snippet is not as well constructed as it could have been. Hope it helps.
Class Style Constructor
If you want to set up your custom element's prototype chain but not register it immediately, you can use the Polymer.Class function. Polymer.Class takes the same prototype argument as the Polymer function, and sets up the prototype chain, but does not register the element. Instead it returns a constructor that can be passed to document.registerElement to register your element with the browser, and after which can be used to instantiate new instances of your element via code.
var MyElement = Polymer.Class({
is: 'my-element',
// See below for lifecycle callbacks
created: function() {
this.textContent = 'My element!';
}
});
document.registerElement('my-element', MyElement);
// Equivalent:
var el1 = new MyElement();
var el2 = document.createElement('my-element');

jQuery: $(this).attr('id') not find id of element - undefined

I'm trying to get id and just simply alert it onclick although is does just "undefined"...
Can you help me out?
important Code:
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='1' onclick="alertme()" />
jQuery:
function alertme() {
alert($(this).attr('id'));
}
Can you see the problem? I can't...
My bad:
I'm sorry, I wanted to simplify the code and I did not realize that I used "alert()" as name for customized function.
First problem to fix is the function name, which I suspect is different in your actual code because otherwise you wouldn't have gotten as far as you have.
You've used an old-school "onclick" attribute to associate the function with the element. Nothing assures that this will be bound to the element as you expect. You could either change the element:
Better would be to use jQuery to bind the handler:
$("#1").on("click", function() {
alert(this.id);
});
The problem is, as others said - the context of the this keyword.
this refers to the DOM element (as you thought it does) in the CALL ITSELF, but once you called alertme() it is not defined in its scope.
To see it you can look at this JS:
function alertme(){
alert($(this).attr('id'));
console.log(this);
}
and this HTML markup:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="console.log(this); alertme()" />
And you will see that you get in the console first the element, then in the alert 'undefined' and then in the console the window.
To fix it you can either simply specify the meaning of this in the call, using javaScript's Function.prototype.call() function:
Change only in the HTML the markup to
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme.call(this)" />
and it will work with the your alertme().
OR you can just pass this into alertme like so:
function alertme(elem){
alert($(elem).attr('id'));
}
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme(this)" />
Sources:
Nice article to understand 'this' in jQuery
this in JS binded by on markup

javascript this.value doesn't work?

sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!
First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});
The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>
Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}

What is the meaning of this code in Javascript

I am newbie to Javascript, I have difficulties getting the meaning of this code properly. I would like to share my thought over the code,and I need your guidance to understand it correctly.
<body>
<form>
<input type="button" value="Click Me!" id="say_hi" />
</form>
<script type="text/javascript" src="js_event_01.js"></script>
</body>
function hi_and_bye() {
window.alert('Hi!');
window.alert('Bye!');
}
var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_bye;
My understanding: the event "onclick" calls the function "hi_and_bye" when ID is "get_alerts". Similarly this could be applied to any event, and I can give an id attribute to any element and that id would be responsible to make an accessible corresponding input element.
Your understanding is correct. You could give an id to any DOM element, not only inputs. Then using the getElementById you could retrieve a reference to this element.
In this example that's what you are doing:
// Get a reference to a DOM element that has id="say_hi"
var hi_button = document.getElementById("say_hi");
// subscribe to the onclick event handler of the DOM element we retrieved on
// the previous line and attach this handler to the hi_and_bye javascript function
hi_button.onclick = hi_and_bye;
I don't think that the body of the function itself requires any more explanation: it will just display 2 alerts once after the other when this function executes.

Removing the event listener on a button programatically

I have a button which is registered with a onclick event as shown
<Input type="Button" name="Register" Value="Register" onclick="CallMe();"/>
Is it possible to programatically remove or deregister the onclick event on this button?
You could set the onclick attribute to null.
var el = document.getElementById('inputId');
el.onclick = null;
or better just remove the attribute altogether with the removeAttribute() docs method of the element.
var el = document.getElementById('inputId');
el.removeAttribute('onclick');
you will need to add an id to the element though for this..
example code at http://jsfiddle.net/gaby/PBjtZ/
document.getElementsByName("Register")[0].onclick = ""
or
document.getElementsByName("Register")[0].removeAttribute("onclick")
Make sure to place this in a JS tag at the end of your document. So the DOM is available when this script is running.
the first example gets all elements with the name "Register" in your dom and returns the first, then it finds and sets the onclick attribute to an empty string. (could be null to)
the second example does the same, but removes the attribute "onclick".
Be careful if you have more then one element with the name "Register" you should do it like Gaby aka G. Petrioli told you to.

Categories

Resources