The scenario is, I need to set the value of the dropdown (ng-select2) when a user presses on edit button present on the page. I am using ajax to fetch the options. The code is in angular.
I took reference from : https://github.com/tealpartners/ng-select2
<div class="form-div">
<label for="uploader">Select Uploader<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="uploader" id="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
<div class="form-div">
<label for="uploader">Select Approver<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="approver" [id]="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
</div>
setSelect2Options() {
this.select2Options = {
triggerChange: true,
allowClear: true,
placeholder : 'Select User* ',
minimumInputLength: 3,
ajax: {
url: '/api/reward/uploader/approver/search/user?limit=15',
headers: {
'X-XSRF-TOKEN': sessionStorage.getItem("auth"),
'content-type': 'application/json'
},
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term, page) {
return {
q: term.term, // search term
_: term._type
};
},
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
id: item.id,
text: item.name + " - " + item.email
}
})
};
}
},
//[placeholder]="'Select User* '"
}
}
The above codes are well and good. But now on a button click i need to set a value inn the select box.
this.vcDataService.getUploaderAproverDetails(id).subscribe((res: any) => {
this.uploaderApproverForm.controls['approver'].setValue(res.approverDetails.uploaderUserId);
this.uploaderApproverForm.controls['uploader'].setValue(res.uploaderDetails.approverUserId);
console.log("134", res)//uploaderUserId
//this.select2Options.ajax.processResults.push({id: 103, text: "aa"})
this.select2Options.placeholder="aa";
//this.displayUploader = "aaa";
// $('#uploader').val('ENABLED_FROM_JS');
// $('#uploader').trigger('change');
// this.select2Options.templateSelection = {
// selected: true,
// id: res.approverDetails.approverUserId,
// text: res.approverDetails.approverName,
// title: res.approverDetails.approverName
// }
// this.select2Options.initSelection = {
// callback: {
// data: {"id":103, "text":'ENABLED_FROM_JS'}
// }
// }
console.log(this.select2Options);
this.updateApproverUploader = true;
this.uploaderApproverId = res.uploaderApproverId;
this.cd.detectChanges();
},
err => {
Swal.fire('Oops...', err.error.err, 'error');
})
I tried few things but didn't got the workaround.
After going through the documentation I found a solution for it. I used the data attribute of the ng-select2 and assigned it to a Select2OptionData type variable.
import { Select2OptionData} from 'ng-select2';
patch_panel_array: Select2OptionData[];
Then I added the required data which I needed to show in the field as displayed below:
res.panelApprovers.map(item => {
this.patch_panel_array.push({
id: item.panelApproverUserId,
text: item.panelApproverUserName + " - " + item.panelApproverUserEmail
})
approverIds.push(String(item.panelApproverUserId));
});
this.formData.controls['panelApprover'].setValue(approverIds);
And here is my select 2 field:
<ng-select2 formControlName="panelApprover" [data]="patch_panel_array" [options]="select2OptionsPanel" width="100%" style="width: 100%;">
</ng-select2>
Related
I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.
I need to send a parameter to Html.Kendo().Dialog():
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted"
#(Html.Kendo().Dialog()
.Title("Update")
.Content("<p>" + msg + <p>")
However, that construct does not allow this, saying that "msg" does not exist in the current content
How can I do that?
Updated version:
if ((Math.abs(newAmount) < Math.abs(Amount)) && newAmount != 0) {
$("#dialog").kendoDialog({
width: "400px",
title: "Split Ticket Confirmation",
closable: true,
modal: true,
content: "<div style='text-align: center'>" + msg + "</div>",
actions: [
{
text: 'OK',
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
SaveData();
},
primary: true
},
{
text: "CANCEL",
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
return false;
},
primary: true
}
]
}).data("kendoDialog").open();
}
else {
SaveData();
}
Using Razor HTML C# syntax, you can achieve it without errors by doing this:
#{
var msg = "The amiunt of " + diff + " will be subtracted";
}
Then just passing it regularly to the Content as you already did.
If you are using JavaScript and really want to use that dialog inside script tags then you can do this:
var dialog = $('#dialog'), undo = $("#undo");
undo.click(function () {
dialog.data("kendoDialog").open();
undo.fadeOut();
});
function onClose() {
undo.fadeIn();
}
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted";
dialog.kendoDialog({
width: "400px",
title: "Update",
closable: false,
modal: false,
content: "<p>" + msg + "<p>",
actions: [
{
text: "OK",
action: function(e){
// e.sender is a reference to the dialog widget object
// OK action was clicked
// Returning false will prevent the closing of the dialog
return false;
},
primary: true
},
{ text: 'Action 2' },
{ text: 'Action 3', primary: true }
],
close: onClose
});
To add another action per request, to the Html.Kendo.Dialog() construct you can do the following:
#Html.Kendo.Dialog()
.Actions(actions =>
{
actions.Add().Text("Ok").Action("onOkClick").Primary(true);
})
And inside your your script tag you create the JS method:
function onOkClick(e)
{
//Do something
}
What I am doing is writing a partial into the page on the event that opens the dialog:
function OpenDialog() {
$.ajax({
url: '#Url.Action("ItemSearch", "Invoice")',
data: {
PartNumber: dataItem.Id,
AltPartNumber: 1,
Description: 1,
Application: 1
},
success: function (result) {
$("#SearchDialogContainer").html(result);
},
error: function (result) {
alert("An error occurred.");
}
});
}
<div id="SearchDialogContainer"></div>
And in the partial:
#model ParameterModel
#(Html.Kendo().Dialog()
.Name("SearchDialog")
.Title("Choose An Item To Add")
.Content("<div class='k-textbox k-space-right search-wrapper'><input id='employees-search' type='text' placeholder='Search employees' value='#Model.Property'/></div>")
.Width(400)
.Modal(true)
.Visible(false)
.Actions(actions =>
{
actions.Add().Text("Add Item").Primary(true);
actions.Add().Text("Cancel");
})
)
<script>
$(document).ready(function () {
$('#SearchDialog').data("kendoDialog").open();
});
</script>
I am new in jquery select2, in result return id, text and name where id is value I know how to get return id(value) with x$("inputBox").val();. but I want get return name in jquery-select2.
Is there any method to get the return name?
x$("#{id:city_combo_box}").select2({
placeholder:"Select City",
allowClear:true,
minimuminputLength:2,
templateResult: formatRepo,
escapeMarkup: function (markup) {return markup},
templateSelection: formatRepoSelection,
multiple:false,
ajax: {
url:ajaxurl,
dataType:"json",
data: function(params){
pp = params.term;
return{
startKey: pp,
page: params.page,
count: 10
};
},
processResults: function (data, params){
var k = data.viewentry;
console.log(k);
params.page = params.page;
return {
results: $.map(k, function(obj) {
return {id: (obj.entrydata[1].text[0]), text: obj.entrydata, name: (obj.entrydata[0].text[0])};
})
};
}
}
}).on("change", function(e){ x$("#{id:claim_limit_text}").val(x$("#{id:city_combo_box}").val(id));
}).trigger("change");
})
The only solution I came across is this:
html
<div id="ddWrapper1">
<select id="dd1"></select>
</div>
js
$(document).ready(function() {
var ddDate = [{
id: 1,
text: 'some item'
}, {
id: 2,
text: 'even more items'
}, {
id: 3,
text: 'oh no'
}, {
id: 4,
text: 'that is a realy long item name...'
}];
$('#dd1').select2({
data: ddDate,
allowClear: true,
multiple: true,
placeholder: '[dd1] select some items'
});
$('#dd1').on('change', function() {
console.log($('#dd1').data('select2').$selection[0].innerText);
})
});
But I have to admit that the result is not the nicest.
I have a method that return json data to my mvc view, not sure why my view shows json data instead of what I have in success part. This is my Post method:
[HttpPost]
[Route("resetpassword")]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
{
...
if (ModelState.IsValid)
{
if (resetPasswordViewModel.Password == resetPasswordViewModel.ConfirmPassword)
{
var user = Task.Run(() => Service.GetUserByEmailAsync(email)).Result;
if (user != null)
{
userRequest.Id = user.FirstOrDefault().Id;
userRequest.Password = resetPasswordViewModel.Password;
userRequest.Token = token;
await Service.UpdateUserAsync(userRequest);
}
}
else
{
return Json(new { status = "error", message = "Please enter the same value again" });
}
}
return Json(new { status = "success", message = "" });
}
This is my view that is modal:
#model Models.ResetPasswordViewModel
#if (Model != null)
{
<div class="page resetPassword">
#using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal" id="reset-password">
<div class="modal-content">
<span class="close">X</span>
<div><input type="email" name="email" id="email" readonly value=#Model.Email /></div>
<div class="create-user-label">Password</div>
....
and this is my ajax function:
function resetPassword() {
var postResult = null;
var data = {
Email: document.getElementById('email').value
};
var path = "/resetpassword";
var errorMessage = document.getElementById('Message');
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
postResult = $.parseJSON(result);
alert(postResult.data);
if (result && result.message) {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
}
but instead of my view I only see json data in my screen like:
{"status":"success","message":""}
Your data will be automatically converted from JSON format into Javascript objects.
Presumably you just want to display the message in an alert:
success: function (result)
{
alert(result.data.message);
},
Well your data is going through, looks like you have some mapping problems, you should try this.
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
alert(result['status']);
if (result['status']== 'success') {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
Can't seem to figure out what the problem is here. This worked perfectly fine when using 3.5, but does not work with 4.0.
I am using select2.full.js as well which supports using input in this manner.
html:
<input id="vcreate-filter" type="text" name="settings[filter]" class="form-control" style="width:100%;"/>
js:
$("#vcreate-filter").select2({
placeholder: "Select or enter application...",
allowClear: true,
multiple: false,
ajax: {
dataType: 'json',
delay: 1000,
type: 'post',
url: '/process/get_application_list.php',
data: function (term, page) {
return {
term: term, // search term
page_limit: 25, // page size
page: page // page number
};
},
results: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
},
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};
}
}
}).on('change', function() {
$(this).valid();
});
get_application_list.php:
.......
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// make sure there are some results else a null query will be returned
if( count($results) > 0 )
{
foreach( $results as $row )
{
$ajax_result['results'][] = array(
'id' => htmlspecialchars($row['event_target'], ENT_QUOTES, 'UTF-8'),
'text' => htmlspecialchars($row['event_target'], ENT_QUOTES, 'UTF-8')
);
}
}
else
{
// 0 results send a message back to say so.
$ajax_result['results'][] = array(
'id' => 0,
'text' => 'No results found...'
);
}
// return result array to ajax
echo json_encode($ajax_result);
html: use select element instead of input.
<select id="vcreate-filter" type="text" name="settings[filter]" class="form-control" style="width:100%;"> </select>`
js: use processResults instead of 'results' as callback property.
processResults: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
assuming the json is in the correct format [{"id": "1", "text": "One"}, {"id": "2", "text": "Two"}]
Breaking changes seems to be documented here.