Append options to select2 - javascript

I have the following select:
<select id="street" name="client[street_id]" class="form-control select2" data-placeholder="Select or Insert The Street" style="width: 100%;">
#foreach($streets as $street)
<option value="{{ $street->id }}">{{ $street->name }}</option>
#endforeach
</select>
And the initialisation:
$(".select2").select2({tags: true});
Note that multiple has not been set to true. The problem is when I enter a new option (tag), first time will add the tag but second time will replace the first one in the list. So how can I add options in the select and keep them? (on each add I will make a request to server to save to db).
https://jsfiddle.net/8c7ujd4g/

I found this solution:
$('.select2').on("select2:select", function(e) {
// what you would like to happen
if(e.params.data.isNew){
$(this).find('[data-select2-tag="true"]').replaceWith($('<option selected>', { value : e.params.data.id })
.text(e.params.data.text));
$.ajax({
// ...
});
}
});
$(".select2").select2({tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
isNew: true // add additional parameters
}
}
});

Related

Get selected item value from select2 dynamically created item in code behind

I'm using bootstrap select2 control with dynamic item creation
function pageLoad(sender, args) {
$('select').select2({
tags: true
});
$("#btn-add-state").on("click", function() {
var newStateVal = $("#new-state").val();
// Set the value, creating a new option if necessary
if ($('select').find("option[value='" + newStateVal + "']").length) {
$('select').val(newStateVal).trigger("change");
} else {
// Create the DOM option that is pre-selected by default
var newState = new Option(newStateVal, newStateVal, true, true);
// Append it to the select
$('select').append(newState).trigger('change');
}
});
}
I tried this get value but it always returns null!
cmd.Parameters.AddWithValue("#company", txt_car_company.Value);
I also tried to set the value in an ASP hidden field but it also returned null
<select id="txt_car_company" runat="server" class="select-single select2-hidden-accessible" data-live-search="true" data-select2-id="txt_car_company" aria-hidden="true" required="required">
<option value="Audi">Audi</option>
</select>
<asp:HiddenField ID="hcarcompany" runat="server" />
<script>
$('#txt_car_company').on('change', function () {
$('#<%=hcarcompany.ClientID%>').val($(this).val());
}
</script>

How to show selected value using javascript in laravel

i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful

How can I disable an entire select dropdown field after selecting an option through Typescript and HTML?

What I'm trying to do: If an option is selected in this certain select dropdown, I would like for the entire select dropdown to be disabled.
I'm using Typescript and I'm pretty brand new to it, so I would like to get some insight on how to go about this.
My code currently looks like this:
<button class="button default link small">
<input
:id="`item-${index}`"
:name="`item-${index}`"
type="checkbox"
v-model="filteredItems[index].Enabled"
#change="formUpdated('', index)"
>
<label :for="`status-${index}`">Enabled</label>
</button>
<label class="bold">Item Type</label>
<select required
v-model="item.Type"
:disabled="isDisabled(item)"
#change="changeItemType('', index)"
#keydown.enter="$event.stopPropagation()"
>
<option disabled value="" hidden>Select Item Type</option>
<option v-for="(value, name) in supportedItems()" :key=value :value=value>{{ name }}</option>
<script lang="ts">
private formUpdated(name: string, index: number): void {
this.$set(this.formChanged, index, name);
}
private changeItemType(name: string, index: number): void {
this.$set(this.formChanged, index, name);
const itemType = this.items[index].Type;
if (itemType === '') {
this.items[index] = API.StoreInventory.Category.blank();
} else if (itemType === 'item_1') {
this.items[index] = API.StoreInventory.Category.blankItem1();
} else if (itemType === 'item_2') {
this.items[index] = API.StoreInventory.Category.blankItem2();
} else if (itemType === 'item_3') {
this.items[index] = API.StoreInventory.Category.blankItem3();
} else {
throw new Error('Item type not found');
}
}
private isDisabled(item: ItemCategory<AllItemTypes>): boolean {
return !item.Enabled;
}
</script>
Note that this is only one field, there are other fields that do not require permanent disabling once an option is selected. There is a button that disables and enables those other fields
So far, I've tried doing
<label class="bold">Item Type</label>
<select required
v-model="item.Type"
:disabled="!value"
#change="changeItemType('', index)"
#keydown.enter="$event.stopPropagation()"
>
<option disabled value="" hidden>Select Item Type</option>
<option v-for="(value, name) in supportedItems()" :key=value :value=value>{{ name }}</option>
but it disables the entire dropdown before I can select an option. I would like to be able to select an option before it disables the entire dropdown.
I've also tried adding
(document.getElementById('item.type') as HTMLInputElement).disabled = true;
to the changeItemType method, but since it's attached to the changeItemType callback, when I refresh the window, the item becomes enabled after being disabled.
Any idea how I would go about in doing this?
You could bind disabled to a flag that is set in the change-event callback:
<template>
<select :disabled="isDisabled"
#change="changeItemType('', index)">
...
</select>
</template>
<script>
export default {
data() {
return {
isDisabled: false,
}
},
methods: {
changeItemType(type, index) {
//...
this.isDisabled = true
},
},
}
</script>
demo

Get id and a field value in EasyAutocomplete plugin

Using easyAutocomplete plugin, I autocomplete an input field and take the selected value and display them on a dropdown .
What I want to do, is have a hidden field that would have the id of the value.
My JSON File returns something like this :
{ "name": "Emily"
"id" : 1
"jobData": [
{
"id":1
"loc":"AL"
},
{
"id":2
"loc":"BG"
}
]
Once I select Emily from my users, my dropdown gets filled with Locations of her job.
How do I also save the Id of the location in a hidden field so that I can send it to my controller?
This is my JS function:
function AutoCompleteS() {
$("#basics").keyup(function(e) {
this.query = e.target.value;
var options = {
url: function(query) {
return "/getUser/"+ query
},
getValue:"name"
list: {
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
function toArray(value){
return value.loc;
}
var allLocations=value.jobData.map(toArray);
$.each(allLocations,function(i,p){
$('#select').append($('<option></option>').val(p).html(p));
})
}
}
};
$('#basics').easyAutocomplete(options);
});
}
How do I get and pass the id ?
EDIT:
html code:
<label for="client1" class=" control-label">First Client</label> <input type="text" name="client" value="" class="form-control input-lg " id="basics"/>
<label for="sel1">Select location:</label>
<select class="form-control input-lg" id="select" >
<option></option>
<input type="text" class="hidden" />
</select>
easyAutocomplete issues:
Your code should be more like this (see remote data source example) - i.e. you should only call easyAutocomplete once:
$("#basics").easyAutocomplete({
url: function(query) {
return "/getUser/" + query;
},
getValue: "name",
list: {
// ...
}
});
HTML issues:
Move the input outside the select, and give them both names (so the values can be submitted to server):
<select class="form-control input-lg" id="select" name="location">
<option></option>
</select>
<input type="text" class="hidden" name="job-id" id="job-id">
To set the value of the hidden field when the select value changes, you need a change handler:
function updateSelect(jobData) {
// Reset options:
$("#select")
.empty()
.append(new Option());
// Add locations:
jobData.forEach(function(job) {
$("#select").append(new Option(job.loc));
});
// Handle dropdown change:
$("#select")
.off("change")
.on("change", function() {
// Reset job id (needed when user selects blank option at top of dropdown)
$("#job-id").val("");
var selectedLocation = this.value;
jobData.forEach(function(job) {
if (job.loc === selectedLocation) {
// Copy job id to hidden field:
$("#job-id").val(job.id);
}
});
});
}
Call updateSelect from your easyAutocomplete onClickEvent handler:
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
updateSelect(value.jobData);
}

Populate dropdown list dynamically in AngularJS

I'm trying to generate dynamic form based on the key of document fields and using ng-if attribute in AngularJS.
Ex:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
Following is the code:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
controller:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields are working fine and populating data but I'm facing issue while populating dropdown fields.
Example: I've two dropdown fields in my mongodb document i.e. city|select and state|select
I'm trying to use ng-options to call function by passing index and colName (document name) to populate dropdownlist but its not working.
Following is the code:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
Express:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
Initially I tried calling function in ng-repeat but it was going into infine loop. Then later I tried ng-init options but it only calls or initialize once which is not working in my case. Here I need to call function dynamically and based on that I want to populate dropdown for different fields.
Any help would be appreciated.
Your view is completely messed up as far I see it you are missing
ng-model
for your select input.
Your JSON is improper its missing , before {'id_':'Arizona'}
Try to get response in your controller and push it to array and make use of that array in your View :
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
var returnArray = [];
alert(JSON.stringify(response));
angular.ForEach(response,function(option){
//parse response and push it to returnArray
returnArray.push(option);
});
return returnArray;
});
}
View :
<div class="form-group">
<select class="form-control" ng-model="selection" ng-options="dropdown._id for dropdown in getDropDownData()">
<option value="">Select</option>
</select>
</div>
Here is the link to Codepen
.
Consider the following solution:
In your controller, set up a variable for the dropdown data:
$scope.dropdownData = {};
Then change your getDropdownData function to:
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
alert(JSON.stringify(response));
$scope.dropdownData[colName] = response; // This will put data into our html file
});
}
And the HTML for your dropdown case should be:
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
I used the notorious ngInit to make the call from getting data for the server. Perhaps there's a better way that I didn't consider. But in any case, the idea is to make the call to the server, and save the data in a way that you can fetch it easily from the view.
Edit
I don't know why, but for some reason this solution doesn't work with ng-options. It does, however, work when using it like this:
<select class="form-control" ng-init="getDropdownData(index,colName)">
<option value="">Select</option>
<option ng-repeat="dropdown in dropdownData[colName]" value="dropdown._id">{{dropdown._id}}</option>
</select>
See a simple example here.
Finally I solved it myself. Thanks #Rishab777 and #yarons for guiding me.
Here's the view code:
<div ng-if="mySplit(index, 1) == 'select'">
<select class="form-control">
<option value="">Select</option>
<option ng-model="providerModelData[index]" ng-selected="providerModelData[index]" ng-repeat="dropdown in dropdownData[index]" value="{{dropdown._id}}">{{dropdown._id}}</option>
</select>
</div>
and controller:
$scope.showModal = false;
$scope.toggleModal = function (colId, colName) {
$http.get('/collectiondata/' + colId + '/collectionName/' + colName).success(function (response) {
$scope.colName = colName;
$scope.colId = colId;
for (var key in response) {
if (response.hasOwnProperty(key)) {
if ($scope.mySplit(key, 1) === 'select') {
$scope.getDropdownData(key, colName);
}
}
}
$scope.providerModelData = response;
$scope.showModal = !$scope.showModal;
});
};
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[query] = response;
});
};
Now the issue is ng-selected="providerModelData[index]" is not working and its showing last item as selected only.

Categories