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

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);

Related

When selecting all radio buttons with knockout, it doesnt recognize the input

This fiddle clarifies things And my selectAll method with pure jquery.
self.selectAll = function( data, event){
$(".dataQueryRadioBtn").each(function() {
$( this ).prop('checked', true );
});
}
When you click on one of the radio buttons and then on Click Me a message shows you the number of the clicked radio button. When you do the same now first clicking on Select All it doesn't show every radio button. Only those you clicked yourself. Why is that so?
The problem is that Knockout has no way to know that the checked property of your <input> has been changed because you only registered a click handler for each.
You can solve this easily by triggering the click event:
$(".dataQueryRadioBtn").prop('checked', false).click();
But generally, when you're in the realms of your viewModel (just like in your selectAll method) you shouldn't rely on DOM elements (it's the elements that should rely on your view-model, not the opposite) to fetch data but rather explicitly change the observable value.
And in your case:
function ViewModel () {
var self = this;
// ...
self.allPossibleTags = []
self.selectAll = function(data, event){
self.selectedTags(self.allPossibleTags);
}
}
// upon document.ready
$(document).ready(function() {
var viewModel = new ViewModel();
viewModel.allPossibleTags = $('.dataQueryRadioBtn').get().map(function(elm) { return elm.value });
ko.applyBindings(viewModel);
});
See Fiddle

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.

$(this) is alerting previous selected values in jquery

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
}

.class selector not working

I'm working in a card game system that the player can select the card by clicking on it and then select the place to put it on. My problem is that when the player click on the target place, nothing happens.
This is my try: http://jsfiddle.net/5qMHz/
And this is my code:
function target() {
$(".target").on("click", function() {
$("#"+x).appendTo(this);
console.log(x);
});
};
What's wrong?
Try binding with document, since you change the class during document ready and there was no element with the class target initially
$(document).on("click",".target", function() {
$("#" + x).appendTo(this);
console.log(x);
}
WORKING FIDDLE
Firstly, your practice of putting function references in to jQuery objects is rather odd. The problem however is that because the .target class is applied after DOM load you need to use a delegate selector. Try this:
var $card
$(".card").on("click", function () {
$card = $(this);
if ($(".myslot").length) {
if ($(".myslot").is(':empty')) {
$(".myslot:empty").addClass("target");
} else {
alert('No empty slots');
}
}
});
$('.field').on('click', ".target", function () {
$card.appendTo(this);
$card = $();
});
Example fiddle
At the moment you are trying to bind the event handler, the elements don't have a class target yet. From the documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
(Technically the elements exist, but they are not (yet) addressable by the class target)
You have three options to solve this:
Add the class to your HTML markup.
Bind the handler after you added the class to the elements.
Use event delegation.
The first two don't really fit to your use case, since your are adding the class target in response to an other event and the number of elements with the class target changes over time. This is a good use case for event delegation though:
$('.field').on('click', '.target', function() {
// ...
});

checkbox running script onclick before actually setting the checked flag

I have a combobox with checkboxes. I am using jQuery to add a Click event to all of the checkboxes. When the checkbox is checked, a script is supposed to run and check an attribute of the checked box to determine it's type and then perform functions accordingly:
function () {
$('.RcbTag').find('input[type="checkbox"]').click(function () {
var evtCB = $(this);
var id = $(this).closest(".rcbSlide").siblings(".RcbTag").attr("id");
var rcbObject = $find(id);
rcbObject.get_items().forEach(
function (item, index) {
if (item.get_attributes().getAttribute('GUIDType') == 'group' &&
item.get_checked()) {
alert("Checked");
}
});
});
The problem right now is that it appears that the script is running before the checkbox is actually flipped to "checked". So in this example, it looks to see if the item attribute is 'group' and if it's checked. This always returns false, but will return true when I uncheck it. So I'm missing some order of events here. How do I fix this?
I think you're mixing jQuery click handlers and the Telerik code. Let's try and just stick with the Telerik-sanctioned events and I think everything will work like you're expecting.
On your RadComboBox, add an event handler declaritively like this:
OnClientItemChecked = "ComboBoxRowClick"
Then declare the JS function as you have it now (except we want to name it and not keep it anonymous):
function ComboBoxRowClick(sender, args) {
if (args.get_item().get_attributes().getAttribute('GUIDType') == 'group' &&
args.get_item().get_checked()) {
alert("Checked");
}
}
For more info on the client side functions from Telerik, you can check this link: http://www.telerik.com/help/aspnet-ajax/listboxitem-client-api.html
Also, you might run into this small annoyance where you have to click in the little checkbox itself, and not anywhere on the row (as one might expect). You can find a workaround for that one here: http://www.msigman.com/2010/07/telerik-radlistbox-fix/
try using change instead of click? that way you will catch changes made via keybord as well. and it will solve ypur problem.

Categories

Resources