Onblur,Onfocus javascript for TextMode="MultiLine" not working - javascript

I've got a multiline asp.textbox input control.
I don't know if my issue is with ASP.NET, the Multiline control, or something else, but the onblur and onfocus are not working.
<script type="text/javascript">
var defaultMsg = 'Write your message here or or call my voice at (xxx) xxx-xxxx.';
var controlMsg = doc.createElement("input");
controlMsg.id = "txtMessage";
controlMsg.type = "text";
controlMsg.value = defaultMsg;
controlMsg.onfocus=function jpFocus() { if (this.value == defaultMsg) this.value = ''; }
controlMsg.onblur=function jpBlur() { if (this.value == '') this.value = defaultMsg; }
</script>
And later....
<asp:TextBox ID="txtMessage" Columns="30" Rows="6" runat="Server" TextMode="MultiLine" />
Does anyone see a reason why this should not be working?

Actually, you're creating a html element and you are attaching an event to it.
In addition, ASP.NET controls does not use the server side id.
Here's what you should do :
var controlMsg = document.getElementById('<%= txtMessage.ClientID %>');
controlMsg.onfocus = // Some Code ...
controlMsg.onblur = // Some Code ...

Try using an anonymous function, like this:
controlMsg.onfocus=function() { if ( ...
Functions and function scope - MDN.
Also, you did call something like document.body.appendChild(controlMsg);, didn't you?
EDIT:
You are using doc.createElement. Make sure that doc definitely points to document.
Also, look at the page in Firefox and see if there are any errors or warnings in the Error Console.

Not sure which version your are using.Please Try this:
protected void Page_Load(object sender, EventArgs e)
{
txtMessage. Attributes["onfocus"]="JavascriptMethod";
}

I'm not sure why this worked and other techniques did not, but this got my HTML to work:
<textarea name="txtMsg" rows="6" cols="30"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
The text can be very long, and the control does not seem to care. Also, the text is only written in a single location.

Related

Javascript validation in Form runat=server

I'm new to .NET and web development in general. I created a form to collect a user's comment and/or a file attachment. Everything works fine but I would like to add client side validation but it fails when I do so. Using Chrome's dev tools I can see the javascript is executed but the first statement fails saying "cannot read property value of undefined". If I remove the runat="server" properties, it works fine but I can no longer access the data from the code behind.
So what options do I have for making the javascript work? Or am I going about saving the data the wrong way?
aspx page:
<form id="commentForm" name="commentForm" runat="server" enctype="multipart/form-data" method="post" onsubmit="return validateCommentForm()">
<p>Add Comment</p>
<textarea id="Comment" name="Comment" rows="4" class="with-100" runat="server" />
<input id="FileAttachment" type="file" runat="server" />
<input type="submit" id="SaveComment" class="red-button" value="Submit" />
</form>
javascript:
function validateCommentForm()
{
var x = document.commentForm.Comment.value;
var y = document.commentForm.FileAttachment.value;
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
c#:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == true)
{
if (Comment.Value.Length > 0)
{
Insert.UserComment(Comment.Value);
}
HttpPostedFile UserFileAttachment = Request.Files[0];
if (UserFileAttachment.ContentLength > 0)
{
Insert.FileAttachment(UserFileAttachment);
}
}
}
Thanks in advance.
You can use jQuery, where you can call the form elements by the name as described in their API.
Retrieve the value:
$("input[name='Comment']").val();
To update the value (if needed) from JavaScript:
$("input[name='Comment']").val('some Comment');
You can also do it by ID (and based on your sample this should work) with the following jQuery:
$("#Comment").val();
So your final JavaScript would look like:
function validateCommentForm()
{
var x = $("#Comment").val();
var y = $("#FileAttachment").val();
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
I do think there's something odd in accessing the file name from a file input box. See the file selector jQuery documentation.

JavaScript: Search string for expression and return error if not found

I have a form that should only allow e-mail addresses with a ".edu" domain, and I worked up some JavaScript to try to make that happen.
Form elements:
<input type="text" name="empEmail" id="empEmail" />
<input type="submit" name="submit" id="submit" value="submit" onClick = "error();" />
<span id="empEmailError"> </span>
JavaScript function:
//Check for non-university e-mail addresses
function error() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re))
{
document.getElementById('empEmailError').innerHTML = "University e-mail
address only.";
return false;
}
}
Here's the fiddle:
http://jsfiddle.net/4T5qV/
I can't get it to work. Not sure what it is I'm missing.
You have to use .test().
if(!re.test(email))
.test() returns whether the regex has matched or not.
Also, you have to use <wrap in head> option of fiddle
Demo
There was a problem where it wasnt finding the error function. It could be that it was putting the error function in a document.on('loaded') function or something like that in the jsFiddle.
So the solution is to add a function to the window, like so:
//Check for non-university e-mail addresses
window.validateEduAddress = function() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re)) {
document.getElementById('empEmailError').innerHTML = "University e-mail address only.";
return false;
} else {
console.log('woohoo');
}
}
Then in your html you need to tell the onclick to use that function like so:
<input type="submit" name="submit" value="submit" id="submit" onclick="validateEduAddress();" />
And just to make it easier, heres the updated jsFiddle
In general you should also try to avoid naming functions so generically, so instead of error or fail you should try to describe the event or functionality :)
As others have noted, the cause of this issue is that you have the onLoad option selected in jsfiddle, and the result is that your inline onclick handler cannot find your error function. This is partly the fault of using inline event handlers (putting the JavaScript directly in an attribute), which is not a recommended practice.
Another problem is that you have a line break right in the middle of one of your string values, and this is causing a syntax error and preventing the code from running at all.
You should use the "no wrap in <head>" option, and unobtrusive JavaScript.
Remove the onclick attribute from your element:
<input type="submit" name="submit" id="submit" value="submit" />
And use this:
function validate(e) {
var email = document.getElementById('empEmail').value,
re = /\.edu$/;
if (re.test(email)) {
document.getElementById('empEmailError').innerHTML =
"University e-mail address only.";
return false;
}
return true;
}
window.onload = function () {
var form = document.getElementById('submit').onclick = validate;
};
(I've used re.test() here as Amit suggests, because that does make more sense semantically in this case.)
http://jsfiddle.net/4T5qV/6/

How to enable asp:LinkButton on client side

I have asp:LinkButton, input Button defined as:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('lnkViewPdf'));" />
the LinkButton is initially disabled in code-behind as:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
and needs to be enabled when Button2 is clicked, so I am calling javascript function to enable the link as:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
//$("#lnkbutton").removeAttr('disabled'); //even this doesn't work
}
But I am not able to enable the linkbutton.
Am I missing something?
Thank you!
__________________________________________________
Anyone interested in solution to above problem:
In code-behind:
this.lnkViewPdf.Attributes["disabled"] = "disabled";
this.lnkViewPdf.Attributes["onclick "] = "return false";
.js:
function TestEnable(lnkbutton) {
$(lnkbutton).removeAttr('disabled');
lnkbutton.onclick = "";
}
NOTE: When setting lnkViewPdf.Enabled = false; LinkButton was being rendered as
<a id="lnkViewPdf" class="aspNetDisabled icoMiniTest">View Office Pdf</a>
see the style class aspNetDisabled, something added by ASP.Net
However setting disabled/onclick attributes from the codebehind as shown above, render Linkbutton as:
<a id="lnkViewPdf" class="icoMiniTest" disabled="disabled" onclick ="return false" href="javascript:__doPostBack('lnkViewPdf','')">View Office Pdf</a>
HTH.
Try now...
function TestEnable(lnkbutton) {
lnkbutton.disabled = "";
lnkbutton.onclick = "";
}
In the code behind, rather than disable by setting Enabled = false, set:
lnkViewPdf.Attributes["disabled"] = "disabled"
So your javascript function:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
}
Your markup:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>')); return false;" />
And your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lnkViewPdf.Attributes["disabled"] = "disabled";
}
$("#<%=lnkViewPdf.ClientID %>").removeAttr("disabled");
You need to know the .Net constructed name in order to accomplish it. The easiest way is to have it set in the head of the page if you can:
<script language="javascript">
var lnkbuttonToEnableId = "<%= this.lnkViewPdf.ClientId %>";
function TestEnable() {
alert('TestEnable() called');
lnkbuttonToEnableId.disabled = false;
}
</script>
At any rate, the only way to get it to work is to pass the ClientId of lnkViewPdf to the function somehow.
try both of those:
<input id="Button2" type="button" value="TestEnable"
onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>'));" />
or
$("#<%= lnkViewPdf.ClientID %>").removeAttr('disabled');
UPDATE: Since you are disabling the LinkButton on server side .NET strips the href attribute from the <a> html element. What you should do to prevent the lost of that information is to disable the LinkButton on the client and then enable it when you need to. Also instead of disabling it all you need to do is remove the href attribute.
So first you need to retain the href and remove it so the <a> link become disabled:
$(document).ready(function () {
var $lnkViewPdf = $("#lnkViewPdf");
$lnkViewPdf.data("href", $lnkViewPdf.attr("href"));
$lnkViewPdf.removeAttr("href");
});
and the function that enables it:
function TestEnable(lnkViewPdfId) {
var $lnkViewPdf = $("#" + lnkViewPdfId);
$lnkViewPdf.attr("href", $lnkViewPdf.data("href"));
}
If you disable the LinkButton using:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
Then the href attibute won't be displayed in the HTML. If you manually add the disabled attribute instead:
if (!IsPostBack)
{
lnkViewPdf.Attributes.Add("disabled", "disabled");
}
Then you're code will work just fine.
Oh!.. and one last thing: You need to set the PostBackUrl property for the LinkButton. You missed it in your example.

Validation summary message pops up twice

I have validation controls in my page and I am using Validation summary message box to display the validation messages,the javascript function shown below worked for me but the problem is I am using this javascript function on OnClientClick event of the button and when I click the button with form controls not been filled its displaying the validation summary message box as expected but when i close the summary box it's getting displayed again and i need to close the message box to disappear, means i have to do two clicks everytime. Can somebody correct me what am I doing wrong.
Here is what I am doing:-
<asp:Button ID="SubmitButtonOne" runat="server" Text="Submit" OnClick="SubmitButtonOne_Click"
ValidationGroup="Cases" ClientIDMode="Static" OnClientClick="PleaseWaitShow()" />
Here is the javascript function:
function PleaseWaitShow() {
var isPageValid = true;
// Do nothing if client validation is not active
if (typeof (Page_Validators) != "undefined") {
if (typeof (Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate();
}
}
if (isPageValid) {
document.getElementById('SubmitButtonOne').value = "Processing...";
}
}
code behind:
protected void SubmitButtonOne_Click(object sender, EventArgs e)
{
try
{
// some functionality
}
catch (Exception)
{
//show errror message
}
}
It is expected behavior.
Once Page_ClientValidate is fired due to your explicit call inside PleaseWaitShow method and second is an implicit call made by the PostBack button click.
And so you are seeing two times the ValidationSummary message box.
I don't have a solution to circumvent this but will update if something strikes.
Note: One thing I would like to point out is since you have ValidationGroup="Cases" on your submit button you should pass that to your Page_ClientValidate method.
Update 1: One way I can think of is trying something like this:
1: OnClientClick="return PleaseWaitShow();"
2: return isPageValid from PleaseWaitShow():
function PleaseWaitShow() {
var isPageValid = true;
....
....
....
return isPageValid;
}
No, it is not the expected behavior. Rather, it's a bug in ASP.NET validation JS code.
The ValidationSummaryOnSubmit function loops over all summaries, and for each summary, loops over all validators. If not group is specified, then each validator's message is appended, resulting in 2 (3, 4, 5?) repetitions of the same messages.
I solved the problem by fixing the function (staring at line 53 or so):
....
for (i = 0; i < Page_Validators.length; i++)
{
var validator = Page_Validators[i];
if (validator.validationGroup != null && summary.validationGroup != null)
{
if (validator.validationGroup != summary.validationGroup) continue;
}
if (!validator.isvalid && typeof (validator.errormessage) == "string")
{
s += pre + validator.errormessage + post;
}
}
....
if you use Page_ClientValidate method, you should set causevalidation to false. CausesValidation="false"
because Page_ClientValidate is already doing this for button or control you validate
Please remove ValidationGroup of Button. Only user for ValidationSummary
Like:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqvName" runat="server" ControlToValidate="txtName" ErrorMessage="Please enter Name" ValidationGroup="SaveName"> </asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" OnClientClick="DisableButton();" Text="Save this Name" ></asp:Button>
<asp:ValidationSummary ID="valSaveName" runat="server" ValidationGroup="SaveName" ShowMessageBox="true" ShowSummary="false" />
Thanks

How to pass javascript var to server side on asp.net

I'm trying to pass a textarea value to the server side. The textarea cant be runat=server though.
heres my code:
<script type="text/javascript">
function replace() {
//Replace < and > on textarea
var obj = document.getElementById('recipient_list');
var str = obj.value;
str = str.replace(/</i, "(");
str = str.replace(/>/i, ")");
obj.value = str;
alert("rec_lst.value: " + document.getElementById('recipient_list').value);
//Pass value to server.
alert("passing to server");
document.getElementById("ctl00$ContentPlaceHolder1$txtEmails").value = str;
alert("Passed to server");
alert("txtEmails.value: " + document.getElementById("ctl00$ContentPlaceHolder1$txtEmails").value);
}
</script>
This isn't working though... Any ideas how to fix or better implement this??..
Try this:
var txtEmail = document.getElementById("<%=txtEmails.ClientID%>");
txtEmail.value = str;
However this won't pass anything to the server, just change text box value.
To have it sent to the server user will have to click submit button, or if you have server side button have such code to "auto click" it thus performing post back:
document.getElementById("<%=btnSubmit.ClientID%>").click();
you cant pass value from client to server using JS .
JS is only a client side code.If you can do something like this, Hacking will be so easy :)
one thing you can do is add some text or label control as invisible and assign the value to the control and pass it to server when some event happens.
Sample code
<asp:TextBox ID="textbox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="callOnEvets()"/>
function callOnEvets()
{document.getElementById('textbox1').value = 10; }

Categories

Resources