Set select2 value as soon as page loads - javascript

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);
}
}
});

Related

Editable resolves to undefined mixing KnockOutJS and plain Javascript

I tried to create a drop-down menu using options binding in KnockOut JS (ko.plus to be precise). Things were running as expected until I mixed my solution up with this jsfiddle: http://jsfiddle.net/jnuc6y05/ in order to place a default option in the list. The problem lies in "HERE" (please see the code) where I get
error message
"TypeError: this.fieldStreetApallou is not a function"
As I said I had no problem, and I think mixing plain javascript with KO caused the situation. I tried to unwrap the editable with no luck since it resolves to undefined. Even ko.toJS does not do the trick (undefined again).
I don't have any serious experience with KO and furthermore with Javascript, and any help would be greatly appreciated.
PS: Reduced code provided
/////// HTML
<input data-bind="value: fieldStreetApallou, enable: fieldStreetApallou.isEditing" />
Rename
<div data-bind="visible: fieldStreetApallou.isEditing">
Confirm
Cancel
</div>
/////// Javascript
<script type="text/javascript">
ko.observableArray.fn.find = function(prop, data) {
var valueToMatch = data[prop];
return ko.utils.arrayFirst(this(), function(item) {
return item[prop] === valueToMatch;
});
};
var availableCompanies = [{
offset: 1,
name: "Company1"
}, {
offset: 2,
name: "Company2"
}
// ...more pairs here
];
//Default pairs for the drop-down menus
var selectedCompanyApallou = {
offset: 1,
name: "Company1"
};
var ViewModel = function(availableCompanies, selectedCompanyApallou) {
this.availableCompaniesApallou = ko.observableArray(availableCompanies);
this.selectedCompanyApallou = ko.observable(this.availableCompaniesApallou.find("offset", selectedCompanyApallou));
this.fieldStreetApallou = ko.editable("Initial value");
postStreetFieldToServerForApallou = function() {
$.ajax({
type: "PUT",
url: "http://www.san-soft.com/goandwin/addresses/" + 15,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: "Address_id=15&Street=" + this.fieldStreetApallou() //<---- HERE!
}).done(function(data) {
alert("Record Updated Successfully " + data.status);
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
});
};
};
ko.applyBindings(new ViewModel(availableCompanies, selectedCompanyApallou));
</script>
I think you linked to the wrong JSFiddle.
Looks like this is not what you are expecting when postStreetFieldToServerForApallou is called by the button click. this in JavaScript is based on who called the function.
To work around it in this case, I like to set var self = this; at the top of the view model so self always points to the view model, then I replace all instances of this with self. This is really only needed on your HERE line, but it simplifies to use self throughout.
The fixed view model code:
var ViewModel = function(availableCompanies, selectedCompanyApallou) {
var self = this;
self.availableCompaniesApallou = ko.observableArray(availableCompanies);
self.selectedCompanyApallou = ko.observable(self.availableCompaniesApallou.find("offset", selectedCompanyApallou));
self.fieldStreetApallou = ko.editable("Initial value");
postStreetFieldToServerForApallou = function() {
$.ajax({
type: "PUT",
url: "http://www.san-soft.com/goandwin/addresses/" + 15,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: "Address_id=15&Street=" + self.fieldStreetApallou() //<---- HERE!
}).done(function(data) {
alert("Record Updated Successfully " + data.status);
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
});
};
};

Set selected option JQuery

I am using jquery-1.12.3.min.js and dynamically get options for select
function loadCompanies() {
if ($("#isSubsidiaryCompany").is(":checked")) {
$.ajax({
type : "GET",
url : "get_companies",
success : function(data) {
$.each(data, function(i, data) {
$('#companiesList').append($('<option>', {
value : data.id,
text : data.name
}));
});
}
})
$("#companiesSelect").show();
$('#companiesList').val(data.id);
} else {
$("#companiesSelect").hide();
}
I want to set option selected but $('#companiesList').val(data.id) doesn`t work, could you suggest me the right way do achieve this, thanks in advance
You are setting the value outside of the AJAX callback function. Which means that those options are not guaranteed that they will be there. Put your code into the success callback:
if ($("#isSubsidiaryCompany").is(":checked")) {
$.ajax({
type : "GET",
url : "get_companies",
success : function(data) {
$.each(data, function(i, data) {
$('#companiesList').append($('<option>', {
value : data.id,
text : data.name
}));
});
$("#companiesSelect").show(); // < === HERE ===
$('#companiesList').val(data.id);
}
})
// ...
Also, to which data are you referring to in your .val(data.id)?
$('#companiesList').val(data.id)
I think there is problem with your data object. please make sure that data.id shoudl contain something.

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 };
});

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

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.

How can I access the element ID from a class, within an ajax function in jQuery?

I'm trying to use the typeahead script for Bootstrap. It's working great, but I'd like it to be a bit more dynamic. I'd like to run several auto-complete inputs on the same page without duplicating code.
HTML:
<input type="text" class="typeahead" name="person_name" id="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search">
Basic jQuery:
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + ###[HOW CAN I PUT ELEMENT ID HERE?]###
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
The above doesn't work (obviously). But if I set the class name to .typeahead-person-search and then create a new typeahead function that manually adds the source person-search, and another function entirely for .typeahead-city-search, then everything works fine. I'd like to avoid having two functions when it's really just a variable that separates the two.
How can I put the element ID of the active .typeahead class into the $.ajax function?
Ok, I've gone up on something else, I couldn't test it directly with the .typeahead librairy, but I've done the same thing with another librairy I amusing.
How bout doing
$('.typeahead').each(function(){
var self = $(this);
self.typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + self.attr('id')
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
});
EDIT :: try my second answer it should work, I've been using that with another librairy that had the same problem
try something like
var id = $(this).attr('id');
then
var url = 'blahblah' + id + 'blablahblah);
and put the var url in your ajax query at the url: spot
You could add a data attribute to each input that contains the dynamic portion of the URL.
<input type="text" class="typeahead" name="person_name" id="person-search" data-source="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search" data-source="city-search">
You can then grab that using jQuery and pass it into the URL.
$('.typeahead').typeahead({
source: function(typeahead, query) {
var source = $(this).data('source');
return $.ajax({
url: '/ajax_lookup_directory/'+source+'.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
You can try the following
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_directory/' + $(this).attr('id') + '.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});

Categories

Resources