Set selected option JQuery - javascript

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.

Related

how to read a json config file and setting that parameter to ajax

I have a Json(config/server.json) config file which has server configuration.
eg:
{
"server": "127.0.0.1"
}
I want to read that 'server' parameter and assign that value to my other jquery functions.
eg:
var server = "";
$(document).ready(function() {
loadConfigFile();
loadCustomers();
});
function loadConfigFile() {
$.getJSON('config/server.json', function(jd) {
$.each(data.server, function(i,s){
alert(s);
});
});
};
function loadCustomers() {
$
.ajax({
type : 'GET',
url : server+':8080/cache/getCustomers',
...
}
My loadConfig file is not reading the JSOn file..What im doing wrong here?
Make sure that /config/server.json is exposed by server and valid address. You can try it by adding to browser. It should show entire file content. Next step, check browser console for errors..
Check this
$(document).ready(function() {
$.getJSON('config/server.json', loadCustomers);
});
function loadCustomers(configFile) {
$.ajax({
type : 'GET',
url : configFile.server+':8080/cache/getCustomers',
});
}
In your config/server.json add this :
{"server": "127.0.0.1"}
You client script :
var server = ""; // don't need
$(document).ready(function() {
loadConfigFile();
loadCustomers();
});
function loadConfigFile() {
$.getJSON('config/server.json', function(data) {
//HERE YOu need to get the name server
alert(data.server);
});
};
function loadCustomers() {
$.ajax({
type : 'GET',
url : server+':8080/cache/getCustomers',
success:function(data){
alert(data);
console.log(data);
$.each(data, function(i,s){
alert(s);
});
}
}

html onchange event not being called from ajax generated dropdown list

I have an ajax generated dropdown list. When the list generates it sends it back to the HTML like below.
However, the HTML side onchange() event does not seem to kick in. How can I get this to work?
function listSess(){
var name = document.getElementById("studentID").value;
$.ajax({
url : "<%=context%>/ListSessionsServlet?name=" + name,
type : "POST",
async : false,
dataType: "json",
success : function(data) {
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.sessid+'</option>';
});
$('#sessid')
.find('option')
.remove()
.end()
.append(toAppend);
}
});
}
<select id="sessid" name="sessid" onchange="listStudents();"> <--onchange not working when getting ajax generated list
</select>
If you bind the change event using jQuery instead of inline as a tag attribute, you can trigger it with jQuery in your AJAX callback:
// Hook up the change event on DOM ready
$(function() {
$('#sessid').change(function() {
listStudents();
});
});
function listSess(){
var name = document.getElementById("studentID").value;
$.ajax({
url : "<%=context%>/ListSessionsServlet?name=" + name,
type : "POST",
async : false,
dataType: "json",
success : function(data) {
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.sessid+'</option>';
});
$('#sessid')
.find('option')
.remove()
.end()
.append(toAppend);
$('#sessid').change(); // fire change
}
});
}
<select id="sessid" name="sessid"></select>
Your current logic for building out the new <options> might not work without them having a value attribute. Here's how I might change it:
...
success : function(data) {
var $sessid = $('#sessid');
$sessid.find('option').remove();
$.each(data, function (index, item) {
$sessid.append($('<option />').val(item.sessid).text(item.sessid));
});
$sessid.val(data[0].sessid).change();
}
...

Binding dropdown list using ajax and jQuery

I would like to bind the data from splunk to a dropdown list.
The servlet return a JsonString by gson
Gson gson = new Gson();
String jsonString = gson.toJson(arrays);
resp.getWriter().write(jsonString);
In the jsp, ajax was used to get back the jsonString and blind in drop down list.
$(document).ready(function() {
$.ajax({
type: "POST",
dataType : "json",
url : "../getName",
success : function(data) {
console.log("success to return name");
if (msg) {
alert("Somebody" + name + " was added in list !");
location.reload(true);
} else {
alert("Cannot add to list !");
}
$.each(objdata["wlsDomain"], function(i, val) {
jQuery('#DropdownList').append('<option value="' + val.name + '</option>');
});
};
)};
)];
It said $(...).ready is not a function. If I change the "$" to "jQuery", then there is no warning. However, binding is failed.
Then I have also tried the below code for knowing whether the ajax is workable.
And it showed "Fail". Therefore, the ajax is not workable.
jQuery(document).ready(function() {
var promise =jQuery.ajax({
type: "POST",
url: "../getName",
dataType: "json"
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
May I know what's wrong with this?
And how can I bind the name get from splunk to a dropdown list?
Thanks!
Try the following code:
$(document).ready(function () {
var $el = $('#DropdownList');
var url = "../getName";
$.getJSON(url, {}, function (data) {
$el.empty(); // remove old options
$.each(data, function(index, obj) {
$el.append($("<option></option>")
.attr("value", obj.name).text(obj.name));
});
} );
});

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

Categories

Resources