jQuery event binding issues with radio buttons - c#

I'm trying to get jQuery to bind an onClick function when the document loads to my radio buttons.
ASP goes back to the database and finds all the open markers and then it sends a response to the page with the raw HTML to make a radio button and an image of the marker. What I need to do is have jQuery (or anything for that matter) bind an onClick that will signal what one is clicked so I can send that markerId back to the database to attach it to a person.
Here is a rough jsFiddle of what I've tried so far. In debugging I added alerts in the each function and I see them 3x like I should but the attr('id') comes back undefined.
This is the html that puts the radio buttons on the form
<br />
<p>Select open marker for new user:
<% getMarkers(); %>
</p>
This is the codebehind for that call
while (reader.Read())
{
if (readIndex % 3 == 0)
markerTable += "<tr>";
string markerId = reader["marker_id"].ToString();
string fileName = reader["marker_filename"].ToString();
markerTable += "<td><input type=\"radio\" name=\"openMarker\" value=\"" + markerId + "\" " +
"id=\"oMrk" + markerId + "\"><label for=\"oMrk" + markerId + "\"><img src=\"/Markers/" +
fileName + "\" /></label></input></td>";
readIndex++;
if (readIndex % 3 == 0)
markerTable += "</tr>";
}
if (readIndex % 3 != 0)
markerTable += "</tr>";
markerTable += "</table>";
}
else
markerTable = "<p>No empty markers. Please delete a user to continue.</p>";
sCon.Close();
return markerTable;
The fiddle I posted has the source pasted into it from this function.
I have two questions.
Why does this not work? It seems like it should, I am getting 3 elements from my jQuery selector statement, It's being called from $(document).ready() why are the attributes undefined?
Is there a better way to do this? I was planning on putting the value in a page variable and then sending it with an ASP button back to the server to a stored procedure to add that marker with some text from another field back to the database. I realize I could add the onClick event into the response html, but dang it I need to understand why what I'm doing isn't working.
I'm pretty new to web, so if I am way off the mark procedurally, I am open for suggestion.

LINK
$(document).ready(function () {
$('input:radio').each(function (radElem) {
var radId = $(this).attr('id');
alert(radId);
});
$('input:radio').on('click', function () {
alert('Clicked');
});
});

$(document).ready(function () {
$('input:radio').on('click', function() {
alert($(this).attr('id'));
});
});
Do you need to send the value to the server while staying on the page? (via ajax)
or do you need to post the form to another page?

It doesn't work because you are trying to bind onClick instead of
just click
The other answers have provided the jQuery for you. In the each you
just need to use this keyword
I tested this in a fiddle, it works. Others have provided similar answers, but here's the fiddle anyway: THE FIDDLE
$(document).ready(function () {
$("input:radio").each(function () {
var radId = $(this).attr('id');
alert(radId);
$(this).on('click', function () {
alert('Clicked');
});
});
});
As for a better way to do what you are trying to accomplish, I do not have a firm grasp of what you are trying to do really, sorry. It feels though, like you should be initially populating this in asp.net, but the constraints of your page may not make this possible. I can't say.
Also, go ahead and pick one of the previous answers, I just wanted to explain to you why what you had wasn't working.

Related

How can I add jQuery to a WebPart (to respond to certain events on the WebPart)?

I started down the path of adding an UpdatePanel to my Sharepoint page so that I can respond to events that take place (such as the checking of checkboxes and mashing of radio buttons, etc.). That so far has, however, been wrought with frustration and all that rot, as can be deduced from this question.
So I'm now probably going to traverse (no pun intended) the jQuery route and am trying to figure out/find out how to add jQuery to a WebPart.
Currenlty, I am dynamically creating controls in C# based on what a user selects in the WebPart's Editor (if they elect to show Section 1, I create all the controls for Section 1, etc.).
As an example, I'm currently conditionally creating a RadioButton in C# like so:
var radbtnEmployeeQ = new RadioButton
{
CssClass = "dplatypus-webform-field-input"
};
Now if I want to add jQuery to it, I can add an ID to it like so:
var radbtnEmployeeQ = new RadioButton
{
CssClass = "dplatypus-webform-field-input",
ID = "radbtnEmp"
};
...and then add jQuery of this nature (pseudocode):
$('radbtnEmp').click {
// visiblize/invisiblize other controls, assign certain vals to their properties
}
This seems feasible to me, but how do I go about adding jQuery to a WebPart? Is it a matter of adding a .js file at the same directory level as the *.ascx.cs file, and then referencing it from the *.ascx.cs file, or...???
UPDATE
For POC testing, I added a file to my project named "directpaydynamic.js" with this content:
<script>
$(document).ready(function () {
$('input:radio[name=radbtnEmp]:checked').change(function () {
if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
alert("radbtnEmp checked");
}
else {
alert("radbtnEmp not checked");
}
});
});
</script>
(derived from an example here)
...and reference the .js file in my *.ascx.cs file like so:
SPWeb site = SPContext.Current.Web;
site.CustomJavaScriptFileUrl = #"C:\Projects\DirectPaymentWebForm\DirectPaymentSectionsWebPart\DPSVisualWebPart\directpaydynamic.js";
(I dragged the .js file onto the code to get the path)
However, running the solution and mashing the radiobutton causes neither alert() to display, so I reckon I've taken the road that was for a good reason less traveled.
UPDATE 2
Realizing I didn't need the script business (as this is a .js file, not an html file), I removed those, and also put an "at any rate" alert() in the jQuery:
$(document).ready(function () {
alert("What's new, pussycat, whoa-oh-oh-oh-OH-oh?");
$('input:radio[name=radbtnEmp]:checked').change(function () {
if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
alert("radbtnEmp checked");
}
else {
alert("radbtnEmp not checked");
}
});
});
...but I still endure an alarming dearth of alerts...
Use below code on Page load method
string url = SPContext.Current.Site.ServerRelativeUrl;
if (!url.EndsWith("/"))
{
url += "/";
}
HtmlGenericControl styleCss = new HtmlGenericControl("link");
styleCss.Attributes.Add("rel", "stylesheet");
styleCss.Attributes.Add("type", "text/css");
styleCss.Attributes.Add("href", url + "Style Library/css/style.css");
HtmlGenericControl JsLink = new HtmlGenericControl("script");
JsLink.Attributes.Add("src", url + "Style Library/js/jquery.min.js");`enter code here`
this.Controls.Add(styleCss);
this.Controls.Add(JsLink);
The thing to do (or perhaps I should write, "a" thing to do) to get this to work is to add code like the following to the end of the WebPart's *.ascx file:
<script>
$(document).ready(function () {
alert("The ready function has been reached");
});
$(document).on("change", '[id$=ckbxEmp]', function () {
alert('Function has been reached');
if ($(this).is(":checked")) {
alert("Checked");
} else {
alert("Not checked");
}
});
</script>
The above works like a champ.

Textbox onchange event

So I have a text box, where I add an onchange event of markAsException.
My javascript is -
function markAsException(recordID) {
//alert("Exception");
//mark exception column
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).innerText = "Exception";
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).style.color = "#FF0000";
document.getElementById("ctl00_cpMain_tdScrollException_" + recordID).style.backgroundColor = "#99CCFF";
//enable comments ddl and remove blank (first item)
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).disabled = false;
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).focus();
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).options[0] = null;
}
What I want to do is, when a user changes the value in a textbox, to mark a column as "Exception", and then focus a drop down list where they have to chose the reason for the exception.
This is what happens.. If I am on that text box and change it, then tab, it tabs to the drop down list.
However, if I change the value and then simply click in another text box on the form, I don't focus the drop down list.
How would I accomplish that?
I would suggest using JQuery's change() function.
The advantage is that it will be more stable across different browsers.
Something like:
$('#<%= TextBox1.ClientID %>').change(function(){
// extract the recordID from the textbox - perhaps with an attribute?
markAsException(recordID);
});
My comment was getting longer so I'm expanding:
Take a look at the JQuery documentation for setting this up as the page finishes loading. If tb is the ID of your textbox your selector would be
$('#<%= tb.ClientID %>')
I would suggest you replace your code and use
tb.Attributes.Add("recordID", recordId.ToString());
This will add the ID you need onto the textbox tag. Once you're in the function I outlined above you can use the following selector to get the recordID in javascript
var recordID = $('#<%= TextBox1.ClientID %>').attr('recordID');
All together
$(document.ready(function(){
$('#<%= tb.ClientID %>').change(function(){
var recordID = $('#<%= tb.ClientID %>').attr('recordID');
if(recordID){
markAsException(recordID);
}
});
});

Countdown label on asp.net redirect page

After a user clicks the log out button I have it take them to a redirection page which displays a message and says " Logging out and Redirecting in ? seconds." I am using
Response.AddHeader("REFRESH", "3;URL=Login.aspx");
is there a way to display how many seconds are left until they are redirected in label?
In your redirect page you need to use JavaScript to handle it.
This sample may help you: http://javascriptsource.com/navigation/countdown-redirect.html
Following up on my comment, you could accomplish your solution via the following code:
<script type="text/javascript">
var timeLeft = 3;
function decrementCounter() {
if (timeLeft > 0) {
document.all('countDown').innerHTML = "Redirecting in " + timeLeft + "...";
timeLeft--;
setTimeout("decrementCounter()", 1000);
}
else {
window.location = "http://www.google.com/"
}
}
</script>
<body>
<form>
<label id="countDown">3</label>
<input type="button" value="Display alert box in 3 seconds" onclick="decrementCounter()" />
</form>
</body>
For example ,
When you Click the Logout button , You can create a count down javascript by dynamic
protected void OnLogout(object sender, EventArgs e)
{
string url = "~/Login.aspx";
string msg = "Logging out and Redirecting in ? ";
StringBuilder js = new StringBuilder("<script language=\"javascript\">")
.Append("var ts = 3; setInterval(\"redirect()\",1000);")
.Append("function redirect(){ if(ts == 0){")
.Append("window.location.href=\"" + url + "\"; }else{")
.Append("document.body.innerHTML = \"msg \" + (ts--)+\"seconds\";}}")
.Append("</script>");
Response.Write(js.ToString());
}
You'll need to use a client-side technology, I.e. JavaScript. Using server-side will require calls to the server which is not needed for something simple like this.
Because you are using Microsoft aspx, you can create a label on the client side and implement an AJAX by giving your code-behind the Id of the label and changing its value base on the time left.

How to retrieve html li value

I have a list in my aspx page where the values for the list are coming from the database. The data can be added to the list successfully
But how can I retrieve the value of the selected list item when I click on that? (ul_Click event)
I don't want to redirect to another page because I'm using AJAX. so i want it in the same page. that's why i commented the
<ul runat="server" id="ulList" onclick="ul_Click">
</ul>
The data is binded to the list in the page_load event.
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Server=NIPUNA-PC\\SQLEXPRESS; Database=XXX; Trusted_Connection=True");
string[] itemList = authorList();
foreach (string item in itemList)
{
HtmlGenericControl newLi = new HtmlGenericControl("li");
//newLi.InnerHtml = "" + item + "";
newLi.InnerText = item;
ulList.Controls.Add(newLi);
}
}
I want the ul_Click() event?
seems like you were on track with the innerHtml thing. You can pass some kind of an ID with the link.
"" + item + "";
then do a request querystring and check for that id. if it's there, then call a function?
i'm not 100% sure, but what you're trying to do might be impossible otehrwise with HtmlGenericControl. I don't think you can bind an onclick event to HtmlGenericControl
Your other option is perhaps go with ajax/javascript
EDIT> just saw the comment. so .... you might do something like
"" + item + "";
you could also do
"" + item + "";
i personally dislike the last one as <a href="#" version because it can cause bad client side behavior such as to go to page top or something stupid like that when clicked.
just to wrap things up. Keep in mind that you'll need a client side javascript to handle the function
<script language="javascript">
function callMyAjaxFunction(bookid){
// do something
}
</script>
adding to robert's ideal instead of including item twice in the markup, you might do
" + item + "
<script language="javascript">
function callMyAjaxFunction(e){
alert(e.innerHTML);// do something
}
</script>

jquery click tracking is acting a little strage

On some links on my HTML page I have a special CSS class, that when clicked, I make a ajax call to a click.aspx page and track the click.
blah-1
$(".click").bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
So what is happening is the value of source, after clicking a few links (that open in a new window) becomes:
source=blah1
then it becomes
source=blah1,blah2
Maybe you need to change it to:
$(".click")each(function(i) {
$(this).bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
});
so that each is processed separately...

Categories