div value is undefined in jQuery - javascript

I have one div in which the value is added dynamically using asp.net code behind. I want to use this value in my jQuery code but the alerts shows the value as undefined. The div displays dynamic dates like this:
<div id="test" runat="server"></div>
protected void dpchange_SelectedIndexChanged(object sender, EventArgs e)
{
test.InnerHtml = Label1.Text;
}
Here is the jQuery code in which I am trying to access the value
$('#addDialog').dialog({
autoOpen: false,
width: 470,
buttons: {
"Add": function() {
alert($("#test").text());
alert($("#test").html());
alert($("#test").val());
var eventToAdd = {
};

Assuming you are using ASP.Net,
you can specify ClientID property on div to be Static so that ID won't change during runtime.
<div id="test" runat="server" clientidmode="Static"></div>
Another way is to use below syntax
alert($('[id$=test]').text());
alert($('[id$=test]').html());
alert($('[id$=test]').val());
If your jQuery is on same aspx page, you can also use inline service-side markup.
alert($('#<%= test.ClientID %>').html());

Related

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

code behind c# - javascript - google map

help! I have a google map in the master page , moving the map I get the coordinates then
Click asp button through javascript I would update the data in the page content in the code behind c # . this works but it only works the first time , by moving the map again , the button is not clicked more
 this code:
page.aspx
Please wait ...
<asp:Button ID="MapTrigger" name="MapTrigger" runat="server" OnClick="MapTrigger_Click" style="display:none;" />
javascript:
function OnSuccess(resul_param) {
if (resul_param) {
document.getElementById("currentDate").innerHTML = resul_param[0];
var clickButton = document.getElementById("<%=MapTrigger.ClientID %>");
$('clickButton').trigger('click');
}
code behind c#.
protected void MapTrigger_Click(object sender, EventArgs e)
{
.....
}
I solved this way. I have made ​​visible to the entire page ( MasterPage + aspx) button with a global function that I put at the beginning of the aspx page immediately after the tag Content
function InitializeVariables() {
var MapTrigger = null;
if (MapTrigger == null) {
MapTrigger = document.getElementById("");
MapTrigger.click();
}
}
now works perfectly.

Replacing widget element with a newly constructed DOM structure

<script>
(function( $ ) {
$.widget( "my.dropbox", {
errorText: function(text) {
$(this.element).next().html(text);
},
_create: function() {
var id = $(this.element).attr("id");
var customDropbox = $(
"<div class='form-group'>"+
"<label for='"+id+"'>"+getLabelFor(id)+"</label>"+
"<select id='"+id+"'></select>"+
"<div class='errors'></div>"+
"</div>"
);
customDropbox.attr("id", id);
$(this.element).replaceWith(customDropbox); // This removes original element from DOM
populateOptions(id);
},
});
}( jQuery ));
$(document).ready(function(){
$("#field1").dropbox(); //blank input field turns into a select with a label, populated options e.t.c..
$("#button1").on("click", function(){
$("#field1").dropbox("errorText", "This is a validation error message"); //throws an error saying dropbox is not initialized
});
});
</script>
<html>
<body>
<input id="field1" />
<button id="button1">Press me</button>
</body>
</html>
So I want a widget with public methods that will replace the original element with all the widget data associated with it. The problem with the above code is that the <select..> element is just a DOM element and if you call .dropbox(..) on it, it will say the widget is not initialized. Is there a way to make the select element into the widget object with the .errorText() method? All widget examples online add stuff around the original element but never replace it. As for the bigger picture, I'm trying to make a generic tool to configure forms dynamically. It's going to be all <input id="..."> in html but then javascript will query a database, get configuration for the field and turn it into a dropbox, checkbox or, say, a date picker with all the labels, validation, and other bells and whistles.
There is more than one issue with your widget code. I'll try to summarize them:
1. Copy the data
You're not copying the data to the newly created customDropbox, so before
this.element.replaceWith(customDropbox);
you should copy the data:
customDropbox.data(this.element.data());
Now the widget will remember that it was initialized.
2. this.element is gone
After
this.element.replaceWith(customDropbox);
you should update this.element so that it points to the newly created customDropbox:
this.element = customDropbox;
3. errorText message takes wrong element
Since the widgets element (this.element) is now pointing to the <div class='form-group'></div> element, the errorText function must be slightly modified to:
this.element.find(".errors").html(text);
4. id should be unique
Now, both the wrapper <div> and the <select> have the same id, which is not allowed in HTML so remove the one on the <select> tag. Luckily, <label> can work without the for attribute, just write it like this:
<label>labelForId <select></select></label>
Then to get the <select>-element, use this.element.find("select") in the widget.
Side note
`this.element` is already a jQuery element, so no need for the additional `$()` wrapping.
See this jsFiddle
function show(){
$("#field1").input({....});
}
function hide(){
$("#field1").input("hide");
}
<button onclick="show()">show</button>
<button onclick="hide()">hide</button>
i think to replace the origin element which initial dropbox() is not a good solution,
because this will force you to rely on the implemention details of jQuery ui factory,
it is easy to make a mistake or introduce bugs, sometimes harder for other people to understand your code
if jquery ui factory change the implemention in the future, you have to modify all your code to make it work
(sorry for my limit understand of jquery ui)
i think we can put the <input/> into a container and initial dropbox() on the container which inturn
replace <input/> with <select> datepicker ..etc.. we can build modules easily by doing so:
<form>
<div class="dropbox"><label for="someID">aaaaaa</label><input id="someID"/></div>
<div class="datepicker"></div>
<div class="othermodule"></div>
</form>
js:
$(".dropbox").dropbox(); // init dropbox you defined
$(".datepicker").datepicker(); // ...
$(".othermodule").othermodule(); // ...
$(".dropbox").dropbox("errorText", "error"); // invoke it smoothly
here is a simple demo: http://jsfiddle.net/m4A3D/
#Wouter Huysentruit's answer provides a list of good suggestion for me
<form>
<div class="dropbox">
<label for="someID">aaaaaa</label>
<input id="someID"/>
</div>
<div class="datepicker"></div>
<div class="othermodule"></div>
</form>
<button id="button1">Press me</button>
<script>
(function ($){
$.widget("my.dropbox", {
_create: function () {
var $input = this.element.find("input");
var sID = $input.attr("id");
var $select = $("<select>");
$select.attr("id", sID);
$input.replaceWith($select);
this.element.append("<div class='errors'></div>");
}, // end _create()
errorText: function (text) {
this.element.find(".errors").text(text);
} // end errorText()
});
}(jQuery));
$(".dropbox").dropbox();
$("#button1").click(function () {
$(".dropbox").dropbox("errorText", "this is error");
});
</script>

Label won't show when label hidden via page load

The desired effect is that on page load the label does not display but when the user clicks the check box the label displays. This small code sample is just a sample to illustrate the issue. The code will always return an object reference exception from javascript when the Visible property of the label is set to false. If that line is commented out, it will execute correctly with no object reference exceptions but the label should be hidden at page load. This application does use master pages which is why were are passing the ClientIDs to the javascript Toggle function.
protected void Page_Load(object sender, EventArgs e)
{
this.chkSelect.Attributes.Add("onClick", "Toggle('" + this.lblAdd.ClientID + "', '" + this.chkSelect.ClientID + "')");
this.lblAdd.Visible = false;
}
<script type="text/javascript">
function Toggle(lblAdd, chk) {
var ctrlAdd = document.getElementById(lblAdd);
var ctrlChk = document.getElementById(chk);
if (ctrlChk.checked == true) {
ctrlAdd.style.display = 'inline';
}
else {
ctrlAdd.style.display = 'none';
}
}
</script>
<asp:Label ID="lblAdd" runat="server" Text="Add" Font-Size="8pt" ForeColor="Blue"> </asp:Label>
<asp:CheckBox ID="chkSelect" runat="server" Text="Check Box1" /><br />
How can we hide that label in Page_Load so we don't get object reference errors from Internet Explorer?
Thanks...
the Visible property does not render the HTML if set to false, that's why you get a null reference (in other words, ASP.NET's Visible is nothing to do with the display CSS property - it actually toggles whether an element is rendered in the HTML code or not.). Instead assign a CSS class on page load that defines display: none, then remove that class on click with javascript

When selecting a value from DropDownList a second time. It doesn't use newly selected value. It uses the old values

I have a div called "ddlFiles". It contains a DropDownList that has a bunch of id's in it. What I am trying to do is get a user to select an id then perform an operation by passing in the selected value.(stored proc needs it) The operation works the first time through. But when I try to select an id again, it uses the old id instead of the new one. So for me to pass in the correct id, I have to get the user to select a new id twice, before it actually takes the second new id.
(NOTE: viewExpensesGrid is the my flexigrid)-not really useful but I thought I'd add it in.
This is my function for getting the selected value from the DropDownList which then passes it to a function:
function getCaseFiles(canMoveExpenses) {
//create Popup with content from div
$('#ddlFiles').dialog({
autoOpen: true,
height: 'auto',
width: 'auto',
modal: true,
buttons: {
"Ok": function () {
var dropDownList = document.getElementById("ddlCaseFilesNew");
var newCaseDdl = dropDownList.options[dropDownList.selectedIndex].value;
//alert("newCaseDdl = " + newCaseDdl);
var oldCaseFile = $("#hidCaseFile").val();
//alert(oldCaseFile);
if (newCaseDdl != -1) {
moveCasefile(canMoveExpenses, newCaseDdl, oldCaseFile);
$(this).dialog('close');
$("#viewExpensesGrid").flexReload();//simply refresh flexigrid
}
else {
showMessage("Error. Please Select a Value From The Lists.");
}
},
Cancel: function () {
$(this).dialog('close');
$("#viewExpensesGrid").flexReload();
}
}
});
}
And here is my div = "ddlFiles":
<div id="ddlFiles">
<label>
Select new CaseFile:</label>
<asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
DataTextField="Display" DataValueField="FileID"
OnPreRender="ddl_PreRender" Width="300px"/>
</div>
My stored procedure requires a new CaseId and an old CaseId, the hidCaseFile is a hiddenField. (this already contains the old file ID.
Try changing this:
var dropDownList = document.getElementById("ddlCaseFilesNew");
with this
var dropDownList = $("#<%= ddlCaseFilesNew.ClientID %>");
When executing, server controls have an Id that is different from the one specified in the ID tag, so you should get it using its ClientID wich is not "ddlCaseFilesNew".

Categories

Resources