Laravel array collect loop in jquery each

I want to add select tag to my code using jquery and it needs values ​​from laravel array collection

controller

$array['skills'] = DB::table('skills')->get();

      

Script

 <script type="text/javascript">
    var skill_count=$('#skill_count').val();
    var array = {!!$array['skills']!!};

    $("#add-skill").click(function(){
        skill_count++;            
        var skill='<div class="row skill"><div class="col-sm-4"><label for="name">Skill:</label><select name="skill['+skill_count+'][skill_name]" class="form-control">$.each( array, function( i, val ) {<option value="+ val.id +"> val.skill_name </option>})</select></div><div class="col-sm-4"><label for="name">Experience:</label><select name="skill['+skill_count+'][pivot][experience_year]"   class="form-control">for(i=1;i<=30;i++){<option value="+ i +">i</option>}</select><select name="skill['+skill_count+'][pivot][experience_month]"   class="form-control">for(i=1;i<=12;i++){<option value="+i+">i</option>}</select></div><div class="col-md-12"><a class="skill-remove pull-right">- Remove Skill</a></div></div>'
        $(".show-skill").before(skill);
    });
</script>

      

but in the browser val.id and val.skill_name are not getting values.

console.log (val.skill_name); giving me values

+3


source to share


2 answers


Hope this helps



var array =  [{
    id: 2,
    skill_name: 'abc'
}, {
    id: 3,
    skill_name: 'xyz'
}];

var options;
$.each( array, function( key, value ) {
console.log(value.skill_name);
  options = options + '<option value="'+value.id+'">'+value.skill_name+'</option>';
});


var skillhtml = '<div><label for="name">Skill:</label><select name="skillname">'+options+'</select></div>';

$("#container").html(skillhtml);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="container">
</div>
      

Run code


jsfiddle: https://jsfiddle.net/j5nkLabw/

+2


source


Since you need echo php array, use json_encode before doing this

var array = {!!json_encode($array['skills'])!!};

or is it better to code it in the controller,



$jsonArray = json_encode($array['skills']);

      

and after that use it in your script var array = {!! $jsonArray!!}

+1


source







All Articles