0

I have some divs that have a class modal- and a state name so it they look like this class="modal-Texas hide". And in the array for Texas it is like this "US-TX": {"location": "Texas"}.

I am trying to find all divs first with the modal- class and split just the state name out and then match up to the array location name and then build a new array with only the "US-TX" or others that matched based on location.

Full code can be found here

http://jsfiddle.net/abennington/ymgkkuzL/225/

Then once i have the new array would like to use that new array like so

onRegionOver: function (event, code) {
        if (stateHTML[code]) {
            $('#jvectormap1_' + code).css('cursor', 'pointer');
        } else if (code) { //if a state is not specified in var stateRedirects then prevent default
            event.preventDefault();
        }
    },

But the stateHTML[code] would be the NEWARRAY[code]

EDIT:

My modal HTML is structured like:

<div class="modal-California hide">
    <div class="modal-content">
        <div class="col-md-6">
            <img alt="" src="healthplanalliance.org/assnfe/images/Adventist.jpg"; />
            <br>
            <strong>
                <a href="/assnfe/cv.asp?ID=">Adventist Health Plan</a>
            </strong>
            <br> Roseville, California United States of America
            <br> Telephone: 
            <br> Local Time : 
        </div>
    </div>
</div>
War10ck
  • 12,387
  • 7
  • 41
  • 54
Aaron
  • 525
  • 2
  • 9
  • 22
  • @ojovirtual has the first part of finding divs and splitting and removing duplicates. Now need to take the vales and match to the stateHTML array location value and then make the new array use the index or "US-TX" – Aaron Sep 23 '15 at 16:50
  • I've posted a complete solution below. Let me know if it works for you. – War10ck Sep 23 '15 at 17:03

2 Answers2

1

I think this should get you what you want:

var classes = $.unique(
    $.map(
        $('div[class^="modal-"]')
            .filter(function (idx) {
                return !$(this).hasClass('modal-conent');
            }),
        function (val, idx) {
            return $(val).attr('class').match(/modal-([\w\s]+) hide/)[1]; 
        })
    );

console.log(classes);

var newArray = {};

for(var a in classes) {
    for(var b in stateHTML) {
        if(stateHTML.hasOwnProperty(b)) {
            if(stateHTML[b].location.toLowerCase() === classes[a].toLowerCase()) {
                newArray[b] = stateHTML[b];    
            }
        }
    }   
}

console.log(newArray);

Regex Credit: ojovirtual

This was a complex question that involved multiple parts. In the first block, the code is using the jQuery begins with attribute selector [attribute^="value"] to select the elements with a class of modal-. From here, it uses a combination of .filter() to remove the modal-conent matches and .map() to pull the state names into an array. Finally, $.unique is called to remove the duplicates from the array. At this point, we can verify in the console that classes contains:

[
    "Texas",
    "California",
    "New Mexico",
    "New York"
]

Next, the code uses a double for loop to loop through the classes array and match the location to any matching location property within an object in the stateHTML object. stateHTML.hasOwnProperty(b) is used to verify that the property is unique to the object and not based off the constructor, thereby eliminating the check of __proto__ and other such properties that don't apply. Both the stateHTML[b].location value and the classes[a] value are lowercased as an extra precaution to ensure the strings matched without case sensitivity. Finally, the property is added to the new object and the value copied from stateHTML[a].

The final result as echoed to the console is:

{
    US-CA: {
        location: "California"
    },
    US-NM: {
        location: "New Mexico"
    },
    US-NY: {
        location: "New York"
    }
}

Note: The absence of the US-TX object in your final output is due to the fact that the US-TX object is commented out in the stateHTML object.

Demo: JSFiddle.

EDIT:

There appears to be an error with the regex when you ported the fiddle to your actual code. I've updated the first part to check for a regex match before continuing. This should hopefully eliminate the error:

var classes = $.unique(
    $.map(
        $('div[class^="modal-"]')
            .filter(function (idx) {
                return !$(this).hasClass('modal-conent');
            }),
        function (val, idx) {
            var matches = $(val).attr('class').match(/modal-([\w\s]+) hide/);
            if(matches && matches.length === 2) {
                return matches[1];
            } 
        })
    );

In the previous example, the code was assuming you would always have a match. In this example, the value is only mapped to the new array if the value matches. If an error occurs or no match is found, the value is skipped.

Community
  • 1
  • 1
War10ck
  • 12,387
  • 7
  • 41
  • 54
  • You ABSOLUTELY ROCK!!! This so awesome!!!! I can't thank you enough!!!! I can now also use your newArray to color only states that have an modal popup. So AWESOME! http://jsfiddle.net/abennington/ymgkkuzL/237/ – Aaron Sep 23 '15 at 17:11
  • @Aaron Glad it worked :) That was a tricky one for sure. Good luck and happy coding! – War10ck Sep 23 '15 at 17:13
  • Any reason you can think of that when i add to my site with other javascript i would get the error Uncaught TypeError: Cannot read property '1' of null from this line return $(val).attr('class').match(/modal-([\w\s]+) hide/)[1]; – Aaron Sep 23 '15 at 17:38
  • Hmm, it looks like the filter is failing to return the expected DOM objects. I noticed that the class `modal-conent` appears to be mispelled in your fiddle. Was that intentional? If that HTML is not an exact match to what's in the JSFiddle, we may need to alter that `.filter` function to target the correct class. – War10ck Sep 23 '15 at 17:40
  • oops did not see that. Let me try and change that to the correct spelling and make sure modal is set to that too. One sec :) – Aaron Sep 23 '15 at 17:44
  • @Aaron No worries. If you correct the spelling in the HTML, you'll need to modify the `.filter` function to target `modal-content` instead of `modal-conent` as well. – War10ck Sep 23 '15 at 17:45
  • ok did that but still get same error. My modal divs look like this – Aaron Sep 23 '15 at 17:50
  • @Aaron I've edited your HTML update into your original question. Let me give this a glance and see if I see anything off hand that may be causing an issue. – War10ck Sep 23 '15 at 17:54
  • @Aaron Edited my answer to provide a work around when no match is found. Not sure if this will do everything you want but it will prevent the error from occuring for sure. – War10ck Sep 23 '15 at 18:00
  • Awesome! Let me try it :) – Aaron Sep 23 '15 at 18:03
  • WORKS!!!! You are too AWESOME!!! You have gone above and beyond in helping me!!! Can't say thank you enough my friend!!!! :) – Aaron Sep 23 '15 at 18:08
0

You can iterate over all the elements whose class starts with modal- and use regular expressions to get the desired data:

var states=[];
$("div[class^=modal]").each(function(){
    if (state = $(this).attr("class").match(/modal\-([\w\s]+) hide/))        
    {
        states.push(state[1]);
    }
});
states=$.unique(states); //remove duplicates
ojovirtual
  • 3,332
  • 16
  • 21
  • Be mindful that [`$.unique()`](https://api.jquery.com/jQuery.unique/) was designed for collections of DOM elements, not general strings. See [this answer](http://stackoverflow.com/questions/10191941/jquery-unique-on-an-array-of-strings#answer-10192052) for more details. – War10ck Sep 23 '15 at 16:09
  • Awesome...so does this new array have only the "US-TX" index that matches up with the state name location:Texas from the class in the original array? I need an new array that is the matching index of the class name that matches the location value. – Aaron Sep 23 '15 at 16:13
  • just updated demo here and logged to console and looks like to you have the div part down AWESOME! The console shows me ["Texas", "California", "New Mexico", "New York"] which are the divs names. Now just need to match those with the location in the existing stateHTML array and make the new array using the index of the matching ones. So it would make the new array with the matching "US-TX". – Aaron Sep 23 '15 at 16:22
  • Any ideas on this? :) – Aaron Sep 23 '15 at 16:48