How do I check if an element is NOT empty with jquery? - javascript

I need to check if an element is empty and if another is NOT empty. The first part of the if works but how do I check if the #dynamicForm element is NOT empty?ยจ
This obviously doesn't work but I need something like it:
if ($("#formButton").is(':empty') && $("#dynamicForm").is(':notempty')) {
//do stuff
}

if(!$("#dynamicForm").is(':empty')){
// code here...
}
Note the not operator (!) in front.

First of all you can check if the selected element is empty and negate it:
!$('#dynamicForm').is(':empty')
Furthermore you can check if it's not empty with jquery selector :not:
$('#dynamicForm').is(':not(:empty)')
A third way would be to select all elements, that are not empty and check the length of the jquery collection:
$('#dynamicForm').not(':empty').length
If you need this check in several places you can add your own function to jQuery:
$.fn.notEmpty = function() {
return !$(this).is(':empty')
}
you can use it like this:
if($('#dynamicForm').notEmpty())
That isn't realy clean and it's not keeping with the jquery conventions. So better extend the selectors instead of extending the functions:
$.extend($.expr[':'],{
notEmpty:function(c) {
return !$(c).is(':empty');
}
});
Now you can use it very straightforward:
if($('#dynamicForm').is(':notEmpty'))

Related

If element has "class1" and/or "class2" in Jquery .hasClass() function

I want to check if an element has this class or another class like this:
if ( $elem.hasClass("foo") || $elem.hasClass("bar") ) {
// do something
}
And I also want to check if an element has two classes:
if ( $elem.hasClass("foo") && $elem.hasClass("bar") ) {
// do something else
}
Is there a way to do this all within the hasClass() function? Something like:
if ( $elem.hasClass("foo bar") ) {
// do something when element has both classes
}
else if ( $elem.hasClass("foo","bar") ) {
// do something when element has either class
}
Strictly answering to your question: no, you can not.
hasClass() accepts a single argument.
As pointed out by others, you might use is(), but here is a test that shows that performances are very much penalized.
I suggest you to stay with your current code.
You could do something a little different to accomplish this. Not sure if this meets your needs though.
Use multiple selectors you can see if an element that matches exists on the page
Use each to execute the code you want
Example of something like this:
$("span.foo, span.bar").each( function() {
$(".test").html("foo or bar was found");
});
JS Fiddle: http://jsfiddle.net/s3gL5pwm/1/
A second solution that uses if would be to use .is() instead.
For example:
if ($("span").is(".foo, .bar")) {
$(".test").html("foo or bar exists");
};
JSfiddle: http://jsfiddle.net/eL2a8smt/

Combining to elements for a focus function

How would I combine two elements to use the focus function? #s_type and #s_ctry I'm trying to avoid extra code by retyping the same exact thing twice.
the way i'm trying it now doesn't work.
<script type="text/javascript">
$(document).ready(function() {
$("#s_type", "#s_ctry").focus(function() {
var first = $(this).find("option").eq(0);
if(first.val() === "0") {
first.remove();
}
});
});
</script>
You have to use a comma in the selector itself:
$("#s_type, #s_ctry")
Reference
You were nearly there! You need to combine them into one string. When you pass 2 arguments to jQuery, the second one is a context in which to match the selector, you can't provide multiple selectors as separate arguments:
$("#s_type, #s_ctry").focus(function() {
//Do stuff!
});
Alternatively, you can use the add method to add elements to the matched set:
$("#s_type").add("#s_ctry").focus(function() {
//Do stuff!
});

Is there a way to select all elements with a certain property value?

I'm building a fairly simple plugin with jQuery that validates a form. When an element is assessed to be valid I run
$(this).prop("valid", false);
In certain instances I'm going to want to block the form from submitting if anything is invalid. Essentially I'm looking for a way to select all the elements where the valid property is false? Am I going to have to iterate over all relevant elements and check for a false reading or is there a jQuery selector that I've overlooked? Something like:
$("input[valid=false]");
Would be nice. Any suggestions?
Try this...
$('input').filter(function() {
return this.valid === false;
});
It will return all input elements (do you mean :input?) where its valid property is false (notice strict equality comparison).
Reusable :invalid jQuery selector filter
You could write a simple selector filter:
$.extend($.exp[":"], {
invalid: function(element) {
return element.valid === false;
}
});
Then simply combine it with whatever selector your using to get your elements ie:
// all invalid inputs
$(":input:invalid");
// or all invalid text boxes
$("input[type=text]:invalid");
That's it.
Let's put it all in a simple plugin that you can easily include in your script code or put in a script file (for reusability purposes on several pages as well as several applications if you'd use the same validation functionality):
(function($) {
$.extend($.exp[":"], {
invalid: function(element) {
return element.valid === false;
}
});
})(jQuery);
use this:
$(':input').each( function() {
return $(this).prop('valid');
});

JavaScript/jQuery "if" condition syntax

I'm attempting to evaluate a class to see if it contains some text in my click handler, but I can't get my code to act properly. What am I missing?
The if statement is looking to see whether the class of the clicked object has the word "headline" in it.
$('[class^=edit_]').click(function(){
var element = $(this).attr('class');
var field = element.split(/_(.+)/)[1];
if ($(this).attr('[class*=headline]'))
{
alert("headline");
}
else
{
alert("not headline");
};
});
Is it possible to construct my if statement with something that evaluates the var field = element.split(/_(.+)/)[1]; since that is really where the information resides.
Something like:
if (element *= "headline"){do this};
I'm not sure I understand all of the "evaluators" that exist in JavaScript to know if I can evaluate a string like that.
Upon re-reading your question, there's an even simpler approach, just check the .className for the string you want using .indexOf(), like this:
if (this.className.indexOf('headline') != -1)
Previous answer:
The closest version to what you have, checking if an element matching a selector is .is(), like this:
if ($(this).is('[class*=headline]'))
But there's another method more appropriate here (if you're checking for a full class, not part of one), you can use .hasClass() like this:
if ($(this).hasClass('headline'))

How can I tell whether an element matches a selector?

Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p or .myclass? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?
The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.
Will this work as intended? I can't figure out Javascript object comparisons.
$(selector, myElement.parentNode).each({
if (this == myElement) // Found it
});
Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...
You can use the is() method:
if($(this).is("p")){
// ...
}
Without jQuery, using Element.matches():
var elements = document.querySelectorAll('div');
console.log(
elements[0].matches('.foo'), // true
elements[0].matches('.bar'), // false
elements[1].matches('[title=bar]'), // true
)
<div class='foo'></div>
<div title='bar'></div>
See supported browsers list
I believe the is() method is what you are looking for.
Otherwise, you might just try selecting the item directly, if that is what you mean.
So if it's an "a" with a class of "myclass", just do $("a.myclass")
I can't apply my selector to the
element's parent and look for children
with the same ID as mine.
You can't do that anyway - the id attribute must be unique.
Maybe you just want:
$(".complicated #selector p.with > div.manyParts").length
If there are no matches, length returns 0, which is falsy, so you can use it in an if statement, like:
if($(".doesThis #exist").length) {
// Do things
}
Probably would be worth storing it in a separate variable and THEN checking the length; that way, if you need to do anything with the matched elements, you don't have to execute the same selector again.
Try Element.matches()
Element.matches()
document.addEventListener("click", event => {
if (event.target.matches(".elementsClass")) {
// It matches
} else {
// Does not match
}
});

Categories