$(this) is alerting previous selected values in jquery - javascript

I am using $(this) to get the current selected(clicked) element of a specific class .For the first time its coming fine i.e i am getting the selected element but as soon as i click on second time it is giving the alert of the old as well as new selection .I am not able to find out what is the issue..
Here is the code..
$('.l-one').click(function () {
var tableName = $(this).text();
//Table Name Lable
$("#lbl").text(tableName);
//Panel
$("#Perticulars").show();
$('.my-new-three').click(function () {
var dishvalue = $(this).text(); //get the value of dish item and display in the table
//console.log(dishvalue);
alert(tableName);
alert(dishvalue);
if (localStorage.getItem(tableName) != null) {
alert("b");
In the alert(tableName); i am getting alert of all the tables selected previously .Please help me to resolve this..
Thanks...

use below code . only click assign events to each time when you click '.l-one'. so if you click '.l-one' 3 time 'click' event assign 3 time to '.my-new-three'.
unbind() function remove event from element and bind() function attach event to element. so here as per your code each time when you click '.l-one' unbind remove click event from '.my-new-three' and bind function again assign click event to '.my-new-three'.
$('.my-new-three').unbind('click').bind('click',function () {});
other way is to use separate click event methods.
$('.l-one').on('click', function () { });
$('.my-new-three').on('click',function () {})

Use separate click handler instead of using click handler insider another one. Consider this code:
$('.l-one').click(function () {
//code
}
$('.my-new-three').on("click",function () {
//code
}
Assuming If .my-new-three exists inside .l-one or .my-new-three creating dynamically then use this:
$('.l-one').on("click",".my-new-three",function () {
//code
}

Related

How to check which element caused an on change event to fire

Js novice here. I've got a few unfinished pages I've inherited, on one page there are two drop downs which use an on change jquery event to create child dropdowns once a value is selected in the first one.
After speaking with the user it is not desired for one of these drop downs to do that. The two sets of drop downs have different names and IDs but the same classes. I'd like to catch the name or ID of which drop down was modified in the event but so far have had no luck syntactically doing that.
EDIT: I've added the on change event code here for reference. The html dropdowns are generated by some really wonky nested partial views
$(document).on("change",
".genericClass",
function () {
$(this).addClass("updated");
if ($(this).hasClass("blank")) {
$(this).removeClass("blank");
var $newAddRow = $(this).parents(".relationControl:first").find(".relationAddRowTemplate")
.clone().removeClass("relationAddRowTemplate")
.addClass("relationAddRow")
.show();
$newAddRow.insertAfter($(this));
}
});
you can use below code, you will the get the id of select element caused event triggered
$(document).on("change",
".genericClass",
function () {
alert($(this).attr('id'));
$(this).addClass("updated");
if ($(this).hasClass("blank")) {
$(this).removeClass("blank");
var $newAddRow = $(this).parents(".relationControl:first").find(".relationAddRowTemplate")
.clone().removeClass("relationAddRowTemplate")
.addClass("relationAddRow")
.show();
$newAddRow.insertAfter($(this));
}
});
you have two options:
1- Use listener
select.addEventListener( 'change', event => {}); then event.target
2- add scope watch
$scope.$watch(function () { return self.selectedValue; }, function (newValue, oldValue) {
if (newFilter != oldFilter) {
// call what ever you want
}
}, true);

How to go through array with dynamically added elements with jquery?

I have a HTML table created with javascript where i have possibility to add new rows (dynamically added elements). In one of the tds i have an input field that fires a bootstrap modal to open. In the modal I have radiobuttons with options and when OK button is clicked the value from the radiobutton is set in the inputfield. The problem is that the value gets updated on every row, not just the row i clicked.
Since the elements are added dynamically i used
$(document).on('click', 'input', function (e) {
doSomething();
});
Any idea how to solve this problem?
Updated with more code
$(document).on('click', 'input', function (e) {
var inputForm = e.target;
modal.modal({show:true});
modal.find(".btn-success").click(function () {
var choice = $("modal").find('input[type=radio]:checked').val();
if (choice) {
modal.modal('hide');
inputForm.value = choice;
}
});
});
Without any furter information about the code you are running it's hard to help you.
But, you might be able to use the target property of the event (e), to look at what element actually triggered the click, to be able to see which row/textbox to update when the modal is closed.

How to refresh drop down when click on select using jquery?

I have a drop down in mvc
#Html.DropDownList(
"Name",
new SelectList(Model.Product, "Value", "Text"),
string.Concat("-- ", "Please select the item", " --"),
new { id = "Product", Class = "form-control" }
)
I fill dropdown dynamically. It works fine. Everything works fine. When i change the item i perform action that i want using jquery onchange method and refresh the dropdown. But i want to refresh dropdown when user click on "Please select the item". When i click on please select the onchange method is not called. How i can do this?
$DropDown.on("change", function () {
//Here i perfome action
});
You might want to extract the "onchange" function in order to reuse it. Something like that
var changeCallback = function(e) {
// chage logic
}
$("#dropdownlistname").on("change", changeCallback);
$("#dropdownlistname").on("click", changeCallback);
$(document).ready(function(){
$('#dropdownlistname').change(function(e){
// Your event handler
});
// And now fire change event when the DOM is ready
$('#dropdownlistname').trigger('change');
});
More Information Here
Edit
You should provide a selector to the on function:
$(document).on('change', 'input', function() {
// Does some stuff
});
In that case, it will work as you expected. Here is the Fiddle using on function
user2052156's answer looks good but if you want the 'click' to happen only the first time then you can remove the click handler after the first call:-
$DropDown.on('click change', function(){
//Here i perfome action
$(this).off('click');
});
Fiddle

load() method is entered (executed) many times

in my html page, i have an image, and on clicking a button, i'm calling the function TestLoad() where it is changing the src of the image and when the image is loaded i'm doing something...
take an example:
javascript:
function TestLoad() {
alert('before');
$('#ImgTest').attr('src', 'Images/Image1.jpg');
$('#ImgTest').load(function () {
alert('after');
});
}
html:
<img id = "ImgTest" alt="" src="" style="width:100px; height:100px"/>
<input type="button" onclick ="TestLoad();" value="TestLoad"/>
my problem is:
when i click the button for the first time, i'm getting the alert "after" one time and if i click another time, the alert will be displayed two time and the third, 3 times...
Kindly advice
Thanks
Each time your handler executes, it adds another new load handler. You only need to assign the handler a single time. If you really need to do it this way, you can either remove the existing handlers first or check the events to see if it's already being handled:
var $imgTest = $('#ImgTest');
$imgTest.attr('src','Images/Image1.jpg');
$imgTest.unbind('load');
$imgTest.load(function(){
alert('after');
});
Or:
var events;
var $imgTest = $('#ImgTest');
$imgTest.attr('src', 'Images/Image1.jpg');
events = $imgTest.data('events');
if(events !== null && typeof events.load === undefined){
$imgTest.load(function(){
alert('after');
});
}
Your onclick event is probably binding another load event.
You don't need to keep adding the event to it. It already exists. If you need to bind another one, you'll want to unbind the previous event first.
.on("load", function() { ... });
.off("load");
You are binding multiple functions in your event handler
//bind this outside of your test load method
$('#ImgTest').load(function () {
alert('after');
});
function TestLoad() {
alert('before');
$('#ImgTest').attr('src', 'Images/Image1.jpg');
}

jQuery: Get reference to click event and trigger it later?

I want to wrap an existing click event in some extra code.
Basically I have a multi part form in an accordion and I want to trigger validation on the accordion header click. The accordion code is used elsewhere and I don't want to change it.
Here's what I've tried:
//Take the click events off the accordion elements and wrap them to trigger validation
$('.accordion h1').each(function (index, value) {
var currentAccordion = $(value);
//Get reference to original click
var originalClick = currentAccordion.click;
//unbind original click
currentAccordion.unbind('click');
//bind new event
currentAccordion.click(function () {
//Trigger validation
if ($('#aspnetForm').valid()) {
current = parseInt($(this).next().find('.calculate-step').attr('data-step'));
//Call original click.
originalClick();
}
});
});
jQuery throws an error because it's trying to do this.trigger inside the originalClick function and I don't think this is what jQuery expects it to be.
EDIT: Updated code. This works but it is a bit ugly!
//Take the click events off the accordion elements and wrap them to trigger validation
$('.accordion h1').each(function (index, value) {
var currentAccordion = $(value);
var originalClick = currentAccordion.data("events")['click'][0].handler;
currentAccordion.unbind('click');
currentAccordion.click(function (e) {
if ($('#aspnetForm').valid()) {
current = parseInt($(this).next().find('.calculate-step').attr('data-step'));
$.proxy(originalClick, currentAccordion)(e);
}
});
});
I think this:
var originalClick = currentAccordion.click;
Isn't actually doing what you think it is - you're capturing a reference to the jQuery click function, rather than event handler you added, so when you call originalClick() it's equivalent to: $(value).click()
I finally came up with something reliable:
$(".remove").each(function(){
// get all our click events and store them
var x = $._data($(this)[0], "events");
var y = {}
for(i in x.click)
{
if(x.click[i].handler)
{
y[i] = x.click[i].handler;
}
}
// stop our click event from running
$(this).off("click")
// re-add our click event with a confirmation
$(this).click(function(){
if(confirm("Are you sure?"))
{
// if they click yes, run click events!
for(i in y)
{
y[i]()
}
return true;
}
// if they click cancel, return false
return false;
})
})
This may seem a bit weird (why do we store the click events in the variable "y"?)
Originally I tried to run the handlers in x.click, but they seem to be destroyed when we call .off("click"). Creating a copy of the handlers in a separate variable "y" worked. Sorry I don't have an in depth explanation, but I believe the .off("click") method removes the click event from our document, along with the handlers.
http://www.frankforte.ca/blog/32/unbind-a-click-event-store-it-and-re-add-the-event-later-with-jquery/
I'm not a jQuery user, but in Javascript, you can set the context of the this keyword.
In jQuery, you use the $.proxy() method to do this.
$.proxy(originalClick, value);
originalClick();
Personally, I'd look at creating callback hooks in your Accordion, or making use of existing callbacks (if they exist) that trigger when opening or closing an accordion pane.
Hope that helps :)
currentAccordion.click is a jQuery function, not the actual event.
Starting with a brute-force approach, what you'd need to do is:
Save references to all the currently bound handlers
Unbind them
Add your own handler, and fire the saved ones when needed
Make sure new handlers bound to click are catched too
This looks like a job for an event filter plugin, but I couldn't find one. If the last point is not required in your application, then it's a bit simpler.
Edit: After some research, the bindIf function shown here looks to be what you'd need (or at least give a general direction)

Categories

Resources