jQuery-set dynamic dropdown value - javascript

I have a dropdown
<select id="DropdownId" label="condition " ></select>
Below is the code, from where i am filling values into the dropdown:
var request = $.ajax({'url': '/getDropdownValues'});
request.done(function(response)
{
response = JSON.parse(response)
var processbyList=[];
$.each(response, function(index, element) {
processbyList.push(element.processby);
});
$("#DropdownId").select2({
data: processbyList
});
});
request.fail(function(jqXHR, textStatus)
{
alert('Request failed: ' + textStatus);
});
I want to set a value inside dropdown. How can I set the dropdown value using jQuery?
Here 'responseitem' is the value which i am getting from some ajax call and i want this value to set into the dropdown.
I have tried using
1. `document.getElementById("DropdownId").value = responseitem;`
2. `$('#DropdownId').val(responseitem);`
But nothing worked for me. Am I missing something or where I am wrong? How to achieve this?
EDIT:
On button click event i am creating a table inside that this dropdown is in one in one column of it.
function onButtonClick(){
// to fill values in dropdown
var request = $.ajax({'url': '/getDropdownValues'});
request.done(function(response)
{
response = JSON.parse(response)
var processbyList=[];
$.each(response, function(index, element) {
processbyList.push(element.processby);
});
$("#DropdownId").select2({
data: processbyList
});
});
request.fail(function(jqXHR, textStatus)
{
alert('Request failed: ' + textStatus);
});
//this is again inside an ajax call
var requestRegex =$.ajax({url:'/Info',
data:"FieldName="+responseitem[0],
processData: true,
contentType: "application/json",
dataType: "json",
});
requestRegex.done(function(responseRegex)
{
var panel=document.createElement("panel");
var h = '<div class="panel panel-default" >';
h += '<div class="panel-heading fixed-panel">';
h +='<h3 class="panel-title">'+responseitem[0]+'</h3>';
h +='<span class="pull-right clickable"></span>';
h += '</div>';
h +='<div class="panel-body">';
h += '<div class="table-responsive">';
h +='<table id="' +"albums"+ '" cellspacing="0" class="table-bordered table-hover specialCollapse>';
h +='<thead></thead>';
h +='<tbody id="' +"tbody"+ '">';
h +='<tr>';
h +='<td><h4><bold>Process By</bold></h4></td>';
//h +='<td id="' +"processBy"+ '"><textarea class="form-control" rows="1" style="max-width: 30%;">'+ responseitem[2] + '</textarea></td>';
h +='<td id="' +"processBy"+ '"><select id="DropdownId" style="width:200px;" value="' +responseitem[2]+ '" ></select></td>';
h +='</tr>';
h +='</tbody>';
h +='</table>';
h += '</div></div>';
panel.innerHTML = h;
$("#DropdownId").select2();
$("#DropdownId").val(responseitem[2]).trigger("change");
});
request.fail(function(jqXHR, textStatus)
{
alert('Request is failing: ' + textStatus);
});
}
EDIT:
document.getElementById("DropdownId").value=responseitem[2];
This is showing correct output in console:
document.getElementById("processbyDropdownId").value=responseitem[2];
>>>"page"
But not in the jQuery UI.I dont want to refresh my entire page. I just want to refresh such that only the dropdown value refreshes.

As you using select2 plugin, you need to trigger change event after set the new value
$('#DropdownId').val(responseitem).trigger('change');
Obviously, responseitem must be one of #DropdownId's items.
You can read more about that here
Update
As you didn't provide enough info in your question, using jsonplaceholder.typicode.com, I created demo to show you how you can change select value after an ajax request (I used select2 too):
HTML
<select style="width: 200px;">
<option value="1">Leanne Graham</option>
<option value="2" selected="selected">Ervin Howell</option>
<option value="3">Clementine Bauch</option>
</select>
JS
$("select").select2();
setTimeout(function() {
$.ajax("https://jsonplaceholder.typicode.com/users", {
type: "GET",
success: function(res) {
var id = -1;
for (var i in res) {
if (res[i].name == "Clementine Bauch") {
id = res[i].id;
break;
}
}
$("select").val(id).trigger("change");
}
});
}, 1000);
Codepen
You will see after 1 second the selected value of select will be changed to Clementine Bauch.
Seems like you updated your question, so, you missing option inside select, change your code as follow:
h += '<td id="' + "processBy" + '"><select id="DropdownId" style="width:200px;"><option value="' + responseitem[2] + '">"' + responseitem[2] + '"</option></select></td>';

Related

json returns nothing after value changed

I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(

how to display JSON Array into table using AJAX in JSP

I am new to ajax. I am trying to display data into table in JSP file.
API is called using AJAX.
Controller pass below response:
BatchwiseStudent [name=Ram, course=MCA (Commerce), emailId=rammansawala#gmail.com, placed=null, batch=2016, mobileNo=7.276339096E9]
In JSP page:
<script type="text/javascript">
function getStudentDetails(){
$batch = $('#batch');
$course = $('#course');
$.ajax({
type: "GET",
url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),
success: function(data){
console.log("SUCCESS ", data);
if(data!=null){
$("#batchwiseTable").find("tr:gt(0)").remove();
var batchwiseTable = $("#batchwiseTable");
$.each(JSON.parse(data),function(key,value){
console.log(key + ":" + value);
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['name']);
rowNew.children().eq(2).text(value['emailId']);
rowNew.children().eq(3).text(value['placed']);
rowNew.children().eq(4).text(value['batch']);
rowNew.children().eq(5).text(value['mobileNo']);
rowNew.appendTo(batchwiseTable);
});
$("#batchwiseTable").show();
}
},
error: function(e){
console.log("ERROR ", e);
}
});
}
</script>
I can see new row into the table but there is no data. I want name, emaild, mobileNo, etc into particular field.
can anyone guide me where am i wrong?
Below code should be keep in the .jsp Page where you show table you don;t need to write html code for table jsp page.
<div id="insert-table-here"></div>
Javascript code:
below code is for ajax call
replace uri with your url value that is used in your url.
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
var str = '<table class="table table-bordered"><thead>'+
'<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
$.each(data, function (key, value) {
str = str + '<tr><td>' +
value.name + '</td><td>' +
value.course + '</td><td>' +
value.emailId + '</td><td>' +
value.placed + '</td><td>' +
value.batch + '</td><td>' +
value.mobileNo + '</td></tr>';
});
str = str + '</tbody></table>';
$('#insert-table-here').html(str);
}, error: function (data) {
}, complete: function (data) {
}
});

Select option does not show data

This is my first attempt to databind an html control via ajax. I check/debug my ajax call and the data are retrieved OK, but the do not appear in the select option. My javascript is located at the bottom of my aspx page. What's the problem
$(function () {
$.ajax({
type: "POST",
url: "psHlp.asmx/getDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#District").empty();
$.each(msg.d, function () {
$("#District").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load districts");
}
});
});
This is my select option which is located at the beginning of my page
<div class="col-sm-3 col-xs-12 ffield">
<select id="District" style="display: none;">
</select>
</div>
Try using like this on your each loop.
var options;
$.each(msg.d, function () {
options += '<option value="' + this["Value"] + '">' + this["Text"] + '</option>';
});
console.log(options);
$("#District").append(options);
You need to specify (index,value) params in your $.each callback function and use value to access the iterated elements. Something like this.
$.each(msg.d, function (index,value) {
$("#District").append("<option value='" + value.Value + "'>" + value.Text + "</option>");
});
Finally I found the solution. All the above suggestions were correct. The problem occurred because I'm using bootstarp js/css (customer's designer provided the layout), so I need to rebuild the multiselect option after the append.
var options = "";
$.each(response.d, function () {
options += '<option value="' + this['Value'] + '">' + this['Text'] + '</option>';
});
$("#Town").append().html(options);
$("#Town").multiselect('rebuild');
Hope this will help at least one person :)

How to retrieve value from a div dynamically?

Guys I have a function which uses ajax call to retrieve data dynamically based upon a value in div. Now lastNoticeID value in the function is not getting updated as its not in any loop..thus it keeps repeating the same data..
CODE :
function callMoreData() {
var lastNoticeID = $('#hiddenLastNoticeID').val();
$.ajax({
type: "GET",
url: "/api/values/getnotice?num=" + lastNoticeID,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
BindNotice(value);
});
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input id="hiddenLastNoticeID" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
As you can see in the code above, I am retrieving value from the above div and then passing it to webApi url... Now this is running fine and on the first scroll I get the values but then the function keeps repeating the same values over and over again i.e. var lastNoticeID is not getting updated. How do I get it to update per scroll event?
btw divNotices has the same html code as BindNotice function.
Use classes instead:
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
And then:
var lastNoticeID = $('.hiddenNotice').last().val();
Or, you could just store the LastNoticeID in a variable:
var lastNoticeID = 0;
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
lastNoticeID = values.LastNoticeID;
}
It would seem that you are adding more elements of the same ID. ID's are supposed to be single instance and Jquery will therefore only grab the first instance in the DOM. (Which is why $('#hiddenLastNoticeID').val(); is the same every time)

How to load JSON data associated with each link onclick?

I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.

Categories