Jacob
Jacob

Reputation: 71

Issue with change/each in jQuery

Tried to do some searching to no avail :(

I'm having an issue with an each loop in jQuery. It's supposed to detect a change in a select and then using the value of the select, run the loop and if the data-cid attribute value is equal to the value of the select, then it's supposed to display the div with the data-cid attribute. However I keep getting undefined errors.

Html

<div class="form-row">
    <label for="community">Select A Community</label>
    <select name="community" id="community" class="selectInput">
        <option value="0">No Community</option>
           <?php foreach ($communities as $c): ?>
                <option value="<?php echo $c->getcID(); ?>">
                      <?php echo $c->getName(); ?>
                </option>
           <?php endforeach; ?>
    </select>
</div>
<div class="form-row">
    <?php foreach ($communities as $c): ?>
        <div class="community-display" data-cid=<?=$c->getcID(); ?>>
            <div class="name">
                <?=$c->getName(); ?>
            </div>
            <div class="address">
                <?=$c->getAddress(); ?><br />
                <?=$c->getCity() . " " . $c->getState() . " " . $c->getZip(); ?>
            </div>
            <div class="contact">
                <?=$c->getPhone(); ?><br />
                <?=$c->getEmail(); ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

Jquery

<script>
$(document).ready(function(){
    $('#community').change(function(){
        $('.community-display').hide();
        $('.community-display').each(function(){
             if ($(this).data('cid').val() == $('#community').val()){
                 $(this).show();
            }
        });
    });
});
</script>

Edit: Included JSFiddle, and the error is type error, just not sure where http://jsfiddle.net/cj6st8y4/

Upvotes: 1

Views: 67

Answers (2)

PeterKA
PeterKA

Reputation: 24638

This is what you need:

$(document).ready(function(){
    $('#community').change(function(){
        $('.community-display').hide()
        .filter('[data-cid=' + this.value + ']').show()
    });
});

Upvotes: 1

Jacob
Jacob

Reputation: 71

Sorry guys for the dumb question, I just realized that the .data handler returns a value already, and that trying to get a val of a val is what was causing the error. Here's the fixed JS... I derped.

<script>
$(document).ready(function(){
    $('#community').change(function(){
        $('.community-display').hide();
        $('.community-display').each(function(){
             if ($(this).data('cid') == $('#community').val()){
                 $(this).show();
            }
        });
    });
});
</script>

Upvotes: 1

Related Questions