JQuery - IF IN String or Array Condition

Using JQuery, I loop through the named attribute tags

in each <option>

dropdown <select>

below.

You will see that I LOVE to have 2 of the preselected options if the number 6 exists in the attribute tags

.

<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 help here. Is there a better way to do this?
In PHP, I usually use the in_array () function, but the javascript seems to be more picky.

+3


source to share


2 answers


jQuery has a function inArray()

:

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

      

Edit



A refactored version of the OP's code that fetches 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/

+4


source


How about splitting it into ,

and checking it?



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

      

+1


source







All Articles