Constantine_92's avatar

ajax jquery when i click addnewfield dependent dropdown not working . not data coming or changing

//here my blade

	<div >
            <label for="field" class="font-weight-bold">Διάλεξε Ειδικοτητα και κατηγορια μελετητων </label>
            <div  id="dynamic-field-1" class="form-group row dynamic-field" >
                <div class="col-sm-4">
                    <select class="form-control" type="text" id="category" name="specialities[]" />
                    <option value="" selected disabled hidden>Choose here</option>
                        @foreach($specialities as $id => $speciality)
                        <option value="{{ $id }}" {{ in_array($id, old('specialities', [])) ? 'selected' : '' }}>{{ $speciality }}</option>
                        @endforeach
                    </select>
                    @if($errors->has('specialities'))
                        <div class="invalid-feedback">
                            {{ $errors->first('specialities') }}
                        </div>
                    @endif
                    <span class="help-block">{{ trans('cruds.experience.fields.specialities_helper') }}</span>
                </div>  
                <div class="col-sm-8">
                    <select class="form-control select2" type="text" name="surveys[]" id="survey" multiple></select>
                </div>
                
            </div>
        </div>

// here my script

		<script>
	$(document).ready(function() {
	var buttonAdd = $("#add-button");
 var buttonRemove = $("#remove-button");
var className = ".dynamic-field";
var count = 0;
var field = "";
var maxFields = 3;
var surveyList = [];



$('#category').on('change', function() {
   var categoryID = $(this).val();
   if(categoryID) {
       $.ajax({
           url: '/admin/getExpirience/'+categoryID,
           type: "GET",
           data : {"_token":"{{ csrf_token() }}"},
           dataType: "json",
           success:function(data)
           {
            console.log(data);
             if(data){
                $('#survey').empty();
                $('#survey').append('<option hidden>Κατηγορία Μελετών</option>'); 
                $.each(data, function(key, survey){
                    console.log ($('select[name="surveys[]"]').append('<option value="'+ survey.specialties +'">' + survey.name + '</option>'));
                   
                });
            }else{
                $('#survey').empty();
            }
         }
       });
   }else{
     $('#survey').empty();
   }
});





function totalFields() {
  return $(className).length;
}

function addNewField() {
  count = totalFields() + 1;
  field = $("#dynamic-field-1").clone();
  field.attr("id", "dynamic-field-" + count);
  field.children("label").text("Field " + count);
  field.find("#survey").val("");
  field.attr("id", "dynamic-field-" + count);
  $(className + ":last").after($(field));
}

function removeLastField() {
  if (totalFields() > 1) {
    $(className + ":last").remove();
  }
}

function enableButtonRemove() {
  if (totalFields() === 2) {
    buttonRemove.removeAttr("disabled");
    buttonRemove.addClass("shadow-sm");
  }
}

function disableButtonRemove() {
  if (totalFields() === 1) {
    buttonRemove.attr("disabled", "disabled");
    buttonRemove.removeClass("shadow-sm");
  }
}

function disableButtonAdd() {
  if (totalFields() === maxFields) {
    buttonAdd.attr("disabled", "disabled");
    buttonAdd.removeClass("shadow-sm");
  }
}

function enableButtonAdd() {
  if (totalFields() === (maxFields - 1)) {
    buttonAdd.removeAttr("disabled");
    buttonAdd.addClass("shadow-sm");
  }
}

buttonAdd.click(function() {
  addNewField();
  enableButtonRemove();
  disableButtonAdd();
});

buttonRemove.click(function() {
  removeLastField();
  disableButtonRemove();
  enableButtonAdd();
});

});

//and my route

	Route::get('getExpirience/{id}', function ($id) {
    $survey = App\Models\Survey::where('specialties', $id)->distinct()->get();
    return response()->json($survey);
});
0 likes
11 replies
Sinnbeck's avatar

How isn't it working? It adds a field and after that the select field stops working ? Please spread at least 30 seconds explaining what happens

Constantine_92's avatar

@Sinnbeck no at the first row work correctly , when i select category then give me surveys that belong at this category . When i click addNewField() to select another category ,categories came but when i pic it no data comes, and one more think the surveys keep the old values.

Sinnbeck's avatar

@Constantine_92 if I understand your code correctly, you have two selects. But the problem is that they have the same ID, which means that jquery cannot figure it out. Try using a class instead of an ID. Same with #survey. Give them unique ids or similar to populate the correct one

BTW. You don't need csrf for a get route

Sinnbeck's avatar

@Constantine_92 I suggest reading up on some basic html

<select class="form-control" type="text" id="category" name="specialities[]" > //removed / that should not be there

In this html you have an ID. But when you clone this whole segment, you get duplicate ids. Check the rendered html after adding a "field"

1 like
Constantine_92's avatar

@Sinnbeck https://imgur.com/oomAS8k

i know that duplicate ids . I try when i click add change the category id and the survey id and i make the same fuction for this ids but again not working

if i removed ids as you told me then from where I will catch this function $('#category').on('change', function()

Sinnbeck's avatar

@Constantine_92 exactly. So use classes here instead. And find a way to find the correct survey id to update. The category could perhaps get a data-id="1" etc to make it easy to find the correct one

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Constantine_92 well a small example. When you add a new field. Imagine that category is a class

field = $("#dynamic-field-1").clone();
  field.attr("id", "dynamic-field-" + count);
category = field.find('.category');
category.attr("data-id", count);
survey = field.find('.survey');
survey.attr("id", "survey" + count);

Now they are easier to find and use

$('.category').on('change', function() {
   var categoryID = $(this).val();
    var id = $(this).data('id'); //now you can find the correct survey id 

Please or to participate in this conversation.