WebDevGuy2 WebDevGuy2 - 1 year ago 85
HTML Question

Can't access attr while looping thru controls of particular class

Working on MVC 5 website. I have a particular row that, which a button is clicked, the row, with all its controls is cloned. Here's the master row that is cloned...

<div class="row filter_row">
<div class="col-lg-12">
<div class="checkbox i-checks">
<input type="checkbox" value="">
<select data-placeholder="Choose..." class="xchosen-select">
<option value="">First Name</option>
<option value="">Last Name</option>
<option value="">Account</option>
<input type="text" placeholder="" class="form-control">
<select style="width: 50px; height: 35px;">
<option value="">And</option>
<option value="">Or</option>
<select class="grouping" style="width: 40px; height: 35px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>

The adding/cloning of the row div works great. Now, what I want to do is this. When I select a NEW item in the dropdowns with class "grouping" then compare it to the PREVIOUS "grouping" dropdown. If they are equal then make the background-color of the div a different "alternating" color. (Basically the purpose of this is that this is an advanced data filtering modal and I want to color code the groups. So, if the first 2 dropdowns are group 1 the background is white, group 2 is an alternating color, group 3 is white, etc... Just to aesthetically help the user see his "groups" of rows. Hope this makes sense.)

The PROBLEM is that I can't seem to access the class or id attributes, etc... As test code I wrote this:

$(".grouping").change(function() {
// loop thru all selecting dropdowns
$("select option:selected").each(function () {
alert($(this).attr('id') + '>>>' + $(this).text());
if ($(this).hasClass('grouping')) {
// do the comparison, blah blah blah
} else {
// for debug
alert('class: ' + $(this).attr('class'));

The issue is attr('id') and attr('class') show up undefined. What could I be doing wrong? I believe I"m trying to access these properties correctly?

Secondly, for the main loop, of course, it's looping thru all dropdowns that are selected. I'd like it to only loop thru those with 'grouping' class. Is there a more efficient way to accomplish this? Thanks!

Answer Source

You are looping over all selected option fields.

You need to loop over the select elements.

So, I think you just need to change this line:

$("select option:selected").each(function () {

To this:

$("select").each(function () {

Hope it can helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download