How to get the name from the id in select2 combo? - javascript

I have select2 ComboBox the data is loaded by Ajax. I am trying to set the default value to the select2 by reading the id from the input value (which is set on the server side) and set it to the select2 programmatically.
I think I should implement the initSelection() function in a way to solve this issue.
Here is my code:
The HTML input is:
<input type="hidden" class="mySelect2" value="01" name="someName" />
The value "01" is set at the server
The JavaScript is:
$(".mySelect2").select2({
ajax: {
url:"data.php",
dataType:"json",
data:function(term, page) {
return {
query:term, page: page -1
} ;
},
results:function(data, page) {
return data
}
}
});
I tried this but it did not work .
$(".mySelect2").select2('val', '01');
And an error occured : "cannot call val() if initSelection() is not defined "

try something like this
$(function(){
$(".mySelect2").select2({
ajax: {
url:"data.php",
dataType:"json",
data:function(term, page) {
return {
query:term, page: page -1
} ;
},
results:function(data, page) {
return data
},
}
});
$(".mySelect2").select2('data', {id:'01',text:'01'});
})
HTML CODE
<input type="hidden" class="mySelect2" style="width:100px;" value="[{id:'01',text:'01'}]" name="someName" />

The general premise of initialising a default value in a select2 control using ajax can be solved using something like:
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("data.php", {
data: {
id: id // return a single item from your service
},
dataType: "json"
}).done(function (data) {
var results = [];
$.each(data, function (index, item) {
results.push({
id: item.Id, // whatever your id field is
text: item.TextValue // whatever your text field is
});
});
callback(results[0]);
});
}
}
I'm not a PHP person, but this should be standard across ajax requests. The approach basically assumes you can return a single result as well as the list.

Related

Asp.Net Core - Return values from the controller and put the values ​into the inputs by Ajax?

I have a drop down list and I want the value to be sent to the controller when an option is selected,replaceing the returned values ​​in the desired inputs
Html Inputs :
<input type="text" class="form-control js-inputs" id="microchipcode">
<input class="form-control js-inputs" id="fa-horse">
<input type="text" id="fa-fatherhorse" class="form-control js-inputs">
Html DropDown:
$('.js-selected-item').change(function () {
let Value = $(this).val();
$.ajax({
data: { value: Value },
Url: "/Horse/GetHorseByMcode",
type: "post",
success: function (data) {
}
});
});
Controller :
public async Task<IActionResult> GetInfoHorse(string value)
{
var horse = await _coach.GetHorseByMcode(value);
if (horse != null)
{
return Json(horse);
}
return NotFound();
}
Query :
public async Task<Horse> GetHorseByMcode(string value)
{
return await _context.Horses.SingleAsync(h => h.MicrochipCode == value.Trim());
}
If you want to put a value into an input via js, add an ID to the inputs and do the following:
JS:
document.getElementById('//inputId').value = '';
Jquery:
("#//inputId").val("");
How do I access the data inside the object?
You can check the request and response in f12 developer tool Network tab, like below.
and implement frontend code to populate input field(s) in ajax success callback function based on your actual returned data.
For example:
success: function (data) {
$("#fa-fatherhorse").val(data.fatherHorse);
//populate other inputs based on your actual returned data
How to replace Drop Down list ?
If you want to dynamically set the selected value/option of the dropdown, you can try:
$("#dropdown_id_here").val(value_of_selected_option);
If you want to dynamically append <option> to your dropdown, you can try:
var newoption = "<option value='" + option_val + "'>" + option_text + "</option>";
$("#dropdown_id_here").append(newoption);

jQuery ajax input field event, options list and setting a value

I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.

ajax postback method for refreshing dropdown list

Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});

Set select2 value as soon as page loads

I know this has been asked several times before, but I've literally been going through solutions for 4 hours and couldn't find the solution for my specific problem.
I've got a select2 select field on an Laravel blade edit view and I would like to set it's value to the data passed to the view. Passing data to the view already happens, and using the select field is no problem either, it works perfectly fine. But every single try I've been going for failed to set it. I've been messing around with a button to set the select field's value, but every modification of
$("select[name=customer]").val("1");
has failed to do this. It always transfers "?id=null". I would appreciate someone setting light on this, as I can't really continue without this. I am adding the important code parts below, if you need anything more, just reply. Thanks in advance!
Select HTML:
<label>*Customer</label>
<select class="form-control" name="customer" id="customer" style="width: 100%">
<option></option>
</select>
Select2:
$("select[name=customer]").select2({
allowClear : true,
placeholder : "Choose customer",
ajax : {
url : "/search/autocomplete/get_customers",
dataType : 'json',
type : "GET",
quietMillis : 50,
delay : 250,
data : function(params) {
return {
filter : params.term
};
},
processResults : function(data) {
return {
results : $.map(data, function(item) {
return {
text : item.name + ' (' + item.customer_code + ')',
id : item.id
}
})
};
},
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
}
});
Button:
<button type="button" onclick="test()">Test</button>
Function test():
function test() {
$("select[name=customer]").val("1");
};
I have been trying several alterations of this, examples:
$("select[name=customer]").val("1");
$("select[name=customer]").val("1").change();
$("select[name=customer]").val("1").trigger("change");
$("select[name=customer]").select2("val", "1");
with the list continuing.
If I didn't provide important stuff, message me or replay please!
Best regards
Nick
First you should check if the selector is correct by using console.log();. This time use single quotes for the attribute name. select[name='customer']
var select = $("select[name='customer']");
console.log(select.length);
If it delivers 0 the selector is wrong. If you have problems with complex css selectors you should probably just use ID's instead.
If jquery selectors are correct but the error occurs, it is most likely because you get the values via ajax and do not wait for the callback/success. Make use of jQuery's ajax success functionality.
$.ajax({
url: '...',
success: function(response) {
test();
}
});
You could try something like this.
$("select[name=customer]").select2({
allowClear : true,
placeholder : "Choose customer",
ajax : {
url : "/search/autocomplete/get_customers",
dataType : 'json',
type : "GET",
quietMillis : 50,
delay : 250,
success: function(){
test();
},
data : function(params) {
return {
filter : params.term
};
},
processResults : function(data) {
return {
results : $.map(data, function(item) {
return {
text : item.name + ' (' + item.customer_code + ')',
id : item.id
}
})
};
},
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
}
});

How to send created tags back to server

Im using Select2 jquery plugin to add/create tags for posts on my ASP.NET MVC site. The features I use is "Loading Remote Data" and "Tagging Support" like this :
<script type="text/javascript">
function tagResultList(tag) {
var counter = 'ny tagg';
var markup = "<table class='movie-result'><tr>";
markup += "<td class='movie-info'><div class='movie-title'>" + tag.text
if (typeof tag.count != 'undefined') {
counter = tag.count;
}
markup += "(" + counter + ")</div>";
markup += "</td></tr></table>"
return markup;
}
function tagResultSelectionName(tag) {
return tag.text;
}
$("#txtTagBox").select2({
multiple: true,
createSearchChoice:
function (term, data) {
if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) {
return { id: 0, text: term };
}
},
placeholder: "Sök efter en tagg",
minimumInputLength: 3,
maximumInputLength: 30,
maximumSelectionSize: 5,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: _tagsUrl,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data.Tags, more: data.MorePages };
}
},
formatResult: tagResultList, // omitted for brevity, see the source of this page
formatSelection: tagResultSelectionName, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
});
</script>
I can type and choose a new tag(create new tag) but the problem is that when submitting the textbox will forward Id 0 to the server and there Is no way to know what the created tag was named.
So how do I get it to send the string instead of the id to the service? Or could there be a mixed mode like id for existing and string for created?
BestRegards
try
function (term, page) {
return {
q: term, // search term
page: page
,newtag : 'created tag' //replace by var or jquery chain that'll return the string
}
it'll be send in the get array to _tagsurl with index newtag

Categories

Resources