How to change text property of asp.net textbox with javascript - asp.net

I have a textbox that I want to change text property of it with javascript, but I can't do.
My sample code below, Can anyone say what is wrong? Thanks...
function openAdresYeni(p) {
document.getElementById('hdnAdresIndex').innerText = p;
}
}

Try this :
function openAdresYeni(p) {
document.getElementById('hdnAdresIndex').value = p;
}
NOTE : By the way if your hdnAdresIndex is a server control, you should use control's ClientID property to get client side id :
function openAdresYeni(p) {
document.getElementById('<%= hdnAdresIndex.ClientID %>').value = p;
}

use value instead of innerText
also, if you're not in asp.net mvc, the ID of the control is probably not what you expect. Look into the myTextBox.ClientID property on the asp.net control.

Related

asp.net 4.0: is there any equivalent of ClientIDMode for the names of INPUTs?

I have an asp:ListView whose ClientIDMode is set to Predictable. Its ItemTemplate contains an asp:textbox.
The ID of the textbox is acting as I expect it to, but its name is still using what looks like an AutoID-style algorithm:
<input name="lvFields$ctrl0$tbVal" id="lvFields_tbVal_somekey" type="text"/>
Is there a way for me to cause the name of the input to act like the ID does?
(Edit in response to questions below:)
The Name of the input element is what's in the POST data, so if a postback alters the list to which the ListView is bound (for example, exchanging two elements) the values from the textboxes end up associated with the wrong keys, because the framework is correlating them based on the Name and not the ID.
You can change the name of an Input by using the method from the following post but modifying it slightly:
how to remove 'name' attribute from server controls?
I over-rode the RenderChildren method on a Page control as I just wanted full control of the HTML for a few controls:
protected override void RenderChildren(HtmlTextWriter writer)
{
var unScrewNamesRender = new RenderBasicNameHtmlTextWriter(writer);
base.RenderChildren(unScrewNamesRender);
}
private class RenderBasicNameHtmlTextWriter : HtmlTextWriter
{
public RenderBasicNameHtmlTextWriter(TextWriter writer) : base(writer) { }
public override void AddAttribute(HtmlTextWriterAttribute key, string value)
{
if (key == HtmlTextWriterAttribute.Name && value.Contains("POLine"))
{
value = value.Substring(value.LastIndexOf("$") + 1);
}
base.AddAttribute(key, value);
}
}
You do need to know what you're doing if you attempt this, WebForms will think the control is missing so you can't use it in any postbacks. For my purposes, where I wanted to add an arbitrary number of multiple lines either server or client-side without having to deal with .Net Ajax controls, it works fine.
I'm pretty sure you can't change the name, especially when you modify the ClientIDMode. As an alternative, you can add a Title attribute. VS will flag this as unknown in the server side code, but it renders correctly in the HTML. If you're doing some client-side manipulation, you can address the input as such:
<script type="text/javascript">
$(document).ready(function () {
$('input:text[title="TextBoxName"]').datepicker();
});
</script>
As far as I know, there is no way to change the name of the input element. The name corresponds to the UniqueID property, which is generated by the system, and which you have no control over. Seems you have to find a way to achieve what yo want using only the control ID.
Both names are using the predictable pattern; originally, name also equaled ct100_ct100 etc. From what I see, that's a predictable name. Client ID value will always use _ between control prefixes and Unique ID (name attrib) will always use $. The two will always match, except for a few controls that leverage name for something (radiobuttonlist uses for grouping).
HTH.
I had the exact same problem once and had to use one of these properties exposed in "System.Web.UI.Control" to get clientside control name in server side.
Play around with these properties and construct the "Name" in server side yourself and use Request.Form("NameHere")
Me.ClientIDSeparator
Me.IdSeparator
Me.UniqueID
A jquery solution
function removeNameAttribute() {
$('input, select').each(function () {
$(this).removeAttr("name");
});
}
//Use a HtmlGenericControl
HtmlGenericControl input = new HtmlGenericControl("input");``
input.ID = "lvFields_tbVal_somekey";
input.Attributes.Add("name", "tbVal");
input.Attributes.Add("type", "text");
input.ClientIDMode = ClientIDMode.Static;

Adding User controls on runtime - accessing the controls

I'm trying to add some user controls on a page. Thats easy, I just do it like this.
UserControl block = (categoryblock) LoadControl("categoryblock.ascx");
Panel1.Controls.Add(block);
But i want to access the label controls and more that are inside the categoryblock.ascx.
How would i do that ?
I cant do it like this,
block.l_itemName.text = "blabla";
I managed to user FindControl("l_itemName") but i would rather like to have the intellisense.
create following property in your user control:
public string ItemName() {
get() {
return l_itemName.text;
}
set(String value) {
l_itemName.text = value;
}
}
This will make you able to do block.ItemName = ""or string temp = block.ItemName
I hope this will help

Display jquery dialog on postback in ASP.NET after saving a new record

What I would like to do is have the user add a new record to the database and popup a JQuery dialog confirming that the new record was saved. I thought this would be a simple exercise. I have a gridview bound to a LINQDataSource to allow the user to view and edit existing records and a textbox and a button to add new codes.
In the head of the document, I have the following:
$('#dialog').dialog({
autoOpen: false,
width: 400,
buttons: {
"Ok": function () {
$(this).dialog("close");
}
}
});
and futher down in the markup I have:
<div id="dialog" title="New Code Added">
<p>"<asp:Literal runat="server" ID="LiteralNewCode"></asp:Literal>" was successfully added.</p>
</div>
So when the user enters a new description and it passes all the validation, it's added to the database and the gridview is rebound to display the new record.
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CCRCode.Add( <long list of paramters> );
GridCode.DataBind();
IsNewCode = true;
NewDescription = <new description saved to database>;
}
}
Now, here's where (I thought) I'd set a boolean property to indicate that a new description had been added as well as the text of the new description. See below:
protected bool IsNewCode
{
get { return ViewState["IsNewCode"] != null ? (bool)ViewState["IsNewCode"] : false; }
set { ViewState["IsNewCode"] = value; }
}
private string NewDescription
{
get { return ViewState["NewDescription"] != null ? ViewState["NewDescription"].ToString() : string.Empty; }
set { ViewState["NewDescription"] = value; }
}
Here's where I loose my way. My guess is I want to add functionality to include code similar to:
$('#dialog').dialog('open');
I've added a registerscriptblock method in the page_load event but that didn't work. Any ideas? Or am I just going about this entirely wrong?
Thanks.
Not really get what you want to do. But, i use jquery alot with .NET in my projects. here is how i do, probably could give you a hint.
foo.aspx.cs
public String ScriptToRun = "$('#dialog').dialog('open');";
change the value of ScriptToRun in your C# code
foo.aspx
$(document).ready(function() {<%=ScriptToRun %>});
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
Two ways: one, write the javascript in your server-side code. Or, define a JS method to show the dialog (say named showDialog), and call it via:
Page.ClientScript.RegisterStartupScript(... "showDialog();" ..);
RegisterStartupScript puts the method call at the end, ensure your script is above it to work. You can also wrap it with document.ready call too, to ensure JQuery is properly loaded.
I think that the only think that you have miss is the creation of the dialog when the Dom is ready.
$(document).ready(function() {$('#dialog').dialog('open');});
I posted code in a different question for a custom "MessageBox" class I wrote:
ASP.NET Jquery C# MessageBox.Show dialog uh...issue
the code by default uses the javascript alert() function, but you can define your callback so that it calls your custom javascript method to display the messages.

How do I set the StripFormattingOnPaste property of a Telerik RadEditor with JavaScript?

I don't have access to the actual asp.net server tag itself, so I need to change the StripFormattingOnPaste property to the EditorStripFormattingOptions enum with JavaScript and I'm not sure how. I have some code that adds an OnClientLoad() and OnClientCommandExecuted() functions that works so I can add it in there, I'm just not sure where the property exists on the client-side and what the enum value would be:
// init OnClientLoad and OnClientCommandExecuted event handlers for all radeditors on the page
Sys.Application.add_load(function() {
if (typeof ($telerik) != "undefined") {
if ($telerik.radControls && Telerik.Web.UI.RadEditor) {
for (var i = 0, l = $telerik.radControls.length; i < l; i++) {
var control = $telerik.radControls[i];
if (Telerik.Web.UI.RadEditor.isInstanceOfType(control)) {
var editor = control;
// ??? editor._stripFormattingOptions = Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage
// editor already loaded, fire event
OnClientLoad(editor);
// attach event handler for paste commands
editor.add_commandExecuted(function(ed, args) {
return OnClientCommandExecuted(ed, args);
});
}
}
}
}
});
Update: I've discovered that the correct enum setting that I want is Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage.
Update #2: I see that the RadEditor JS object has a _stripFormattingOptions property, but I think it might just be for private use.
The Telerik controls are based on ASP.NET AJAX and use pretty much the same coding conventions - public properties have getters and setters methods. In this case you should use
editor.set_stripFormattingOptions(Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage);
To get the current value, use
var value = editor.get_stripFormattingOptions();
The property you saw (editor._stripFormattingOptions) is just used to store the value. Since its name starts with an underscore you are correct to assume that it is private and so you should not rely on it. The getter and setter methods are public and you are free to use them.

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

Resources