I have a button in my html that when clicked, I need it to pass the index attribute value to my click listener:
<button class="btn buy-button js-prevent-cart-listener guys" index="1">Add To Cart</button>
and the listener:
$('.girls').on('click', buyButtonGirlsClickHandler, index);
So that when I run this function, I can access the event value and use it within the function:
function buyButtonClickHandler(evt) {
console.log(evt.value);
}
I dont want to change it to have an 'onclick()' attached to the button. Is this possible and if so how? Obviously the code above is not able to pass the index value, and i have tried numerous times
You need not to pass the index in on function. You should try changing your on function to
$('.girls').on('click', buyButtonGirlsClickHandler);
and in the handler you can receive it by attr
function buyButtonClickHandler(evt) {
console.log(evt.value);
var index= $(event.target).attr("index");
}
https://jsfiddle.net/525npjfn/
or as #Andreas commented , use this inside click.
function buyButtonGirlsClickHandler(evt) {
console.log(evt.value);
var index = this.getAttribute("index");
alert(index);
}
https://jsfiddle.net/525npjfn/2/
On button click, you can store it's index value in a variable and then pass it into the desired function. This is the clean snippet to solve your problem.
Please use data- prefix to use custom HTML attribute otherwise HTML validators will cry for this.
$(document).ready(function() {
$('.js-prevent-cart-listener').click(function() {
var idx = $(this).attr('data-index');
buyButtonClickHandler(idx);
})
});
function buyButtonClickHandler(idx) {
console.log("This is index value " + idx);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn buy-button js-prevent-cart-listener guys" data-index="1">Add To Cart</button>
Instead of passing the event handler directly, wrap it inside a new function. Your index data will be passed because it stays in the scope.
let index = "whatever your index data is";
$('.girls').on('click', (e, index) => buyButtonGirlsClickHandler(e, index) );
Note: I'm using ES6 syntax there, may not work on old browsers.
Related
I've some buttons on my page. The mockup looks like this
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>
The goal is to get the value of the data-id attribute. Currently I'm using this javascript.
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(this).attr('data-id');
});
My problem is that when I log the value to my browser console console.log(id); I the value of the id variable is undefined.
What is wrong with my code?
Using arrow function expression implies the value of this is not the one you intend.
In this case you need to use event.target:
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(event.target).attr('data-id');
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>
To suggest you an alternative way:
$('.js-category-delete').on('click', function (event) {
const clickedItem = jQuery(this); // and also jQuery(event.target)
const id = clickedItem.data('id');
console.log(id);
});
The function keyword makes this what you've expected at first.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Pen: https://codepen.io/shifu462/pen/WVaGLB
Also, as a shortcut for
jQuery(event.target).attr('data-id');
I've used here another jQuery method to get the value of a data attribute.
jQuery(event.target).data('id');
Docs: https://api.jquery.com/data/
I use the following to get the json for each member and create an element with a click listener.
$.getJSON('/api/members', function (membersJson) {
$(membersJson).each(function (i, item) {
$('#contacts').append('<div class="membercard">' + item.Name + '</div>');
.click(() => show_details(item));
})
});
function show_details(item) {
$('#memberName').val(item.Name);
$('#memberOcc').val(item.Occupation);
}
When a membercard is clicked it is meant to send its info to a more detailed div. However, when clicking on any of the dynamically created divs, only the item data from the last json in the loop is sent to the detailed view. Why is this and how can I fix it?
you are binding and iterating inside a loop, this is to avoid in general, because the scope of the function will in the click, will take only the last element of the loop
Try refactoring like this:
$('#contacts').on('click', '.membercard', function() {
show_details($(this).data('item'));
});
$.getJSON('/api/members', function (membersJson) {
$(membersJson).each(function (i, item) {
var div = $('<div class="membercard">' + item.Name + '</div>');
div.data('item', item);
$('#contacts').append(div)
})
});
function show_details(item) {
$('#memberName').val(item.Name);
$('#memberOcc').val(item.Occupation);
}
This is a common problem with JavaScript. Essentially, because the click event happens after the loop, the “item” variable is equal to the last item. To fix this, simply change:
$(“#contacts”).click(() => show_details(item));
To:
let _item = item;
$(“#contacts”).click(() => show_details(_item));
This creates a copy of the variable that will have the same value even after the loop completes.
I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!
Here is my issue:
I am creating dynamically a button with an onclick function like this:
$("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');
The parameters are well read but the function is not trigger, and I've got this error message:
"bob is not defined" when bob is the string value of the param1.
Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.
Thanks much for your help!
That's because this string right here:
'onclick="remove('+param1+','+param2+');"'
Will look like this in the end:
'onclick="remove(foo, bar);"'
You probably want it to look like this:
'onclick="remove(\'foo\', \'bar\');"'
So change it to this:
'onclick="remove(\''+param1+'\', \''+param2+'\');"'
You could also do this:
$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
remove(param1, param2);
});
Edit: I also noticed that you were missing one " from your $()-call: $("#test) should be $("#test").
I can suggest you this
<script type="text/javascript">
//<![CDATA[
var i = 0;
$(function () {
$("#lnkAdder").click(function () {
// appending new item
$("#Container").append(
$("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
var data = ++i;
alert("I'm clicked, I'm number " + data);
})
);
});
});
//]]>
</script>
Add item
<div id="Container"></div>
The key here is the javascript closure.
As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.
You guys mind checking out this jsfiddle I made to help you understand my issue. http://jsfiddle.net/kr1zmo/DqbeX/8/:
item
item 2
item 3
item 4
<p id="result"></p>
<script language="javascript" type="text/javascript">
(function($) {
$.fn.liveBindTest = function() {
return this['live']('click', function() {
var savedvar;
if (!savedvar || savedvar == 0) {
// is false, do false things.
savedvar = 1;
jQuery('#result').append(savedvar);
} else {
// is true, do true things.
jQuery('#result').append(savedvar);
savedvar = 0;
}
return false;
});
};
})(jQuery);
jQuery(document).ready(function() {
$('a.cref').liveBindTest();
});
</script>
I want to save a variable for each click.
Take a look at this example.
Did you want to toggle which bit of code to execute? If you want to hold the value in a closure, you'll need to declare it outside of the live event handler function.
If the value needs to be held for each element matched by the selector, then you could use $(elem).data() to store the value like in this example.
You declared your variable inside the event handler, creating a separate local variable for each handler.
You need to declare the variable outside the function.
If you want a separate variable for each element, you can declare the variable and add the handler in an each call, or use jQuery's .data function.