Hey there i am using this little jquery:
$("area.imagefield[data-name='" + searchText + "']").each(function() {
to check if the value of the attribute "data-name" matches exactly the variable "searchText".
But i need to check if the value of the attribute "data-name" is index of the variable "searchText", so using the
.indexOf
What i tried:
$("area.imagefield[data-name=]").each(function() {
if ($(this).attr("data-name").indexOf(searchText) != -1) {
console.log("match");
} else {
console.log("no match");
}
But there is no log in the console... :/ any idea´s ?
Actually your code looks good except one typo.
Remove the equal sign after data-name otherwise it's an invalid css selector:
So area.imagefield[data-name=] should be area.imagefield[data-name]
Try this way:
$("#imagefieldID").each(function() {
if ($(this).attr("data-name").indexOf(searchText) != -1) {
console.log("match");
} else {
console.log("no match");
});
jQuery data()
Is the normal way of working withdata attributes in jQuery, and probably what you would want to use.
$('area.imagefield').each(function (i) {
if ($(this).data('name')===searchText) {
console.log('match '+i);
} else { console.log('no match '+i); }
});
made a fiddle: http://jsfiddle.net/filever10/mau93/
Related
I am using if else condition in jQuery to handle check boxes.
My condition is that at least one check box is selected and after that alert if condition is running and not the other one. Here is my code
$(document).ready(function() {
$('#outer_menu').click(function() {
var $fields = $(this).find('input[name="mychoice"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
if(".a:checked "){
$(".language").find(".translate-language").toggleClass("translate-language translate-language_show");
} else if (".a_orignal:checked") {
$(".language").find(".orignal-language_hide").toggleClass("orignal-language_hide orignal-language");
} else {
alert('chose one');
}
return false;
}
});
});
our else if condition is not working when if condition false
I think what you are trying to do is to check whether the element with class a or a_original is checked, for that you need
if ($(".a").is(":checked ") {
$(".language").find(".translate-language").toggleClass("translate-language translate-language_show");
} else if (".a_orignal").is(":checked") {
$(".language").find(".orignal-language_hide").toggleClass("orignal-language_hide orignal-language");
} else {
alert('chose one');
}
use .is() to check whether the element satisfies the given selector
you need to fetch the jQuery object for the target element
Look at this line of code:
if(".a:checked ")
I believe it should be:
if ($(".a:checked "))
That might not be the end of your issues though, unless a is a class rather than you intending to select links.
Same problem here:
else if (".a_orignal:checked")
Change to:
if($(".a").is(":checked")){
and:
else if ($(".a_orignal").is(":checked")){
The .prop() method gets the property value for the first element in the matched set.
Write:
if(".a").prop("checked"){
$(".language").find(".translate-language").toggleClass("translate-language translate-language_show");
}
else if (".a_orignal").prop("checked"){
$(".language").find(".orignal-language_hide").toggleClass("orignal-language_hide orignal-language");
}
For example, I have
<div class="welcome_font">name</div>
and
<div id="nameho" style="color:#5AC7E6;">another-name</div>
I want to write an "if" statement in jquery/javascript where if "name" matches "another-name", then do something. How do I do that?
The .html() function grabs the inner html when using jQuery. So you could use the following to compare the two:
if ( $('.welcome_font a').first().html() === $('#nameho').html() )
{
...
}
let me know if that makes sense or if you have any questions :)
Try,
if( $('.welcome_font a').text() == $('#nameho').text() )
{
////Do something
}
Research first next time. You could get this with a simple search.
if($(".welcome_font a").text() == $("#nameho").text())
{
//To do
}
var name_1 = $('.welcome_font').text();
var name_2 = $('#nameho').text();
if(name_1===name_2) {
alert('yes');
} else {
alert('no');
}
Demo : http://jsfiddle.net/TSGqC/
or
var name_check = ($('.welcome_font').text()===$('#nameho').text()?true:false);
if(name_check) {
alert('yes');
}
Demo : http://jsfiddle.net/TSGqC/1/
If I have multiples classes call "location" and I need to find if "Red" is in one of the class can I do that in jQuery?
<td title="Location" id="location_1" class="location" colspan="5">Red</td>
<td title="Location" id="location_2" class="location" colspan="5">Yellow</td>
.
.
.
<td title="Location" id="location_10" class="location" colspan="5">Orange</td>
I tried the following but is not working.
if($(".location").find("Red")){
alert("found!");
}
What is the proper way to do it...if it is possible. Many Thanks!
Working jsFiddle Demo
Try this:
if ($(".location:contains(Red)").length !== 0) {
alert('found');
}
References:
:contains() Selector - jQuery API Documentation
If you have the color name in a variable:
var color = 'Red';
if ($(".location:contains(" + color + ")").length !== 0) {
alert('found');
}
See jsFiddle Demo.
You can
var reds = $(".location").filter(function(){
return $.trim($(this).text()) == 'Red'
})
if(reds.length){
alert('found')
}
The argument to .find() is a selector, not a text string to search for.
if ($(".location:contains(Red)").length > 0) {
alert("found!");
}
You should try to find their text() (this maps to "InnerText" in javascript):
$("td").each(function()
{
if($(this).text()=="Red")
{
//Do what you want
}
});
Try like
$('.location').each(function(){
var my_cnt = 0;
if ($(this).text() == "Red") {
my_cnt += 1;
}
if (my_cnt > 0) {
alert("Match Found at "+my_cnt+" times");
} else {
alert("Match Not Found");
}
});
I'd suggest, based on the assumption you want to do something if it's found, rather than just read a number of alerts:
$('.location').filter(function(){
return (this.textContent || this.innerText).indexOf('Red') > -1;
}).addClass('redFound');
JS Fiddle demo.
The above allows you to style the elements in which the string 'Red' was found (indexOf() returns -1 if a string is not found).
If you'd prefer the search to be case-insensitive, though you could simply use a regular expression, with .test():
$('.location').filter(function(){
return /\bred\b/gi.test(this.textContent || this.innerText);
}).addClass('redFound');
JS Fiddle demo.
References:
addClass().
filter().
JavaScript regular expressions.
test().
I want to check a textarea whether it is empty or not. For this I write the following code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?
I am getting it correctly. This is what I did.
Click on validate, it said Please Write Problem Description.
Write something and click. Nothing happened.
Remove the text. Click on validate, it said Please Write Problem Description.
Note: Use a trim function to eliminate empty spaces.
Code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Demo: http://jsfiddle.net/TZGPM/1/ (Checks for Whitespaces too!)
Do check for white space in the value like this
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute.
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value.replace(/ /g,'').length) {
return true;
} else {
alert("Please Write Problem Description");
return false;
}
}
<textarea id="problem_desc"></textarea>
<button onclick="validateForm()">Validate</button>
I'm trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($('#element'))) {
// do something
}
if ($('#element').is(':empty')){
//do something
}
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
You can also make it into a jQuery plugin, but you get the idea.
I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):
if($.trim($("selector").html())=='')
White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:
if ($someElement.children().length == 0){
someAction();
}
!elt.hasChildNodes()
Yes, I know, this is not jQuery, so you could use this:
!$(elt)[0].hasChildNodes()
Happy now?
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
If by "empty", you mean with no HTML content,
if($('#element').html() == "") {
//call function
}
In resume, there are many options to find out if an element is empty:
1- Using html:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
2- Using text:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
3- Using is(':empty'):
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
4- Using length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
In addiction if you are trying to find out if an input element is empty you can use val:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Empty as in contains no text?
if (!$('#element').text().length) {
...
}
Another option that should require less "work" for the browser than html() or children():
function isEmpty( el ){
return !el.has('*').length;
}
You can try:
if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}
*Replace white spaces, just incase ;)
document.getElementById("id").innerHTML == "" || null
or
$("element").html() == "" || null
Vanilla javascript solution:
if(document.querySelector('#element:empty')) {
//element is empty
}
Keep in mind whitespaces will affect empty, but comments do not. For more info check MDN about empty pseudo-class.
if($("#element").html() === "")
{
}
Are you looking for jQuery.isEmptyObject() ?
http://api.jquery.com/jquery.isemptyobject/
Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289
$.extend($.expr[':'], {
trimmedEmpty: function(el) {
return !$.trim($(el).html());
}
});
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
Try this:
if (!$('#el').html()) {
...
}
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by #qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})