SilverNightaFall
SilverNightaFall

Reputation: 4180

Getting HTML tag attribute of an element using jQuery

How would I alert the user if they selected more than one COP1000 and in another instance alert the user if they selected more than one COP 2830. Right now it notifies the user if they selected more than one class.

<script type="text/javascript" charset="utf-8">
var p = 0;
$(document).ready(function () {
    $('input:checkbox').click(function () {
        var COP1000 = $(this).attr('data');
        if ($('input:checkbox:is_checked').attr()) {
            p++;
        }
        if (p >= 2) {
            alert('You can only select this class once');
            return false;
        }
    });
});
</script>

Below are checkboxes with data being the name of the class

<input name="class[]" data="COP1000" value="<tr><td>COP1000 <td>8:00AM-9:00AM 
</td><td>MWF </td><td>Sanford </td><td>3</td></tr>" type="checkbox" class="auto-
style88"/>
<input name="class[]" data="COP1000" value="<tr><td>COP1000 <td>11:30AM-12:00PM
</td><td>TTH </td><td>Altamonte </td><td>3</td></tr>" type="checkbox" class="auto-
style88" />

<input name="class[]" data="COP2830" value="<tr><td>COP2830 <td>11:00AM-12:00PM 
</td><td>MWF </td><td>Sanford </td><td>3</td></tr>" type="checkbox" class="auto-
style88"/>
<input name="class[]" data="COP2830" value="<tr><td>COP2830 <td>6:00PM-8:45PM 
</td><td>T </td><td>Altamonte </td><td>3</td></tr>" type="checkbox" class="auto-
style88"/>

Upvotes: 0

Views: 169

Answers (2)

Frederiek
Frederiek

Reputation: 1613

This should work:

$(document).ready(function() {
    $('input:checkbox').click(function() {

        var COP1000Counter = 0;
        var COP2830Counter = 0;


        $('input:checkbox:checked').each(function(){
            if($(this).attr('data') == "COP1000")
            {
                COP1000Counter++;
            } else if ($(this).attr('data') == "COP2830"){
                COP2830Counter++;
            }
        });

        if (COP1000Counter > 1 || COP2830Counter > 1) {
            alert('You can only select this class once');
            return false;
        }
    });
});

By adding more counters or in the if other numbers you can play with all classes and the number of allowed occurences

Fiddle

Upvotes: 1

Drew
Drew

Reputation: 898

Here you go, check this fiddle out.

though I feel like my solution is rather crude and can still be improved. but it's a start.

hope it helps. :)

Upvotes: 0

Related Questions