Search code examples
jqueryarraysjquery-selectbox

Rewrite select option value to exclude specific array segments


This pertains to my question yesterday, which was answered perfectly here by @iambriansreed.

In trying to take it one step further, my brain short-circuited. Plus, the jquery api site is down.

I have two select boxes; certain options in the second are removed based on the selection of the first. Option values of each select box are arrays.

What I need to do now is CHANGE the value of the second selectbox so that any array segment that doesn't match the first is removed. I've been on it all day and it's twisted my head. So, in this fiddle, if "Chamber Music" is selected in #selectbox1, the value of #selectbox2's option Chamber Music 5 should change to

<option value="620069,1547340">Chamber Music 5</option>, 

since the other value (328874) wasn't a match in the original array. Possible? Clunky? I'm already comparing arrays, so already getting non-matches.


Solution

  • I'm not quite sure I understand the question, specifically the "the value of #selectbox2's option Chamber Music 5 should change to Chamber Music 5" part. What I assume is that you want to change the value of the option in the second select box, depending on the selected values in the first select box.

    Something like this would work: http://jsfiddle.net/3VfU4/3/

    // check each value
    var values = this.value.split(',');
    var new_values = [];
    var result = true;
    
    for(i in values) {
        if($.inArray(values[i], selected) > -1) {
            result = false;
            new_values.push(values[i]);
        }
    }
    
    this.value = new_values.join(',');
    
    return result;