Home > Enterprise >  Dynamique Select box Laravel
Dynamique Select box Laravel

Time:10-29

the data displayed and removed instantly

im trying to create a dynamique select box with laravel , get the data from database and then select one to get the data related to it by id . i made those methode :

Jquery

@section('scripts')
<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('change','.state_id',function(){
            var state_id=$(this).val();
            var div=$(this).parent();
            var op="";
            $.ajax({
                type:'get',
                url:'{!!URL::to('finddelegName')!!}',
                data:{'id':state_id},
                success:function(data){
                    console.log('success');
                    console.log(data);
                    console.log(data.length);
                    op ='<option value="0" selected disabled>chose delegation</option>';
                    for(var i=0;i<data.length;i  ){
                        op ='<option value="' data[i].id '">' data[i].name_ar '</option>';
                    }
                    div.find('.name_fr').html("delegation_id");
                    div.find('.name_fr').append(op);
                },
                error:function(){
                }
            });
        });
});
</script>
@endsection

Controller

    public function finddelegName(Request $request){
        $data=Delegation::where('state_id',$request->id)->take(100)->get();
        return response()->json($data);
    }


when i select one from the box ( like the photo ) it console to me the data and then removed select data from Select box consol my data how can i fix it ? Thanx

CodePudding user response:

I believe your delegation field should be dropdown. So, you suppose to have this as the field:

 <select  id="delegation_id" ></select>

Then, you will able to inject your ajax response into it:

$(document).ready(function(){
        $(document).on('change','.state_id',function(){
            var state_id=$(this).val();
            var div=$(this).parent();
            var op="";
            $.ajax({
                type:'get',
                url:'{!!URL::to('finddelegName')!!}',
                data:{'id':state_id},
                success:function(data){
                    console.log('success');
                    console.log(data);
                    $("#delegation_id").empty();
                    $("#delegation_id").append("<option value=''> Select Delegation</option>");
                    $.each(data, function(i, item){
                       $("#delegation_id").append("<option value='"   
                       data[i].delegation_id   "'>"   data[i].delegation_value   " 
                       </option>");
                    });                   
                },
                error:function(){
                }
            });
        });
});
  • Related