2
votes

I have a SharePoint jquery form that I use in a CEWP and one of the elements on the form is a Multi Selecion element, which is a drop down list that allows for multiple selections. Ex:

 <select name="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
 </select>

The element needs to be pre-selected with data from a SharePoint list. I have a column called cars and the data is comma dilimited (ex: Saab,Audi).

So, using spservices and jquery, how do I pre-select the element with "Saab" and "Audi"? Here's what I have in jsFiddle: http://jsfiddle.net/rXGmc/ I then need to apply it to sharepoint. Thanks for any help or insight you can provide.

2

2 Answers

1
votes

So if I got it well, for Saab,Audi the output should be something like this:

<select name="cars" id="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab" selected="selected">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi" selected="selected">Audi</option>
</select>

Can't this be done server side?

If you want to do it client side, I'm not sure what type of data SharePoint returns, supposing "Saab,Audi" is a string, you can do something like this in JavaScript:

<script>
str = "Saab,Audi";
sel = str.split(",");
// Note I have added id="cars" in the HTML
options = document.getElementById("cars").getElementsByTagName("option");
for(var i in options)
    for(var j in sel)
        if(options[i].innerHTML == sel[j])
            options[i].selected="selected";
</script>
1
votes

Your fiddle didn't work because you didn't include jQuery (in the Frameworks & Extensions options on the left) and because your selector had some problems:

'select[name="cars"] option[value="saab"], select[name="Volvo"] option[value="audi"],option[value="benz"],'
//                              incorrect name here ----^^^^^       and a trailing comma ----------------^

The first part of your selector:

select[name="cars"] option[value="saab"]

...actually would select the "saab" option, but then the second part:

, select[name="Volvo"] option[value="audi"]

...is trying to select an option element that is a child of a select element with name="Volvo" and there is no select with that name. Then the third part:

, option[value="benz"],

...is trying to select an option with "benz" regardless of which select element it might belong to.

But the whole selector doesn't work because it has a trailing comma.

So fix those problems and it will work on "saab" and "audi":

'select[name="cars"] option[value="saab"], select[name="cars"]  option[value="audi"]'

Demo: http://jsfiddle.net/rXGmc/2/

Having said all that, a neater option is to use .find() or .children():

$('select[name="cars"]').children('[value="saab"],[value="audi"]')
                        .attr('selected', 'selected');

Demo: http://jsfiddle.net/rXGmc/4/