How to inherit Class in javascript? - javascript

The function is not working, It is not putting values in "input".
function example(id){
this.code= function(){$('.'+id).val(id)}
this.validate= function (){
$('.'+id).keyup(function (e){
if(e.keyCode==13) this.code();
})
}
}
body
<input type="text" class="test"/>
<input type="text" class="test1"/>
<script type="text/javascript">
var test= new example('test')
var test1= new example('test1')
test.validate()
test1.validate()
</script>

Your keyup event handler will have a different "this". You can use bind to correct the problem
keyup(function (e){
if(e.keyCode==13) this.code();
}.bind(this))
When you bind to an event, the handler is called with the "this" keyword set to the object that fired the event, not the object that created the event.

Well javascript is a bit hard to understand when it comes to this..
this article explains some of it http://www.crockford.com/javascript/inheritance.html
But one way to solve it would be
function example(id){
this.code= function(){$('.'+id).val(id)}
var self = this;
this.validate= function (){
$('.'+id).keyup(function (e){
if(e.keyCode==13) self.code();
});
}
}

Related

Copy a 'change' EventListener function

I have this HTML tag
<input type="file" id="File">
which has an event listener
document.getElementById("File").addEventListener("change", function() {alert("test")});
I would like to copy the function in the listener but all the following lines return null or undefined
document.getElementById("File").getAttribute("change")
//null
document.getElementById("File").change
//undefined
document.getElementById("File").getAttribute("onchange")
//null
document.getElementById("File").onchange
//null
How can I copy the anonymous function from the listener?
You can't.
You didn't keep a reference to it, and there is no API to pull it out of the list of listeners.
Refactor your code so you keep a reference to it from the start.
function myChangeHandler (event) {
alert("test");
}
document.getElementById("File").addEventListener("change", myChangeHandler);
As an alternative you could trigger the event of the original object with dispatchEvent(). But note, if the function uses this reference it will refer to the original element the event is attached to. Same is true if the event paramter is used (function(event){}).
document.getElementById("test").addEventListener("change", function() {
console.log("test");
console.log("triggered element id: " + this.id);
});
document.getElementById("manual").addEventListener("click", function() {
document.getElementById("test").dispatchEvent(new Event('change'));
});
<input id="test">
<button id="manual">manual</button>
Another alternative is to overwrite the standard addEventListener() function so it will store a reference to the given function. This is an example of this. You probable want to store the reference in a different way but kept it easy as an example.
You only have to make sure that the function is overwritten before the element is created.
//Store the orignal addEventListener() function under a new name so we can still use it.
Node.prototype.originalAddEventListener = Node.prototype.addEventListener;
//Create a variable where we store the handler for the #test1 element
var test1Handler;
//overwrite the orignal function with our own so it will store a reference to the #test1 event handler in the variable
Node.prototype.addEventListener = function(e, fn){
if(this.id === 'test1') {
test1Handler = fn;
}
this.originalAddEventListener(e, fn);
}
//Attach event with the overwritten function, lets say this is done by an extarnal libary.
document.getElementById('test1').addEventListener('change', function(){
console.log("Changing element id: " + this.id);
});
//When the button is clicked the change handler of test1 is copied to test2.
document.getElementById('exec').addEventListener('click', function(){
document.getElementById('test2').addEventListener('change', test1Handler);
});
<label for="test1">Test 1</label><input id="test1"><br>
<button id="exec">Add Test 1 change handler to Test 2</button><br>
<label for="test2">Test 2</label><input id="test2"><br>
If you want to do this for the window object you probably need to overwrite window.addEventListener because window isn't a Node

oninput isn't calling the function

I'm trying to run a function whenever an input's text changes. I'm using the oninput attribute to do that. I followed W3Schools tutorial. When I try it on in my own code, (or JSFiddle,) the function doesn't get called.
JSFiddle
$(document).ready(function () {
function myFunction() {
alert("asdf");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" oninput="myFunction()">
Because oninput calling a method myFunction that is out of scope. There is no reason for it to be inside the ready handler
//$(document).ready(function () { <--get rid of this
function myFunction() {
alert("asdf");
}
//}); <-- get rid of this
Now it will work

Add onclick to element, but keep current onclick event

Is it possible to add a javascript event to a DOM element that already has a onclick event, but I want to keep that event property.
I have radio buttons like this:
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this);" />
in which I want to add
window.location.href=window.location.href
while keeping the original onclick, but I have no access to the html, I can only modify through javascript.
so my desired code will be
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this); window.location.href=window.location.href" />
Wrap the
window.location.href=window.location.href
in function, lets call it
onRadioButtonClick()
then, just do
var self = this; //keep the context of the file
$("[name=checkout-payment]").on('click', function () {
onRadioButtonClick.call(self); //call the method with the normal context.
//continue code..
});
You could try:
var curHandler = $('#checkout-payment-56').attr("onclick");
$('#checkout-payment-56')[0].onclick = null;
$('#checkout-payment-56').click(function () {
window.location.href=window.location.href;
});
I actually found out there was a much simpler way to acheive my desired result.
$( '.webshop-checkout input[type="radio"]' ).click(function() {
location.reload(true);
});
i am sorry i was not clear in my original post, and it has been edited.
If you want to add this to every .webshop-checkout input[type="radio"], you could do it that way:
$('.webshop-checkout input[type="radio"]').click(function(){
window.location.href=window.location.href;
});
JS Fiddle Demo
$("#checkout-payment-56" ).bind( "click", function(evt) {
console.log('that works');
//sessionStorage.setItem(evt.target.id,evt.target.className);
});

How to prevent default on form submit?

If I do this I can prevent default on form submit just fine:
document.getElementById('my-form').onsubmit(function(e) {
e.preventDefault();
// do something
});
But since I am organizing my code in a modular way I am handling events like this:
document.getElementById('my-form').addEventListener('onsubmit', my_func);
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}
How can I prevent default now?
The same way, actually!
// your function
var my_func = function(event) {
alert("me and all my relatives are owned by China");
event.preventDefault();
};
// your form
var form = document.getElementById("panda");
// attach event listener
form.addEventListener("submit", my_func, true);
<form id="panda" method="post">
<input type="submit" value="The Panda says..."/>
</form>
Note: when using .addEventListener you should use submit not onsubmit.
Note 2: Because of the way you're defining my_func, it's important that you call addEventListener after you define the function. JavaScript uses hoisting so you need to be careful of order of things when using var to define functions.
Read more about addEventListener and the EventListener interface.
All you have to do is add a parameter to your function and use it inside.
var my_func = function(event) {
event.preventDefault();
}
The parameter inside now represents the parameter from the addEventListener.
i known this is old, but just for the sake of it.
try
document.getElementById('my-form').addEventListener('onsubmit',
function(event){event.preventDefault();my_func();});
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}

Can you refer to the element on which a handler called a function?

I usually never use this programming style, but thought I would give it a try just so I know whats up with it.
Here is my input tag HTML:
<input id="Read" type="checkbox" onclick="readClicked()" checked>
And my associated function:
function readClicked() {
console.log(this);
console.log($(this));
alert('Read Clicked!');
}
Is there anyway to refer to the element in which the handler that called readClicked() was called from inside the function?
Something like:
function readClicked() {
var caller = function.caller;
var type = $(caller).attr('type');
}
Pass this as a parameter:
onclick="readClicked(this);"
Then your function would be:
function readClicked(el) {
var type = $(el).attr('type');
}
Although, since you're using jQuery, I would suggest binding the event with jQuery, instead of inline. Like this:
$("#Read, #OtherElement").on("click", clickHandler);
function clickHandler() {
var type = $(this).attr("type");
}
DEMO: http://jsfiddle.net/mWLTw/
<input id="Read" type="checkbox" onclick="readClicked(this)" checked>
function readClicked(elem) {
console.log(elem);
console.log($(elem));
alert('Read Clicked!');
}

Categories