Load script or CDN after ajax call - javascript

I'm trying to run this ajax method for multi select drop down:-
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
},
async: false
When i use the static multi select drop down on the html it works without red box, image shown as below :-
And which is not working is shown in red box:-
These scripts i'm using :-
<link href="~/css/jquery.multiselect.css" rel="stylesheet" />
<script src="~/js/jquery.multiselect.js"></script>
<script src="/js/jquery.min.js"> </script>
The issue as i see is that in case of dynamic my scripts runs before page load and thus this dynamic ajax don't show drop down,but in case of static multi select drop down it works because this drop down is before the page loads and thus the script runs over it how do i run ajax before page call or before these scripts run.

Just call your .selectMultiple event function in your ajax success method after inserting your select tag in DOM
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
$('#langOpt3').selectMultiple(
//your code
);
}

Related

jQuery-set dynamic dropdown value

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>';

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 :)

All Dynamic Posts defaults to first Object

I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position

Difficulty calling JavaScript function on click after dynamically generating table

I'm having difficulty making a clickable button in my dynamically generated table that would send data specific to the table cell that was clicked.
My table is generated and modified whenever the user types into the search box with this AJAX call:
$(document).ready(function(){
$("#data").keyup(function () {
$.ajax({
type: "POST",
dataType: "JSON",
data: "data=" + $("#data").val(),
url: "search1.php",
success: function(msg){
var output = "";
for(var i = 0; i < msg.length; i++) {
output += '<tr onmouseover=this.style.backgroundColor="#ffff66"; onmouseout=this.style.backgroundColor="#F0F0F0";>';
output += '<td>';
if (msg[i].website != ''){ output += '' + msg[i].name + '</td>';}
else output += msg[i].name + '</td>';
output += '<td class="description">' + msg[i].description + '</td>';
output += '<td><input type="button" onclick=' + submit() + ' value=' + msg[i].id + '></td></tr>'; // Here is where I'd like to put in a clickable button
}
$("#content").html(output);
$("#myTable").trigger("update");
}
});
});
});
If I make submit() simply alert("hello") it runs when the page is loaded for every instance of the onclick call to submit(). Could someone please explain to me how to make submit only get called when its button is clicked and not on page load. Thanks in advance.
You have to put the submit() call in a quoted string. Same goes for the msg[i].id. All values in HTML should be quoted.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
You are trying to assign submit() to the button's onclick, but you are actually calling the function when you generate the string output. It needs to be in quotes inside the string, not concatenated in.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
//----------------------------------------^^^^^^^^^^^^
A better strategy would be to leave out the onclick attribute entirely, and use jQuery's .on() to dynamically assign the method. It is often considered a better practice to bind events dynamically rather than hard-code them into HTML attributes.
// No onclick attribute in the string:
output += '<td><input type="button" value="' + msg[i].id + '"></td></tr>';
// And a call to .on() in the $(document).ready()
$('input[value="'+msg[i]+'"]').on('click', function() {
submit();
});

jQuery doesnt invoke alert box

I have the following:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.getJSON(
"/myServer/getAllWidgets",
function(data) {
var optionsHTML = "<select id='widget-sel'>";
optionsHTML += "<option selected='selected' id='default'>Select an option</option>";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">'
+ data[i] + '</option>';
}
optionsHTML += "</select>";
$('#widget-sel-div').html(optionsHTML);
}
);
$("#widget-sel").change(function() {
alert("Hello!");
});
});
</script>
<div id="widget-sel-div"></div>
So, the idea is that when document.ready fires, it populates the widget-sel-div with a select box (widget-sel) and then creates a change handler for that select that simply prints "Hello!" to the screen via alertbox.
When I run this, I get no errors (Firebug doesn't complain at all) and the select gets populated with all my widgets from the AJAX call to /myServer/getAllWidgets. The problem is, the change handler isn't working: when I select a widget I don't get the alertbox. Can anybody spot where I'm going awrye? Thanks in advance.
At the time the code runs, the #widget-sel element doesn't exist in the DOM, because you add it in the callback to getJSON (which is asynchronous). You can't bind an event handler to it when it doesn't exist yet.
To get around this, you can delegate the event handler higher up the DOM tree (looks like you can use the parent div in this case) with the .on() method (jQuery 1.7+, if you're using an older version, use .delegate() instead):
$("#widget-sel-div").on("change", "#widget-sel", function () {
alert("Hello!");
});
This is due to the asynchronous nature of the AJAX call. The change handler will be executed before the AJAX call has completed and therefore there will be no element in the DOM for it to bind to. Instead, place the change in the AJAX call back:
$.getJSON(
"/myServer/getAllWidgets",
function(data) {
var optionsHTML = "<select id='widget-sel'>";
optionsHTML += "<option selected='selected' id='default'>Select an option</option>";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">' + data[i] + '</option>';
}
optionsHTML += "</select>";
$('#widget-sel-div').html(optionsHTML);
$("#widget-sel").change(function() {
alert("Hello!");
}
}
);
Or alternatively you can leave the change handler where it is and delegate the event listener to a static parent element like this:
$('#widget-sel-div').on('change', '#widget-sel', function() {
alert("Hello!");
});

Categories