shruthi shruthi - 7 months ago 14
Javascript Question

How to push the values with open brace and close brace

My answer shows like 1,2,3,1,2,1,4,5 (without open and close tag)

but i want to show like this model [1,2,3][1,2][1,4,5]

want with open close tag, because want to seperate the option values to store in database.

my script

var foo = [];
$('.box22').each(function(x,v){
var temp =[]
$(v).find("select[name='category[]'] > option:selected").each(function(i, selected){
temp.push($(selected).val(),[]);
});
foo.push(temp);
alert(foo);
});


my view file code

<?php for($i=0; $i<4; $i++) { ?>
<div class="box22">
<div class="mcm">
<input type="text" placeholder="Myself" id="coworkers" name="coworkers[]" />
<span class="bar"></span>
</div>
<div class="select2">
<select id="category_<?php echo $i; ?>" name="category[]" class="chosen-select ref-sel1" multiple >
<?php
foreach($genre as $gen){
echo '<option value='.$gen->genre_id.'>'.$gen->genre_name.'</option>';
}
?>
</select>
</div>
</div>
<?php } ?>

Answer

Try the following

var foo = [];
  $('.box22').each(function(x, v) {
    var temp = []
    $(v).find("select[name='category[]'] > option:selected").each(function(i, selected) {
      temp.push($(selected).val());
    });
    text = '[' + temp.join(',') + ']'
    foo.push(text);

  });
  alert(foo.join(''));

demo here

Comments