2016-02-22 2 views
0

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

<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> 

ответ

0

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

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

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

<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>