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.
I am trying to change the focus from one textbox to another while the character count in
on textbox reaches 13 I am using the code below with nothing happening whatsoever:
if (!this.ClientScript.IsClientScriptBlockRegistered("qtyFocus"))
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "qtyFocus",
#"<script type='text/javascript' language='javascript'>function qtyFocus(){
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
if(trckNumberLength == 13){
document.getElementById('txtQuantity').focus();
}}</script>");
}
txtTrackingNumber.Attributes.Add("onchange", "javascript:return qtyFocus();");
can anyone help please ?
Probably because the line in the script that's doing
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
Needs to be changed for:
var trckNumberLength = document.getElementById('"+txtTrackingNumber.ClientID+"').value.length;
The reason being that txtTrackingNumber will very likely have a different Id when it's rendered on the page so you need to use the ClientID property of the control instead of the id you defined on the markup.
input[disabled='disabled']
{
background-color:#FFFBF0;
color: #28B51D;
}
I am using the following code, but it doesn't work in IE.
It works in the rest of the Browsers.
Since you tagged your question as javascript, here is my advice for IE : include an ie-only script with an ie-triggering html comments, that adds a ie-disabled class to every disabled input. If the status of inputs can change after the initial page load, add a timed observer to your page that sets the class properly.
input[disabled], input.ie-disabled
{
background-color:#FFFBF0;
color: #28B51D;
}
javascript file, included with conditional comment:
function checkDisabled() {
var inputs = document.getElementsByTagName('INPUT');
for(var i=0, l=inputs.length; i<l; i++) {
if(inputs[i].disabled) {
if(inputs[i].className.indexOf('ie-disabled')==-1)
inputs[i].className = inputs[i].className+' ie-disabled';
} else {
inputs[i].className = inputs[i].className.replace('ie-disabled', '');
}
}
}
setInterval(checkDisabled, 1000); // check every second
Here is a test (for IE). Note that the color css attribute is ignored by IE for disabled inputs. If you really need a green text, use readonly instead of disabled.
I have an Asp.Net page with a list of options accompanied by a checkbox in a ListView control. I have applied Paging using the paging control. However I want to maintain the status of the checkboxes across the various paged pages of the ListView. I have done this with the following code
private List<int> IDs
{
get
{
if (this.ViewState["IDs"] == null)
{
this.ViewState["IDs"] = new List<int>();
}
return (List<int>)this.ViewState["IDs"];
}
}
protected void AddRowstoIDList()
{
int checkAction = 0;
foreach (ListViewDataItem lvi in lvCharOrgs.Items)
{
CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
if ((((chkSelect) != null)))
{
int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);
if ((chkSelect.Checked && !this.IDs.Contains(ID)))
{
this.IDs.Add(ID);
checkAction += 1;
}
else if ((!chkSelect.Checked && this.IDs.Contains(ID)))
{
this.IDs.Remove(ID);
}
}
}
}
protected void lvCharOrgs_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem lvi = (ListViewDataItem)e.Item;
if ((lvi.ItemType == ListViewItemType.DataItem))
{
// Find the checkbox in the current row
CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
// Make sure we're referencing the correct control
if ((chkSelect) != null)
{
// If the ID exists in our list then check the checkbox
int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);
chkSelect.Checked = this.IDs.Contains(ID);
}
}
if (Profile.proUserType == "basic")
{//basic account so no choice of charity
((CheckBox)e.Item.FindControl("chkSelect")).Checked = true;
((CheckBox)e.Item.FindControl("chkSelect")).Enabled = false;
}
}
Now I have a CustomValidator control which checks to ensure between 3 & 5 records have been selected. If this is true the page is valid and processed. If it is not the case (eg less than 3 or more than 5) the page is Invalid and the CustomValidator throws up a label to notify of this fact.
I use the following code on the serverside to implement this.
protected void lvCharOrgsValidator_ServerValidate(object source, ServerValidateEventArgs args)
{// Custom validate lvCharOrgs
//update selected rows
AddRowstoIDList();
//get count and verify is correct range
int counter = this.IDs.Count;
args.IsValid = (counter >=3 && counter <=5) ? true : false;
}
This all works fine except I need to implement a 'ValidatorCallout' extender from the AJAX Control Toolkit. However this doesn't work with CustomValidators unless they implement clientSide validation. Thus I need to convert the 'lvCharOrgsValidator_ServerValidate' method to a clientside JavaScript function.
Hope this clarifies my requirements.
What does the following do?
AddRowstoIDList();
Something like the following is a start, but will need more details on the above method to provide a working answer
function validateRowCount(sender, args) {
//update selected rows
AddRowstoIDList(); // Does this add row indexes to an array?
//get count and verify is correct range
var counter = IDList.length;
args.IsValid = (counter >=3 && counter <=5);
}
It might be worth looking at Script# for a longer term solution, if you're planning on doing a lot of conversion.
EDIT:
now I can see the AddRowstoIDList() method, to do this on the client-side will be slightly different. Firstly, get a reference to the DOM element that is rendered for lvCharOrgs. Probably the most straightforward way to do this in vanilla JavaScript would be to put the JavaScript function in the page and use the server tags to get the rendered ClientID.
function validateRowCount(sender, args) {
var lvCharOrgs = document.getElementById('<%= lvCharOrgs.ClientID %>');
var checkboxes = lvCharOrgs.getElementsByTagName('input');
var len = checkboxes.length;
var counter = 0;
for(var i =0; i < len; i++) {
if (checkboxes[i].type == "checkbox" && checkboxes[i].checked) counter++;
}
args.IsValid = (counter >=3 && counter <=5);
}
Should work something like this - Working Demo
add /edit to the URL if you want to see the code
If you change int to var, your code is valid JavaScript. (But since it depends on other functions and objects you need to convert those as well.) Also if you're using the c# 3.5 compiler it will stay valid C# even with var instead of int.
Probably not what you want, but there is jsc:
"Web 2.0 hype? Want build better web
sites, but javascript is too hard? No
real IDE? Maybe you should try jsc.
The web app can be built within Visual
Studio 2008 or any other c# compliant
IDE, and then the application
magically appears. You should think of
it as a smart client. Precompile your
c# to javascript with jsc! As an
option instead of using IIS and
asp.net, you could get away by using
apache, with mysql and php."
Have a look at this article. It applies to asp.net mvc, but it also covers some basics and you might be able to do something similar for asp.net. In particular, you might find the jquery remote validation attributes shown in the article useful for what you intend to do.
SharpKit converts C# to client side javascript.
https://sharpkit.github.io/
Well, you can always include your own javascript with custom validators. Here is a link to an article that introduces adding javascript to a validator. You just have to write your own javascript, really.
I heard about a cross-compiler from c# (or was it IL?) to JavaScript but unfortunatly do not remember the name anymore, but a google-search turned up stuff like this: http://jsc.sourceforge.net/
I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);