0

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

Tushar
  • 85,780
  • 21
  • 159
  • 179
Tomas Lucena
  • 1,204
  • 1
  • 14
  • 31
  • Use Double equal to or Triple equal to. Refer [this](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) – Bugfixer Aug 31 '15 at 04:45

3 Answers3

3

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('');
        // ^^^^
    }
});
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Note that you are missing the `this` keyword! `$(this).html('');`, `$(this).text('')`, or better `$(this).empty()` – Ram Aug 31 '15 at 04:42
  • @Vohuman I've added that in the last code snippet, can you please check again – Tushar Aug 31 '15 at 04:43
  • sorry man, dont work (continue applying for all p) but a guy gave me the solution!!! I will post it – Tomas Lucena Aug 31 '15 at 04:50
2

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
        }
    });
Unni Babu
  • 1,839
  • 12
  • 16
0

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.

Murali Mohan
  • 126
  • 7