ASP.Net Javascript integration - asp.net

I am trying to use the following script in asp.net:
<script language="javascript" type="text/javascript">
function checktext() {
var txt = document.getElementById('tbComments');
if (txt.Text.Length > 0) {
alert('Thank you for submitting feedback.');
return true;
}
else {
alert('Sorry, you must enter text before submitting.')
return false;
}
}
</script>
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="checktext();" />
I have tried using it on the onclick event.. the script will just not work at all.
Any Ideas?

you can use the ClientID property for getting the name of a Control on the client side. I suggest you to try jQuery for all these though
var txt = document.getElementById('<%=tbComments.ClientID%>');
besides, the OnClientClick has to receive a true or false value, in order to "know" whether to send the request to the server; so you have to change it with something like OnClientClick="return checktext();"

Try calling it like this:
<asp:Button
ID="btnSave"
runat="server"
Text="Submit"
onclick="btnSave_Click"
OnClientClick="return checktext();" />
Also this line looks suspicious in a web forms application:
document.getElementById('tbComments');
Make sure that the generated id of your control is not prefixed with something else.

Replace:
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="checktext();" />
with:
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="return checktext();" />
Replace:
var txt = document.getElementById('tbComments');
With:
var txt = document.getElementById('<%= tbComments.ClientId %>');
HTH.

everone else mentioned OnClientClick so I won't address that.
assuming tbComments is a textbox of some kind, this line
if (txt.Text.Length > 0) {
is going to fail because Text is not a property of html inputs or textareas, which is how asp.net textboxes are rendered. what you want is
if (txt.value.length > 0) {
also, is there some reason you're not using a regular asp.net RequiredFieldValidator control? you're doing more work than you need to. If you absolutely have to have alert boxes, you can use a CustomValidator control to call your function (you'll have to tweak it to fit the model).

Related

cannot access js code in content page

I took one masterpage and one web form selected with the first master page.
In this webform i took textbox and button. Button's OnClientClick property set with validate()
I took one JScript.js file in that i write the following function :
function validate() {
var no = document.getElementById('<%=TextBox1.ClientID %>').value;
if (isNaN(no)) {
alert('not a number.');
}
}
In default.aspx page i write the textbox and button code is as following
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" onclientclick="validate()" Text="Button" />
In master page's head section i call the js file as following :
<script src="JScript.js" type="text/javascript">
</script>
So the my question is this is not worked the alert message not appears as i write non numeric number in textbox.
You can't use asp .net binding syntax in js files.
this will be rendered the same in your js file, and will not contain ur TextBox1ClientId:
var no = document.getElementById('<%=TextBox1.ClientID %>').value;
either pass the client Id from your aspx page as a parameter to the validate method, or embed your javascript function in ur aspx.
You can add clientIDMode="Static" in your control.
<asp:TextBox ID="TextBox1" runat="server" clientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" clientIDMode="Static" onclick="Button1_Click" onclientclick="validate()" Text="Button" />
Or if you want to make it project level, just add the line in web config file
<pages clientIDMode="Static"></pages>
inside <system.web>.

Update Panel and triggers from a repeater control

Hi I found code similiar to the following online. It's seems really great for getting a button buried in a repeater control to trigger a full cycle back to the server.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="HiddenButton" />
</Triggers>
</asp:UpdatePanel>
<!--Make a hidden button to treat as the postback trigger-->
<asp:Button ID="HiddenButton" runat="server" Style="display: none" Text="HiddenButton" />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<!--when cick the button1, it will fire the hiddenButton-->
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('HiddenButton').click();return false;"
runat="server" />
</ItemTemplate>
</asp:Repeater>
It uses a hiddenButton to achieve this by hooking the click event of the original button to this one. However my addition to this was the setting of the CommandArgument for the button. I would also need it to be set for the HiddenButton.
Does anyone know a way of going about this?
First I will like to explain the Disadvantage of using the Update Panel using the very same example posted by you.
Below is the Original Code
Output
To display the 22 character string you can check how much data is being received and sent to server. Just imagine following
If you would consider send each request to Database using Update Panel and your GridView is in Update Panel!!!!!!
Suppose you would use ViewState data for each request and with GridView Inside the Update Panel.
Both the above techniques are worst as per my understanding.
Now I will describe you Page Methods
Page Method over Update panel
Page Methods allow ASP.NET AJAX pages to directly execute a Page’s Static Methods, using JSON (JavaScript Object Notation). Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a Web Method to request only the information that we’re interested.
Sample Code
Output
Hope this clearly explains the difference of usage.
Answer to the original Query
You have to register the ItemDataBound event of the below Repeater and use below code for it.
Code Behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = (Button)e.Item.FindControl("Button1");
btn.OnClientClick = string.Format("SubmitButton('{0}');return false;"
, HiddenButton.ClientID);
}
}
JavaScript
<script type="text/javascript">
function SubmitButton(btn)
{
$("#" + btn).click();
}
</script>
//Alternative
<script type="text/javascript">
function SubmitButton(btn)
{
document.getElementById(btn).click();
}
</script>
Reference & Here
Your HiddenButton control is a server control but you are trying to access it in JQuery using it's ASP.Net ID,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('**HiddenButton**').click();return false;"
runat="server" />
A quick way to fix it is to make a separate function,
<script type="text/javascript">
function SubmitButton(btn)
{
$get("#" . btn).click();
}
</script>
and change your button code to ,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>'
runat="server" />
In code behind, in repeater's ItemDataBound event, find the button and HiddenControl and set Button1's OnClientClick property,
Button1.OnClientClick= string.Format("SubmitButton('{0}');return false;",HiddenButton.ClientID);

Styling the relevant input on validation error, like MVC

I have search the net and not found anything that has helped, so thought I would ask on here.
I have a simple asp.net 2.0 form.
<form runat="server">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:TextBox ID="txt1" runat="server" ValidationGroup="valGroup1"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txt1" ValidationGroup="valGroup1" runat="server" Display="Dynamic" ID="val1" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="btn1" runat="server" ValidationGroup="valGroup1" CausesValidation="true" Text="submit" />
</form>
What I want to do is to change the styling on the input when validation fails for that particular input. Preferably by adding a class, not inline styles.
I can do this when javascript is not available via code behind, but what I want to do is have the same happen when javascript is available.
I know that ASP.NET injects a global js variable called Page_Validators, which is an array of all of the validator spans on the page. Is there an easier way to do this other than looping through all of these??
EDIT
I can sort of do it with the following:
<script type="text/javascript">
function ValidateInputs() {
var validators = Page_Validators;
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (!validator.isvalid) {
document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
}
}
}
</script>
Was just wondering if there was a better way??
And can I get the microwoft validation scripts to call my validation method? or can I hook into the validation event manually?
That's a pretty good way of doing it; there is no public event or something else to tap into, unless you want to start replacing public events with your own custom ones (that gets messy).
HTH.
It turns out my answer is the only one that I am going to get!
<script type="text/javascript">
function ValidateInputs() {
Page_ClientValidate();//Validate the validators using microsofts validation
var validators = Page_Validators;
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (!validator.isvalid) {
document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
}
}
}
</script>
Also, on the button, set the OnClientClick="ValidateInputs();" to OnClientClick="ValidateInputs();return false;"

how to clear an label value in javascript

I have an label "test" comimg from .cs [c# code] text="data saved successfully" . but once I click the save button i need to clear its text
right now I have 3 required field validators. with message [cannot be blank, cannot be blank,cannot be blank,] as user as clicked the save button I need to clear the text of the label. But need to show the required fields validator message
any idea how to solve it
thank you
make a javascript function like:
<Script type="text/javascript">
function clearText(cntId) {
var cnt = document.getElementById(cntId);
cnt.value ="";
return false;
}
</script>
then on your submit button attach a client side event
<asp:Button id='btnSubmit' Text='Submit' onClientClick='clearText("<%this.lblLable.ClientId%>");' .... />
On the client-side use a script like this
<script type="text/javascript">
function clearLabelValue(){
var labelObj = document.getElementById("<%= myLabel.ClientID %>");
labelObj.value = "";
}
</script>
<asp:Label id="myLabel" runat="server" Text="Some text"/>
<asp:Button id="myButton" runat="server" Text="Submit" OnClientClick="clearLabelValue();return false;"/>
Didn't test it in detail, but should work.
It is not really clear what you want to achieve, although I have the feeling there may be a "better" (more standard compliant) way of achieving what you want. Maybe you could describe more clearly what you want, so we may be able to help you.
In these situations when a particular button has validation attached to it and also we need to fire some javascript what is done is to define a javascript function which is called on click of save button.
What this javascript function does:
This function will take your label and will set its value as blank so that the text is cleared.
Now in order to validate the page which happens internally (in case the javascript function is not written on the save button click) we need to explicitly call what asp.net call for client side validation.
There is a function page_ClientValidate which needs to be called from this javascript function so that validation is still done and we also do some other processing like clearing the label in this case.
<!--for cleaning to label ; -->
document.getElementById("MyLabel").innerHTML = "";
<!--and label is like;-->
<asp:Label ID="MyLabel" runat="server" ></asp:Label>
You can simply achieve this using below script:
<script type="text/javascript">
function clearLabelValue(){
document.getElementById("<%= myLabel.ClientID %>").innerText=""
}
</script>
<asp:Label ID="myLabel" runat="server" ></asp:Label>
<asp:Button id="myButton" runat="server" Text="Submit" OnClientClick="clearLabelValue();"/>

Why does ModalPopupExtender not show through javascript?

I followed several web resources to understand how to show a popup from client side, and I made this code:
<asp:ImageButton runat="server" ID="btnOk" ImageUrl="imagens/btnAlterar.gif" OnClientClick="btnOkClick()" />
<asp:LinkButton runat="server" ID="dummyForPopup" Visible="false"/>
<ajaxToolKit:ModalPopupExtender runat="server" BehaviorID="btnOkPopupBehavior" ID="MPXtender" TargetControlID="dummyForPopup" PopupControlID="pnlUpdateUserModal" BackgroundCssClass="modalBackground" OkControlID="btnCloseRequestUserUpdate" OnOkScript="userUpdReq_onOk()" />
function btnOkClick()
{
if(validateAll())
{
var behavior = $find('btnOkPopupBehavior');
if (behavior)
{
behavior.show();
}
else
{
var lblOutput = $get('<%= lblOutput .ClientID %>');
lblOutput .innerText = 'Couldn't find popup';
}
}
}
previously I had the modal popup linked to the ok button, it was working pretty well. Now I need some validation before opening the popup, and this code is not working anylonger =/
1) Your dummy button has to be visible = true, otherwise the javascript doesn't work properly. So set visible = true but disaply none with css:
<asp:LinkButton runat="server"
ID="dummyForPopup" style
="display:none" Visible="true" />
2) lblOutput .innerText = 'Couldn't find popup'; is a javascript error. You need to change it to: "Couldn't find popup"; (or use &apos;)
3) OnClientClick="btnOkClick()" should really say: OnClientClick="btnOkClick(); return false;"
4) Look for any other javascript errors on your page because those will stop the popup from workign properly.

Resources