arkjoseph
arkjoseph

Reputation: 494

Jquery remove divs not equal to search results

Original question: here Upon searching i need to alter the results across rows which are equal to the search val();

For this example lets assume we need 90042.

Current js:

(function($) {

            $(document).ajaxComplete(function(e, xhr, settings) {
                var zip = ($("#edit-field-zip-value").val());

                $('.zip div').filter(function() {
                    return $(this).text() == zip;
                 }).css('color','red');

            });

        }(jQuery));

Markup:

<table>
 <tbody>
   <tr>
    <td>
      <div class="zip">
       <div style="color: red">90042</div>
       <div>90052</div>
       <div>90062</div>
       <div>90072</div>
       <div>90082</div>
      </div>
    </td>

    <td>
     <div class="marker">
      <div>foo</div>
     </div>
    </td>

    <td>
     <div class="dma">
      <div>Pheonix</div>
      <div>Flagstaff</div>
      <div>Tucson</div>
      <div>Lipsum</div>
      <div>Goro</div>
     </div>   
    </td>
   </tr>
   </tbody>
   </table>

The end goal here is to remove all div's other than 90042, foo, and pheonix.

Something like this:

<table>
 <tbody>
   <tr>
    <td>
      <div class="zip">
       <div style="color: red">90042</div>
      </div>
    </td>

    <td>
     <div class="marker">
      <div>foo</div>
     </div>
    </td>

    <td>
     <div class="dma">
      <div>Pheonix</div>
     </div>   
    </td>
   </tr>
   </tbody>
   </table>

I have a feeling the results of my questions will result in un-even rows so it may be necessary to append end results to new divs or table. ( Might be wrong here tho )

Upvotes: 0

Views: 684

Answers (2)

Drew
Drew

Reputation: 898

here's a code to remove all div's other than what you have indicated.

$("td > div > div").not(":first-child").remove(); 

See it in action here.
Is this what you are looking for?

Upvotes: -1

Yuval
Yuval

Reputation: 3433

So with your answer to @DonZacharias' comment, you could format the HTML this way

<table>
 <tbody>
   <tr>
    <td class="zip">90042</td>
    <td class="marker">foo</td>
    <td class="dma">Pheonix</td>
   </tr>
   <tr>
    <td class="zip">90043</td>
    <td class="marker">foo</td>
    <td class="dma">Arizona</td>
   </tr>
  </tbody>
</table>

and then the code becomes

var zip = 90042;
$('td.zip').not(function() { return $(this).text() == zip; }).parents('tr').remove();

otherwise you have to find the index of the div you're looking for. It ain't a good idea, but if you insist, this should do it:

var zip = 90042;
var index = -1;
$('.zip div').each(function(i,el) { if ($(el).text() == zip) { index = i; return false; } });
if (index != -1) {
    $('.zip, .dma, .marker').each(function(i, el) {
        $(el).find('div').not(':eq('+index+')').remove(); 
    });
}

Upvotes: 2

Related Questions