I'm trying to call getPointOnMap function on the onclick event and to give it an json object as a parameter.
here is code samples:
$.ajax({
type: "POST",
url: "/getResult.json",
success: function(result) {
var html = '';
for (var i = 0; i < result.length; i++) {
var obj = result[i];
html += "<input type='checkbox' onClick='getPointOnMap(" + obj + ")'/>" + obj.address + "<br>";
}
$("#myDiv").append(html);
}
});
here is function getPointOnMap
function getPointOnMap(object) {
map.addMarker({
lat: object.lattitude,
lng: object.longtitude,
click: function(e) {
alert('You clicked in this marker');
}
});
}
firebug output(also in question name):
SyntaxError: missing ] after element list
getPointOnMap([object Object])
what should I do to pass correct object?
I don't think it is allowed to repost a question, anyway you should create your HTML Input not via string but via DOM, so you can attach the handler to the function and not on the "onclick".
$.ajax({
type: "POST",
url: "/getResult.json",
success: function(result) {
for (var i = 0; i < result.length; i++) {
(function (n) {
var obj = result[i],
element = $("<input>", {type: "checkbox"});
element.click(function () {
getPointMap(obj);
});
$(document.body).append(element, obj.address + "<br />");
})(i)
}
}
});
Ok, simple way:
html += "<input type='checkbox' onClick='getPointOnMap(" + obj.lattitude + ", " + obj.longtitude + ")'/>" + obj.address + "<br>";
function getPointOnMap(lat,lng) {
map.addMarker({
lat: lat,
lng: lng,
click: function(e) {
alert('You clicked in this marker');
}
});
}
$.ajax({
type: "POST",
url: "/getResult.json",
success: function(result) {
var myDiv = $('#myDiv');
$.each(result, function(i, obj) {
myDiv.append(
$('<INPUT>').attr('type', 'checkbox').on('click', function() {
getPointOnMap(obj);
},
obj.address,
"<br>"
);
});
}
});
Related
I want to know how to bind dropdownlist using ajax get. This is the code, What is wrong?
$("#dropdown").on("click",
function ()
{
$.ajax(
{
url: '#Url.Action("List", "Employee")',
type: "POST",
data: $("#dropdown").serialize(),
success: function (data) {
var org = '<option>Select Organisation </option>';
for (var i = 0; i < data.length; i++) {
org += '<option value="' + data[i].organisationid + '">' +
data[i].organisationname + '</option>';
}
$("#dropdown").html(org);
}
});
I am able to display out all the details including the button. However, the main problem is that the when I click the button, nothing happens. It says that BtnRemoveAdmin() is not defined when I inspect for errors. However, I have function BtnRemoveAdmin()?? I have tried to move the function to htmlstring. Nothing works. I am not sure what went wrong.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role,
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
for (var i = 0; i < arr.length; i++) {
htmlstring = '<div class="grid-container">' +
'<div>' + arr[i].userid + '</div>' +
'<div>' + arr[i].employeename + '</div>' +
'<div>' + arr[i].role + '</div>' +
'<div>' + '<button onclick="BtnRemoveAdmin()">Remove</button>' + // 'BtnRemoveAdmin' is not defined
'</div>' ;
$("#name").append(htmlstring);
}
function BtnRemoveAdmin() {
var data = event.data;
removeadmin(data.id);
}
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
All your code is defined inside an IIFE.
That includes BtnRemoveAdmin.
When you generate your JavaScript as a string, it is evaled in a different scope.
BtnRemoveAdmin does not exist in that scope.
Don't generate your HTML by mashing strings together.
Use DOM instead.
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
I use JQuery, and sometimes I get the same problem with plain JS functions not being called.
So I create JQuery functions :
$.fn.extend({
btnRemoveAdmin: function() {
...//Do what you want here
}
});
To call it use :
<button onclick="$().btnRemoveAdmin();"></button>
Hope it helps you !
this is my code to change the drop down list values when the checkbox is checked. I use asp.net mvc framework and java script to call the action. The list of the drop-down should show only the expired medicines when the checkbox is checked. But, it results in (Error: [object:object]). It didn't hit the controller action 'getmedicine'. Can anyone help me?
function GetMedicineList(_isExp) {
var url = "getmedicine";
$.ajax({
url: url,
data: { IsExp: _isExp },
cache: false,
type: "GET",
dataType: "json",
success: function (data) {
var markup = "<option value='0'>Please Select Expired Medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#clientId").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
and in the view,
#Html.CheckBoxFor(m => m.IsExp, new { Id = "isExp", #onchange = "GetMedicineList(this.value);" })
I solved the problem. One error is the action that I use to trigger is not an action result. It is a list. I changed it. I also I have did some changes in js. It works properly now.
var GetMedicine= function () {
var url = UrlMedicine.GetMedicineChecked;
var isExp = $('#isExp').val();
var url = url + '?isExp=' + isExp;
$.get(url, null, function (data) {
{
var markup = "<option value='0'>Please Select Expird medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#medicineId").html(markup).show();
}
});
}
var GetMedicineList = function () {
if ($('#isExp').is(":checked")) {
userMedicineHistory.GetMedicine();
}
}
return {
GetMedicineList: GetMedicineList,
GetMedicine: GetMedicine
};
$(document).ready(function () {
$("#isExp").change(userMedicineHistory.GetMedicineList)
});
I don't want to parse all title from the list. I only want the first title to be parsed. Any suggestion?
function parseRSS(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
$.each(data.responseData.feed.entries, function(key, value){
var thehtml = '<h3>'+capitaliseFeed(value.title)+'</h3>';
$(container).append(thehtml);
});
}
});
}
function capitaliseFeed(string) {
return string.toUpperCase();
}
Instead of $.each you could loop the data and keep only the first entry
for (var i = 0; i < data.responseData.feed.entries.length; i++) {
var entry = data.responseData.feed.entries[i];
var thehtml = '<h3>'+capitaliseFeed(entry.title)+'</h3>';
$(container).append(thehtml);
break;
}
Probably a simple fix, The rest of the table is sorted excpet this part here
(right at the top)
The table will work now and again in the right order (data from source does not change) but is really dicey when it does or not
Ideas?
Sam
Heres the code
//first define a function
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(3)").text().trim();
var dataB = $(b).find("td:eq(3)").text().trim();
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url1',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tr ><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url2',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
The sorting as to do with spaces but is also linked to your jquery selector.
As often, array are 0 index based in Jquery, then if you want to sort on your price your 2nd column (0-index based) you need to do as below :
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(2)").text().replace(/\s/g, "");
var dataB = $(b).find("td:eq(2)").text().replace(/\s/g, "");
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
var json = {results:[{price:"$12 .45"}, {price:"$13 .45"}, {price:"$12 .05"}, ]}
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
$("#tableid").append("<tr ><td>section</td><td>no</td><td>" + price);
}
sortTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableid"></table>
`