3

With Jquery, I'm looping through the attribute named tags, in each <option> of the <select> dropdown below.

You'll see I would LOVE to have 2 of the options preselected, if the number 6 exists in the tags attribute.

<select name="someFun" id="someFun"  multiple="multiple">
  <option value="1" tags="4,6,7">something</option>
  <option value="44" tags="2">something</option>
  <option value="61" tags="1,3,6">something</option>
  <option value="44" tags="2">something</option>
</select>

<script language="javascript" type="text/javascript">
$(document).ready(function(){

  var preselectedtag = '6'; // auto select any with 6

  $("#someFun > option").each(function() {
     var tag = $(this).attr("tags");

     /* change attr of this option to "selected" if 6 exists in var tag */

  });

});
</script>

I could use some help here. Is there a best way to do this?
In PHP I normally use an in_array() function, but javascript seems way more picky.

2 Answers 2

4

jQuery has an inArray() function:

var tags = $(this).attr("tags").split(",");
if ($.inArray(preselectedtag, tags) > -1) {
  alert("Tag " + preselectedtag + " detected!");
}

Edit

Refactored version of OP's code that selects the detected option tags:

$(function(){
  var preselectedtag = '6',
      selected = [];
  $("#someFun > option").each(function() {
    var n = $(this), 
        tags = n.attr("tags").split(",");
    if ($.inArray(preselectedtag, tags) > -1) {
      selected.push(n.val());
    }
  });
  $('#someFun').val(selected);
});

http://jsfiddle.net/zFBVT/

Sign up to request clarification or add additional context in comments.

2 Comments

+1 You could add $(this).attr('selected', 'selected') to select the options.
$(this).attr('selected', 'selected') appears to not work. Or it's selected everything. How do I select that single option, while iterating through all of them?
1

What about splitting it by , and checking?

var tags = tag.split(",")
if(tags.indexOf("6")!==-1){
    //do whatever manipulation you desire
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.