ajaxform select2 объединяет несколько идентификаторов

У меня есть форма поиска select2 с ajaxform, которая объединяет новые записи формы в исходную форму поиска select2. Если добавляется более одной новой записи, новые текстовые значения правильно объединяются в поле поиска, однако любой новый скрытый идентификатор заменяет существующий. Кажется, что он добавлен, потому что все новые текстовые значения отображаются в поле поиска select2. Я думаю, проблема в том, что новый идентификатор должен быть связан со скрытым полем урожая в дополнение к текстовому полю, связанному с полем поиска. Я не знаю, как это сделать. Ваша помощь приветствуется.

<script>
$(document).ready(function() { 

$("#search").select2({
width: '60%',
allowClear: true,
minimumInputLength: 0
});

$('#btnSubmit').on('click', function() {

$.ajax({
    asynch : true,
    type : 'POST',
    dataType : 'json',
    url: '../cfc/stages.cfc?method=addstage&returnformat=json',
    //all form fields submitted to url
    data: $("form").serialize(),

    success : function(data, textStatus) {
        //close the modal
        $('#stagemodal').modal('hide');

        //set the returned data to a variable
        var fullname = $('#stagename').val();
        $("#cropstageid").val(data.DATA);

        //get current selection
        var selection = $(search).select2("data");
        //add a new item to the selection
        selection.push({id: data.DATA, text: fullname})
        //set the updated selection
        $(search).select2("data",selection);

        //reset form
        $('#addstageform')[0].reset();
        //output data to console
        console.log(data.DATA);

}
});
});

});
</script>


<cfform name="stageform" id="stageform" action="settings_form_action.cfm" method="post" ENCTYPE="multipart/form-data">

<h4 class="text-primary">Select Crop Stages</h4>
<input type="hidden" id="cropstageid" name="cropstageid">

<cfselect id="search" multiple name="cropstageid" >
<cfloop query="stages" >
<option value="#cropstageid#" >#stage#</option>
</cfloop>

</cfform>

*AjaxForm для новых записей

<cfform id="addstageform" name="addstageform" action="" method="post">
<input type="text" name="stagename" id="stagename" autofocus size="35">
<input type="button" id="btnSubmit" value="Add" /><
</cfform>

person Robin    schedule 22.02.2016    source источник


Ответы (1)


Благодаря помощи коллеги, решение ниже:

  1. в случае успеха мы больше не присоединяемся к скрытому полю, поэтому удалите $("#cropstageid").val(data.DATA);
  2. в случае успеха добавьте   $('#search').append('' + fullname + ''); эта строка добавляет еще один параметр выбора из недавно добавленной записи ajaxform
  3. больше не нужно скрытое значение, так как оно прикрепляется как опция выбора, поэтому удалите скрытое поле формы урожая внутри формы.

Очищенный скрипт ниже:

<script>
$(document).ready(function() { 

$("#search").select2({
width: '60%',
allowClear: true,
minimumInputLength: 0
});

$('#btnSubmit').on('click', function() {

$.ajax({
asynch : true,
type : 'POST',
dataType : 'json',
url: '../cfc/stages.cfc?method=addstage&returnformat=json',
//all form fields submitted to url
data: $("form").serialize(),

success : function(data, textStatus) {
//close the modal
$('#stagemodal').modal('hide');
//set the returned data to a variable
var fullname = $('#stagename').val();
//get current selection
var selection = $('#search').select2("data");
//add the new option to the select 
$('#search').append('<option value="' + data.DATA + '">' + fullname +    '</option>');
//add a new item to the selection array
selection.push({
id: data.DATA, 
text: fullname
});
//set the updated selection
$('#search').select2("data",selection);
//reset the modal form
$('#addstageform')[0].reset();
//output to the console
console.log(data.DATA);
}

});
});

});
</script>
person Robin    schedule 23.02.2016