Jquery if $this attribute selector contains a word - javascript

Is it possible to use the jquery attribute contains selector on $(this)? I cannot find any examples. I am trying to see if input fields contain a certain word.
$("#form input").keyup(function() {
if ($(this).filter( "[name~='someWord']" )) {
console.log('yes');
}
});
The code returns yes for all input even if they don't contain someWord.

You have to use .is() at this context,
if($(this).is( "[name~='someWord']" )) {
console.log('yes');
}
Because .filter() would return a jquery object (element collection), and that would never be false.

You can do this even better with Vanilla JS in the event handler
$("#form input").keyup(function(evt) {
if (evt.currentTarget.name.indexOf('someWord') > -1) {
console.log('yes');
}
});
This checks the name attribute of the actual DOM element and does not add the overhead of the jquery wrapper.

Try
$("#form input").keyup(function() {
if ($(this).filter("[name~='someWord']").length) {
console.log('yes');
}
});
or better:
$("#form input").keyup(function() {
if ($(this).is("[name~='someWord']")) {
console.log('yes');
}
});

Related

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.
I tried the following code but the results does nothing.
#1. hasAttribute():
if ($('input[type=checkbox]').hasAttribute("disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#2. is():
if ($('input[type=checkbox]').is("[disabled]")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#3. prop():
if ($('input[type=checkbox]').prop("disabled", true)) {
$(this).closest('.chkbox').addClass("is-disabled");
}
So then I think the problem is on the line:
$(this).closest('.chkbox').addClass("is-disabled");
Any idea?
Thanks.
You can use :disabled selector
see here
You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.
This code should work as you desire.
$(function() {
// Grab all inputs with the type checkbox.
var input = $('input[type=checkbox]')
// Check for each of the input fields (i, el stands for index, element)
input.each(function(i, el) {
// Does it have the attribute disabled?
if(el.hasAttribute('disabled')) {
// Add the class 'is-disabled'
$(el).closest('.chkbox').addClass('is-disabled')
}
})
$('input[type=checkbox]').change(function(){
if ($(this).is(":checked")) {
$(this).closest('.chkbox').addClass("is-checked");
} else {
$(this).closest('.chkbox').removeClass("is-checked");
}
});
});

What's the proper way to check if an element has an ID or not with jQuery?

I thought I could check if an element has an ID with has() like this:
if ($button.has('#Menu-Icon')[0] !== undefined) {
//do stuff
}
but I learned that instead, it checks if there's a descendant which matches the ID. So I don't think this is the right jQuery method to use, but nevertheless it's the only thing that seems to show up when I search the subject on Google.
Which jQuery method is the right one for checking if a given element has a certain ID or not?
Check the id using the attr() function like this:
$('button').on('click', function() {
if ($(this).attr('id') == 'TheID') {
alert('The button you pressed has the id: "TheID"!');
} else {
alert('You pressed a button with another id..');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="TheID">TheID</button>
<button id="anotherID">anotherID</button>
You can check the id property like of the underlying element like
if ($button[0].id == 'Menu-Icon') {
//do stuff
}
or jQuery way to use .is()
if ($button.is('#Menu-Icon')) {
//do stuff
}
The has() method is used to filter a set of elements by checking whether those contains elements matching the passed selector, also it returns a jQuery object so checking for undefined will never be true
Try something like below which should work:
<div id=""></div>
$(document).ready(function(){
if($('div').attr('id') != ''){
alert("have id");
}else{
alert("do not have id")
}
});

Check element class name

This should be a quickie!
I need to differentiate between two elements on click by their class name.. for example
html:
<p class='p1'>paragraph element</p>
<p class='p2'>paragraph element</p>
jquery:
$('p').on('click', function() {
if ($(this).attr('class', 'p1') {
callThisFunction();
} else {
doNothing();
}
});
if ($(this).is(".p1")) {
or
if ($(this).hasClass("p1")) {
$(this).attr("class", "p1") actually sets the class attribute. Checking against $(this).attr("class") is no good either because it could have multiple classes.
$(this).hasClass('p1') is faster.
Use .hasClass() to check the class.
$('p').on('click', function() {
if ($(this).hasClass('p1')) {
callThisFunction();
} else {
doNothing();
}
});
working demo : http://jsfiddle.net/nSMDA/
$('p').on('click', function() {
if ($(this).hasClass('p1')) {
console.log("do something");
} else {
console.log("do nothing");
}
});
Example:
http://jsfiddle.net/DNKUX/
If you need to differentiate behavior like this- where only some elements take action - what you should really be doing is only binding to the ones that match rather than to every <p> element.
$('p.p1').on('click', callThisFunction);
Here is a new fork of goma's jsfiddle: http://jsfiddle.net/4b8Pf/2/
if($(this).attr('class') === 'p1'){} is what you want to use. $(this).attr('class', 'p1') sets the current element to have a class of p1.

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

jQuery check if target is link

I have a global function to capture clicks.
$(document).click(function(e){
//do something
if(clickedOnLink)
//do something
});
I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.
http://jsfiddle.net/Af37v/
You can try to see if the element you clicked on either is or is a child of an <a> tag.
$(document).click(function(e){
if($(e.target).closest('a').length){
alert('You clicked a link');
}
else{
alert('You did not click a link');
}
});
I believe using is will actually have better performance than the answers suggesting closest:
$(e.target).is('a, a *');
This checks if the element itself is an a or if it is contained with an a.
This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
If the exact target is link, then you can use .is()
Example:
$(".element").on("click", function(e){
if($(e.target).is("a")){
//do your stuff
}
});
EDIT:
If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length
Example:
$(".element").on("click", function(e){
if($(e.target).closest("a").length){
//do your stuff
}
});
With jquery just get the tagName attribute
$("a").prop("tagName");
Updated:
You could check if the target is an a or if a parent is an a.
$(function () {
$(document).on('click', function (e) {
$target = $(e.target);
if ($target.closest('a').length > 0) {
alert('i am an a');
}
});
});
http://jsfiddle.net/8jeGV/4/
You can test if there's a <div> under <a> by testing if the .children() <div> has anything inside it. If nothing is inside, or there is no <div>, the if statement will return false.
I suggest this code:
$(document).click(function(e){
var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false),
//run code
if ( willRedirect === false ){
e.preventDefault();
//the link will not redirect
if ( $(this).children('div').html() ){
//there is a <div> inside <a> containing something
}
else {
//there is no <div> inside <a>
}
}
else {
//the link is not pointing to your site
}
});

Categories

Resources