Using jQuery I'm trying to get the id of control, which I clicked (radiobutton). I read this question and tried almost everything from there:
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
But I'm always getting: Undefined
I just don't understand what I'm doing wrong.
UPDATED:
Radiobuttons is generated dynamically in code behind by C#:
controlToReturn = new RadioButton
{
ID = controlId
};
((RadioButton)controlToReturn).Text = text;
((RadioButton)controlToReturn).Checked = Convert.ToBoolean(Convert.ToInt32(value));
((RadioButton)controlToReturn).GroupName = groupName;
((RadioButton)controlToReturn).CssClass = cssClass;
((RadioButton)controlToReturn).Attributes.Add("runat", "server");
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show();");
and function in ASPX:
<script type="text/javascript" language="javascript">
function Show() {
if ($(this).cheked = true) {
console.log(this);
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
}
}
</script>
I know radiobutton has id, I checked generated HTML.
Your problem is this has no context within your function and is in fact the window itself.
You would need to modify both the output html to provide context as an argument:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
and change the function Show:
function Show(el) {
/* for jQuery use $(el) */
if(el.checked) {
alert(el.id);
}
}
C#:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
JavaScript:
function Show(radio) {
if (radio.checked) {
alert(radio.id);
}
}
To attach a click-listener and alert the ID, your code would look something like this:
$(function () {
$("input[type='radio']").on("click", function () {
alert(this.id);
});
});
A working demo: http://jsfiddle.net/SSBnV/1/
Related
Hello i am failing to pass the value from dropdownlist in the parent aspx form to textbox in the child aspx form
Parent javascript
: The First script is to open the popup window
<script type="text/javascript">
var popup;
function NewCustOpn() {
popup = window.open("NewCustomer.aspx","Popup",toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
</script>
This is the second script on the parent page to get the value of the dropdownlist
<script type = "text/javascript">
function parentFunc()
{
return document.getElementById ("<%=DropDownList1.ClientID%>").value;
}
</script>
The child page javascript:
<script type = "text/javascript">
window.onload = function ()
{
if(window.opener != null && !window.opener.closed)
{
var val = window.opener.parentFunc();
var textbox = document.getElementById("<%=TextBox1.ClientID%>");
textbox.Value = val;
}
}
</script>
When the popup opens TextBox1 is empty.
Your problem is simple. Just replace the below line from your child page's js function
textbox.Value = val;
to
textbox.value = val; // lowercase "v"
or justdo a direct assignment like this
document.getElementById("<%=TextBox1.ClientID%>").value = val;
Or another possible solution would be to directly pass the required value from the parent page as a querystring value and you don't need the js function in the popup page. The querystring value you can access it in child pages's page load event and assign it directly to the textbox.
Your Parent js
function NewCustOpn() {
var ddlvalue = document.getElementById("<%=DropDownList1.ClientID%>").value;
var popup = window.open("Popup.aspx?dropdownval=" + ddlvalue, "Popup", "toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
And from you child page's code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["dropdownval"])) {
TextBox1.Text = Request.QueryString["dropdownval"];
}
}
Trying to pass value (abc) from code-behind to JavaScript but the page fails and doesn't load. Is there something wrong with the syntax? I've noticed that normally the <%...%> is highlighted yellow but this is not the case in my code.
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() { });
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = "<%=Variable_codebehind %>";
}
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = "hello world";
}
Error from logfile:
Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
first bind the value to a hidden control
then get the value from the hidden control
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = <%=Variable_codebehind %>;
}
});
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = HttpUtility.JavaScriptStringEncode("hello world", true);
}
You can use Page.RegisterStartupScript and pass some variables from Code-Behind. Place the script in a .js file and call it on OnLoad method from the code-behind:
OnLoad CodeBehind:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", String.Format("MyScript({0});", codeBehindVar));
MyScript.js
function MyScript(myVar)
{
var self = this;
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = self.myVar;
}
}
I'm currently working with the AJAX:UpdatePanelAnimationExtender and I've implemented it in code behind which is currently working perfectly but I've ran into a problem with using the UpdatePanelAnimationExtender and an ASP:Repeater. I've been messing around with different ways of implementing it but nothing has worked correctly...
I've tried to have it written in codebehind - inside itemBound (generates the code perfectly, is attached to the UPAE but of course is dropped on partial postback).
I've also attempted using it in the aspx which also posed a problem.
The repeater itself is creating a table of items (a cart) and I am attempting to highlight items that have changed when a postback happens (highlight qty if the qty changes, etc).
I've read that jquery has a much cleaner way of doing this and am attempting to go that direction.
edit:
I'm currently looking at
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
changedHighlight();
}
function EndRequestHandler(sender, args){
if (args.get_error() == undefined){ changedHighlight(); }
}
function changedHighlight() {
$(document).ready(function() {
$('span,input,option,select').live('change', function() { $(this).effect("highlight", {color: "#44EE22"}, 1500); });
});
}
I'd have to compare a stored value for it to the new posted value, which I'm working on right now. Also 'change' doesn't appear to work on asp:labels?
Ended up using a global var (eh..) due to the issue of postback with the UpdatePanel and DOM recreation every time (meaning not able to use $.data() or this.data()).
Will only highlight non-submit inputs and DOM elements that have an ID. (otherwise static asp:labels will continue to flash)
var oldVar = [];
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args) {
$(document).ready(function() {
oldVar = [];
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '') oldVar[this.id] = getValue(this);
});
});
}
function EndRequestHandler(sender, args){
$(document).ready(function() {
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '')
{
if (oldVar[this.id] != getValue(this))
{
$(this).effect('highlight', {color: '#44EE22'}, 3000);
oldVar[this.id] = getValue(this);
}
}
});
});
}
function getValue(control){
if ('value' in control) return control.value;
else if('textContent' in control) return control.textContent;
else if('innerText' in control) return control.innerText;
}
i'm using the below javascript to change an image on an aspx in asp.net c#
<script language="JavaScript" type="text/javascript">
var updateImageWhenHashChanges = function()
{
theImage = document.getElementById("ctl00_ContentPlaceHolder1_Image1a");
if(window.location.hash == "#size=2")
{
theImage.src = "<%# Eval("realfilename", "/files/l{0}") %>";
}
else if(window.location.hash == "#size=3")
{
theImage.src = "<%# Eval("realfilename", "/files/{0}") %>";
}
else if(window.location.hash == "#size=1")
{
theImage.src = "<%# Eval("fullthumbname", "/thumbnails/{0}") %>";
}
else
{
}
}
</script>
here's how i call it with a link
test
the problem is that it only does what i'm expecting on the SECOND click of the link, because it seems onclick fires before the href, so the first time i'm just placing the var and the 2nd time i'm actually getting what i want.
does anyone know how i can fix this? i'm trying to get the image to change on each click
Perhaps you can replace your href with javascript:void(0) and then handle the link's "natural" click behavior at the end of your onclick() script.
Have you tried a different event like onmouseup or onunload?
You should pass in the current anchor's href to the function call and then use that in your if statements, then return false so that the default behavior isn't used.
var updateImageWhenHashChanges = function(pChoice)
{
theImage = document.getElementById("ctl00_ContentPlaceHolder1_Image1a");
if(pChoice == "size2")
{
// more lines of picking and choosing... and finally:
return false;
and then in the anchor
test
It would also be much better if you could use your databinding to put the real href of the image into the href of the anchor so that if JavaScript wasn't enable the user would still end up being able to see the image in question. Then your function code would just be getting a handle to the image and setting the source to that inbound param.
What about something like this:
<script type="text/javascript">
var updateImageSize = function(imageType, imageID)
{
thisImage = document.getElementById(imageID);
switch(imageType)
{
case "thumb":
// change image src to the thumbnail's path
thisImage.src = "YourThumbNailPath";
case "medium":
// change image src to medium image path
thisImage.src = "YourMediumImagePath";
case "large":
// you get the picture
thisImage.src = "YourLargeImagePath";
default:
// whatever you want it to default to
thisImage.src = "YourThumbNailPath";
}
}
</script>
Then the implementation:
Update Image
Hope that helps.
So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command