Having trouble with my variable 'html'. I think i have the scope correct but something weird happens when I run this code. the first alert of the 'html' variable produces a blank result and then I populate my select list with the same 'html' variable and it works, then i alert the 'html' variable again and the options show up.
If I remove the two alerts the list is not pop
function populateMakes(years)
{
var makes = new Array();
var html = "";
$.each(years, function () {
var uri = "/api/make?year=" + this;
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
});
});
alert(html);
$("#Make").html(html);
alert(html);
$("#MakeSection").removeClass("hidden");
};
Document Ready Script
$(document).ready(function () {
populateYears();
$("#Year").change(function () {
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateMakes($("#Year").val());
});
$("#Make").change(function () {
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateModels($("#Year").val(), $("#Make").val());
});
$("#Model").change(function () {
$("#SubModelSection").addClass('hidden');
//
});
$("#Clear").click(function () {
$("#YearSection").addClass('hidden');
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateYears();
})
});
.getJSON is async and i overlooked the timing. i needed to add the .done callback and set the output there. the script simply wasn't finished yet.
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
}).done(function () {
$("#Make").html(html);
$("#MakeSection").removeClass("hidden");
});
I also didn't send an array in the event handler on the code I posted in the question. I fixed that first.
Related
I load partialview on load page .
$(window).bind("load",
function() {
$.get("/agent/GetInfo",
function(data) {
$("#home-tab-right").empty();
$("#home-tab-right").append(data);
});
});
I have a dropdown on partialview. I want to run a function on change it. I use this code but don't run it.
$(document).ready(function(){
$('#StateId').change(function() {
var item = $(this).val();
$.ajax({
url: '#Url.Action("FindCity", "Agent")',
type: 'POST',
data: { value: item },
success: function(result) {
$("#CityId").find('option').remove();
$.each(result,
function(i) {
var optionhtml = '<option value="' +
result[i].Id +
'">' +
result[i].Name +
'</option>';
$("#CityId").append(optionhtml);
});
$(".popup-loading").hide();
}
});
});
});
In order to avoid attaching the same event multiple times. Use Off() first
$(document).off("change.findCity").on("change.findCity","#StateId",function(){ //process })
<script type="text/javascript">
$(document).ready(function (event) {
$('#StateId').on('change', function (event) {
//do something
});
});
</script>
I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!
I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}
I want to send json data from my controller to my view when a specific action happens.
I used this on controller to send the data
[HttpGet]
public JsonResult JSONGetParking(int buildingID){
return this.Json(
new
{
Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
}
, JsonRequestBehavior.AllowGet
);
}
it works very good
on my script i used this:
FloorScript.js
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
I have opened google chrome and I can see the request and the response like this:
i can see the two text that i alerted
However, on my selector, i just see undefined value
Html
<div id="editor-label">
<select id="parkingID" name="parkingID"></select>
</div>
I have added the jquery in this
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/FloorScript.js");
}
You're not looping on the correct variable.
You did this:
$.each(data, function (obx, oby) {
whereas you should do this:
$.each(data.Result, function (obx, oby) {
This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.
Also I'd replace:
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
with:
$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {
and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:
#Html.DropDownListFor(
x => x.BuildingId,
Model.Buildings,
new {
id = "buildingID",
data_url = Url.Action("JSONGetParking")
}
)
and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):
$('#buildingID').change(function () {
var url = $(this).data('url');
$.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {
Alright, now the initial mess is tidied up.
use data.Result in your each loop
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data.Result, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
Hope this helps...
I have a function in java script, that I used it to take the JSON from my asp.net mvc controller, to display the item in my view :
<script type="text/javascript" language="javascript">
var k = 0;
var record_count = 0;
var col_count = 3;
var row_count = record_count / col_count;
var str = "<table>";
function itemTemplate() {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, function (product) {
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
});
str += '</table>';
alert(str);
return (str);
}
$(document).ready(function () {
alert(itemTemplate());
});
</script>
Problem : when I alert the function in $(document).ready function, first it is alert <table></table> and then continue to alert the full string that I concatenate it in my $.getJSON function. So the function is return before taking JSON.
Anyone have any idea about it?
Thanks.
try setting async to false, then make your $.getJSON call
Code:
jQuery.ajax({async : false});
$.getJSON( ... );
Reference: http://api.jquery.com/jQuery.ajax/
Note: As of jQuery 1.8, the use of async: false is deprecated.
Alternate Solution
<script type="text/javascript" language="javascript">
var k = 0;
var record_count = 0;
var col_count = 3;
var row_count = record_count / col_count;
//var str = "<table>";
function itemTemplate(callback) {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, callback);
//str += '</table>';
//alert(str);
//return (str);
}
$(document).ready(function () {
itemTemplate(function (product) {
var str = "<table>";
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
str += "</table>";
alert(str);
});
});
</script>
Well, that's how ajax works, the $.getJSON starts an asynchronous call to the server, so you will hit the next lines before the ajax call is completed. You should create all of the table HTML inside the callback for the getJSON
function itemTemplate() {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, function (product) {
var html = "<table>";
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
html += "</table>";
// now append html to the DOM
});
}
the function will return before you get the data back from the server, so anything you want to do with the data returned from the server has to be inside the callback of the .getJSON
Ajax requests to a server are asynchronous. This means, the client computer says: Go forth and do something at that 3rd party server. And when you have an answer (aka, a response) then tell me and i'll deal with it.
So .. lets wire that JQuery code to do -exactly- that...
<script type="text/javascript">
$(document).ready(function () {
// Just call this method, on load.
// (yuck, but i'm following your code)...
itemTemplate();
});
function itemTemplate() {
$.ajax({
url: "/ProductListing/AllProductListing/0",
type: "GET",
success: function (data, textStatus, jqXHR) {
// Handle success. like .. append data, etc.
//.....
alert("whatever");
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle the error. Don't forget you can access
// data from the response (aka. the jqXHR)...
alert(errorThrown);
}
});
}
</script>
The trick here was to wire up the success: and the error: callback's.
Once in there, you can do whatever you want, etc.
Try putting a break point in there and seeing the values :)
Reference: jQuery.ajax() doco's.
$.getJSON executes asynchronously which means that as soon as it fires off the request the function invocation is considered complete and the JavaScript engine moves on to the next line of code: str += '</table>'.
You get two alerts because you invoke the alert function within your itemTemplate function which itself is invoked to return a value for the alert function call made within $(document).ready. Did you mean to call alert twice?
In any case it seems that your intention as far as building str is to close out the table tag after the completion of $.each so...
var k = 0,
record_count = 0,
col_count = 3,
row_count = record_count / col_count,
str = '<table>';
function itemTemplate() {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, function (product) {
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
str += '</table>';
alert(str);
});
}
$(document).ready(function () {
itemTemplate();
});