Tomas Lucena
Tomas Lucena

Reputation: 1526

Avoid jquery function for all the content

I have a table with 20 rows. In each row there is an element

<p class="exp-date">'.$cust->Expiration_Date.'</p>

This element is going to be repeated and return different values but in a lot of rows return 0001-01-01. I want to hide this content so I wrote this in javascript

var exp = $(".exp-date").val();  
var exphide = '0001-01-01';
    if(exp = exphide) {
        $(".exp-date").html('');
    }

and also have tried this

$('.exp-date').each(function() {
        if(exp = exphide) {
            $(".exp-date").html('');
        }
    });

But in both cases apply the jquery on the first row and modify everything not only where the statement is declared.

Someone any idea?

Thanks in advance

Upvotes: 0

Views: 68

Answers (3)

Tushar
Tushar

Reputation: 87203

You're using assignment in if statement. The condition exp = exphide will always evaluate to true and the code inside the if statement will execute for all the elements.

Change

if(exp = exphide) {

to

if(exp == exphide) {

or

if(exp === exphide) {

Also, use text() instead of html() to get the date, and use trim() on it to remove extra spaces before comparing.

Use this/$(this) inside the each to get the innerText of the current element.

$('.exp-date').each(function () {
    if ($(this).text().trim() == exphide) {
    //  ^^^^^^^^^^^^^^^^^^^^^^^^
        $(this).html('');
        // ^^^^
    }
});

Upvotes: 3

Murali Mohan
Murali Mohan

Reputation: 136

First you should correct the syntax in the if condition and then try the below code. When you are using "each" for looping you should pass index and value to the callback function as shown below. Then you can achieve the desired result.

var exphide = '0001-01-01';
$('.exp-date').each(function(index, value) {
        var exp = $(value).text(); 
        if(exp == exphide) {
            $(value).html('');
        }
    });

I suggest not to remove the content from table cell instead you can hide. Hope this helps.

Upvotes: 0

Unni Babu
Unni Babu

Reputation: 1814

Use == and "this", else it will point to all classes. Code shown below

    var exphide = '0001-01-01';
    $('.exp-date').each(function() {
        if(this.innerHTML == exphide) {  //this.innerHTML
            $(this).html('');  //this.html..else will point to all classes
        }
    });

Upvotes: 2

Related Questions