How to use event.target inside jQuery child selector? - javascript

I want to check if a child-element of a clicked div has a certain class.
So i do this:
$('.panel').on('click', function (event) { if($(".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); } });
The problem: I have more then one .panel class. Since my whole site gets generated by the user and json-files, i need a dynamic environment without ids.
So, actually my if-statement is preventing all .panel-clicks from doing their job.
I want to do something like this:
if($(event.target + ".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); }
So i want to select all input - elements from the clicked div without
having an array and loop through it.
Is this possible? Or what is the most efficient way of selecting child-elements of the clicked one?

You should rather use this to get the targeted element:
$(this).find("input").hasClass('h5_validator_error');
or
$('input',this).hasClass('h5_validator_error');

You shoud make the dom object $(event.target) and then apply the jquery method on it.
Try this:
$('.panel').on('click', function (event) {
if($(event.target).find('input').hasClass('h5_validator_error')){
alert('true');
}
else{
alert('false');
}
});
Working Example

Related

Clicking on a button that has onClick already on

I know this sounds silly, but I need to create a function that finds a button that has onClick attached to it. And then clicks it.
So like:
<div onclick="coolFunction()" class="coolClass">
<p>Click Me!</p>
</div>
I tried searching for it by doing something like this:
$('.coolClass').attr('onClick') == 'coolFunction()'
Which did actually find it, the problem is I don't understand how can I click on it because it's in an if method.
Your selector would be something more like $('[onclick="coolFunction()"]').
So to do what you describe, you could do this
$('[onclick="coolFunction()"]').trigger('click');
Although, unless coolFunction() cares about being explicitly by this DOM element, you could just call coolFunction(), without having it piggy-back on your click handler.
Update: With an argument
// Note selector is less specific, but still targeted
$('[onclick^="coolFunction"]').trigger('click');
With, this, you can trigger the click handler, and coolFunction(var) in your HTML would work as expected.
if ( $('.coolClass').attr('onClick') == 'coolFunction()' )
{
$('.coolClass').click();
}
$('.coolClass').each(function() {
$this = $(this);
if ($this.attr('onClick') == 'coolFunction()') {
$this.trigger('click')
}
});
This will select all elements with .coolClass, check if the onClick attribute matches the coolFunction call and trigger the click event on that element.
As couzzi said, you can first verify if all the elements of the class coolClass have the attribut coolFunction and when it's the case you can just apply what you want to do on them.
$('.coolClass').each(function() {
$this = $(this);
if ($this.attr('onClick') == 'coolFunction()') {
$this.trigger('click')
}

Jquery Click with 2 ids with Condition for one specific

I have a jquery click function calling 2 different ids, but I need to perform a peculiar code only for the id #go1.
How could it be done?
$('#go1, #go2').click(function(){
if ('#go1').click() {
//do what I need
}
});
Thank you
You need to use event target along with is selector to check whether target is element #go1:
$('#go1, #go2').click(function(e){
if ($(e.target).is('#go1')) { // or if (e.target.id == '#go1')
//do what I need
}
});

Checkbox and click event handling

I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});

How to use javascript to select (a) child(ren) element(s) of a hovered element?

assuming I have a (very large) div tag and inside the div tag I have a (normal size) button, now I want to be able to create a shortcut that if a user is hovering over the div tag, they can press return key to click the button.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div').hover(function(){
$('this button').click();
});
}
});
This is how I imagine it might look like in jQuery (didn't work obviously). I am open to suggestions. jQuery solutions are fine, plain javascript solutions are even better.
It's actually pretty easy.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div:hover button').click();
}
});
Don't use .hover() or .on('hover') because they are simply not selectors.
You can use .is(":hover") within your keypress handler to determine if the proper div is being hovered:
$(window).keypress(function(){
if($("#target").is(":hover")){
alert("pressed!");
}
});
http://jsfiddle.net/y7joukzw/2/
(NOTE: Make sure you click within the "result" frame to ensure it is the active frame when testing the jsfiddle)
Rather than checking for hover on every keypress, you're better off reversing the order of event checking so that you only incur the keypress overhead while the user is hovering. Something like:
function checkKeypress(e) {
// Check keypress and perhaps do something
}
$('div').hover(
function(){
$(window).keypress(checkKeypress);
},
function() {
$(window).off('keypress', checkKeypress);
}
);

Can I determine what was clicked using JavaScript?

Once again I've inherited someone else's system which is a bit of a mess. I'm currently working with an old ASP.NET (VB) webforms app that spits JavaScript onto the client via the server - not nice! I'm also limited on what I can edit in regards to the application.
I have a scenario where I have a function that does a simple exercise but would also need to know what item was clicked to executed the function, as the function can be executed from a number of places within the system...
Say I had a function like so...
function updateMyDiv() {
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
how could I get the ID (for example) of the HTML element that was clicked to execute this?
Something like:
function updateMyDiv() {
alert(htmlelement.id) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
I can expand on this if neccessary, do I need to pass this as an arguement?
The this keyword references the element that fired the event. Either:
<element onClick="doSomething(this);">
or
element.onclick = function() {
alert(this.id);
}
Bind your click events with jQuery and then reference $(this)
$('.myDivClass').live('click', function () {
updateMyDiv(this);
});
var updateMyDiv = function (that) {
alert(that.id);
// save the world
};
You don't need to pass "this", it is assigned automatically. You can do something like this:
$('div').click(function(){
alert($(this).attr('id'));
})
Attach the function as the elements event handler is one way,
$(htmlelement).click(updateMyDiv);
If you are working with an already generated event, you can call getElementByPoint and pass in the events x,y coords to get the element the mouse was hovering over.
$('.something').click(function(){
alert($(this).attr('id'));
});
You would need to pass it the event.target variable.
$("element").click(function(event) {
updateMyDiv($(event.target));
});
function updateMyDiv(target) {
alert(target.prop("id"));
}
Where is your .click event handler? Wherever it is, the variable this inside of it will be the element clicked upon.
If you have an onclick attribute firing your function, change it to
<tag attribute="value" onclick="updateMyDiv(this)">
and change the JavaScript to
function updateMyDiv(obj) {
alert(obj.getAttribute('id')) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
use the .attr('id') method and specify the id which will return what you need.

Categories