<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('click','.add_brand',function(){
            $('.error').html('');
            $("#brandModal").modal('show');
            $(".brand_edit_id").val('');
            $(".brand_edit_name").val('');
            $(".save_btn").html('Save');
            $(".Add_edit_brand").html('New');
        })
        $(document).on('keyup', function(e) {
        if (e.key === 'Enter') {
            $('#brand_form').submit();
        }
        });
        $(document).on('submit', "#brand_form", function(e) {
            e.preventDefault();
            var name = $("#brand_form #name").val();
            var _id = $("#brand_form .brand_edit_id").val();
            $('.save_btn').prop('disabled', true);
            var postType = "POST";
            var post_url = "{{ route('brand.store') }}"
            if(_id){
            var post_url = "{{ route('brand.update',['brand'=> ':brandId']) }}";
            post_url = post_url.replace(':brandId', _id);
            var postType = "PUT";
            }
            $.ajax({
                type: postType,
                url: post_url,
                data: {
                    name: name,
                    id: _id,
                },
                success: function(data) {
                    $('.save_btn').prop('disabled', false);
                    if ($.isEmptyObject(data.error)) {
                        $("#brandModal").modal('hide');
                        if($("#brandList").length > 0){
                            var brandVal = $("#brandList").val();
                            $("#brandList").empty();
                            $("#brandList").append('<option value="" disabled selected>Select Brand</option>');
                            $.each(data.brandList, function (key, value) {
                                var selected = brandVal == value.id ? 'selected' : '';
                                $("#brandList").append('<option value="' + value.id + '" ' + selected + '>' + value.name + '</option>');
                            });
                        }else{
                            $('#brand-table').DataTable().ajax.reload();
                            var alertType = "{{ trans('quickadmin.alert-type.success') }}";
                            var message = data.success;
                            var title = "Brand";
                            showToaster(title,alertType,message);   
                        }
                    } else {
                        printErrorMsg(data.error);
                    }
                }
            });
        });
        function printErrorMsg(msg) {
            $.each(msg, function(key, value) {
                $(`#brand_form .error_${key}`).html(value);
            });
        }
    });
</script>