I need to set CSS values in the ready function below.
$(document).ready(function ()
{
$("<div id='" + 1 + "' class='box'></div>").css("left", 105).css("top", 54).appendTo("#center").draggable();
$("<input type='text'></input>").appendTo("#" + 1);
}
It works fine, then it create a textbox within a draggable div and place them at top:54 and left 105. Now I need to get X,Y from server query, and I've tried this:
$(document).ready(function ()
{
$.ajax({
type: "POST",
url: "Default.aspx/Get",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
var singleControls = msg.d.split('.');
$.each(singleControls, function (key, value)
{
var singleParameters = value.split(',');
if (singleParameters[0] != "")
{
var ids = singleParameters[0];
var type = singleParameters[1];
var cordX = singleParameters[2];
var cordY = singleParameters[3];
var container = $("#center").position();
var x_Coord = cordX - container.left;
var y_Coord = cordY - container.top;
$("<div id='" + ids + "' class='box'></div>").css("left", cordX).css("top", cordY).appendTo("#center").draggable();
$("<input type='text'></input>").appendTo("#" + ids);
}
});
}
});
Where Get() returns X,Y, with this it creates the div, but it places it at 0,0.
Can someone please explain why this isn't working?
sample: https://skydrive.live.com/redir.aspx?cid=d7fc3da7fdbc700d&resid=D7FC3DA7FDBC700D!302&parid=D7FC3DA7FDBC700D!301
if you are hard coding the left and top styles, then why not add them to the .box style in your style sheet like so
.box{
position:absolute;
left:105px;
top:54px;
}
otherwise the css function should look like the following:
.css({
position:'absolute',
left:'105px',
top:'54px',
});
here is a jsfiddle.net example
Related
Hi i am trying to navigate through anchor link. Only the first link works. For example if i click a link in a page it goes to that link, but when there is another link in page whcih i have clicked it doesnt work. And also the second has the same class 1st link Please help.
$('#frmDisplay').on('load', function () {
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
public static string getlink(int Id)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
string link = "extlink";
BookTree obj = new BookTree();
DataSet ds = obj.getlink(Id);
SqlCommand cmd=new SqlCommand("select vcFilePath from tblBookNodes where iModuleId='" + Id + "'",conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
bytes = (byte[])dr["vcFilePath"];
}
string fileName = link.Replace(" ", "_") + ".htm";
// DirectoryInfo strPath = new DirectoryInfo(HttpContext.Current.Server.MapPath(#"~/Linking/"));
//string strPath = HttpContext.Current.Server.MapPath(#"/Linking/") + fileName;
//foreach (FileInfo file in strPath.GetFiles())
//{
// file.Delete();
//}
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/htmlFile/"), fileName);
var doc = new HtmlDocument();
string html = Encoding.UTF8.GetString(bytes);
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
StreamWriter sWriter = new StreamWriter(path);
sWriter.Write(sw.ToString());
doc.Save(sWriter);
sWriter.Close();
//string fileContents = html;
//System.IO.File.WriteAllText(path, html);
return File.ReadAllText(path);
}
You have to use "on" instead of find() and event listener attach.
Please refer to this example:
$('#formDisplay a.anchroLink').on('click', function() {
// TODO: handle the click
})
This is necessary because when you add the event listener the DOM is not yet ready to handle requests for non existing content. Using "on" you can attach an event to a class or a simple DOM query.
To be more clear I post your code with modifications based on my previous suggestion:
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d)
},
error: function (response) {
alert(response.responseText);
}
});
});
My last answer (I don't know you were using iFrames):
function clickHandler() {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
// You can reload the event handler because the prev one
// has been lost after refreshing the page with the ajax call.
$('#frmDisplay').contents()
.find('a.anchorLink')
.click(clickHandler);
},
error: function (response) {
alert(response.responseText);
}
});
}
$('#frmDisplay').on('load', function () {
$('#frmDisplay')
.contents()
.find('a.anchorLink')
.on('click', clickHandler);
})
good evening,
j tries to retrieve the data from the user but the problem iç that i can not handle the coords because of "," longitude and latitude, i do not know how to treat these give, i tried with parsefloat but without result, thank you
code controller action :
public ActionResult GetNeaarByLocations(string CurrentLat, string CurrentLng)
{
using (GeolocationTestEntities context = new GeolocationTestEntities ())
{
var CurrentLocation = DbGeography.FromText("POINT(" + CurrentLat + " " + CurrentLng + ")");
//var CurrentLocation = DbGeography.FromText("POINT(36,806494799999996 10,181531600000001)");
var places = (from u in context.schoolinfo orderby u.Location.Distance(CurrentLocation)
select u).Take(4).Select(x=>new schoollinfo(){ Name = x.name ,Lat = x.Location.Latitude, Lng = x.Location.Longitude,Distance = x.Location.Distance(CurrentLocation)});
var nearschools = places.ToList();
return Json(nearschools , JsonRequestBehavior.AllowGet);
}
}
and this is code Ajax :
jQuery.ajax({
cache: false,
type: "POST",
url: "#Url.Action("GetNeaarByLocations")",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ CurrentLng:currentLatLng.longitude, CurrentLat: currentLatLng.latitude }),
success: function (data) {
if (data != undefined) {
$.each(data, function (i, item) {
addMarker(item["lat"], item["lng"], "Click to get directions");
})
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
thanks all.
we need to convert lng & lant to double
var currentLatLng = position.coords;
var Lat = currentLatLng.latitude;
var Lng = currentLatLng.longitude;
var LatDouble = parseFloat(Lat);
var LngDouble = parseFloat(Lng);
for Ajax is to delete att stringify
data: JSON({ CurrentLng:LngDouble , CurrentLat: LatDouble }),
I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},
Hi I have this code below
How could I pass preferably 1 array which will contain an ID number and a value from a textbox which is dynamically generated and then passed to the backend to C#
var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
listoftextboxesWithID[i] = value.ID.toString();
listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
i++;
});
//---Till here the data in the above arrays is as expected, the problem starts below in the data :
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
[WebMethod]
public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity,
string supplier, float vatRate, int colorID, int brandID, string imagePath, string[] listOfTextBoxesID, string[] listOfTextBoxesValues )
{
Product p = new Product();
ProductPriceType ppt = new ProductPriceType();
p.CategoryID = subCategoryID;
p.Name = name;
p.Description = description;
p.Quantity = quantity;
p.Supplier = supplier;
// p.VATRate = vatRate;
p.ColorID = colorID;
p.BrandID = brandID;
p.Image = imagePath;
//...
}
Any help would be much appreciated
if I will do it, my approach is to seperate those two,
create string array for texts
create string array for values
i believe that the number of values will be the same with texts since it is generated dynamically.
then pass those two string arrays in c# backend.
you can use json2.js is cool ,I used this
var valueObj = { field1: $("input[name=field1]").val(),
field2: $("input[name=field2]").val()}
and then I can parse with this:
JSON.stringify(valueObj)
in the ajax call you can use like this
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data:valueObj ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
//In JS file
var arr = [];
arr.push( $("#textZipcode").val());
arr.push( $("#textPhone").val());
arr.push($("#textAddress").val());
arr.push( $("#textMobile").val());
//You can add any number. It will store to array properly.
$.ajax({
type: "POST",
url: "HomePage.aspx/SaveData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({arr:arr}),
success: function (response) {
}});
//In C#
[WebMethod]
public static void SaveData(string[] arr)
{
}
I have the following code which will store coordinate positions of the div whenever it is moved. The positions are stored into database so that when user returns, it remains there. The following code works somewhat similar to that. But the positions are not accurately maintained when I do two – three movements.
Note: I think the problem is following lines of code
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
Note: I am getting the error "Microsoft JScript runtime error: 'absolutePosition.left' is null or not an object" when I use var absolutePositionLeft = ui.absolutePosition.left;
Can you please suggest how to overcome this?
The code:
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=dImage.ClientID%>").draggable(
{
drag: function (event, ui) {
//when dragging
$("#<%=dImage.ClientID%>").css("opacity", "0.3");
},
stop: function (event, ui) {
//when stopped
//showAlert();
debugger;
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
var elementName = ui.helper.attr('id');
saveCoords(absolutePositionLeft, absolutePositionTop, elementName);
$("#<%=dImage.ClientID%>").css("opacity", "1.0");
},
cursor: "move"
});
});
function showAlert()
{
alert("hai");
}
function saveCoords(x, y, el, id)
{
$.ajax({
type: "POST",
url: "GridViewHighlightTEST.aspx/SaveCoords",
data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
if (response.d != '1')
{
alert('Not Saved!');
}
},
error: function (response)
{
alert(response.responseText);
}
});
}
</script>
And the C# Code is
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = GetSavedCoords(1);
foreach (DataRow row in dt.Rows)
{
string elementName = row["element"].ToString();
System.Web.UI.HtmlControls.HtmlControl theControlElement = (HtmlControl)this.FindControl(elementName);
if (theControlElement != null)
{
theControlElement.Style.Add("left", row["xPos"].ToString() + "px");
theControlElement.Style.Add("top", row["yPos"].ToString() + "px");
}
}
}
I believe your problem is that
var stopPositions = $(this).position();
should be
var stopPositions = $(event.target).position();
In any case, it's extremely useful to use a JavaScript debugger, it will keep you sane. If you are using Chrome or IE use F12 to get to developer tools. If you're using Firefox get Firebug.
Using one of these tools can help you quickly verify what this actually is which, depending on the frameworks your using, can quickly get confusing. A debugger can also help you verify your DOM and code flow.