Client side keypress handling event, set focus function, and __doPostBack ASP.NET - javascript

I'm trying to do the following :
First, a textBox get the focus on page load (no problem here)
Then, when ENTER button is pressed inside that textBox, it switch focus to the second textBox.
Finally, when ENTER is pressed in that second textBox, it does a postback and reahes code behind event just like when you press a classic <asp:button />
Based on :
Fire event on enter key press for a textbox
and
JavaScript set focus to HTML form element
I managed to come up with :
HTML :
<asp:TextBox ID="txtNNoSerie" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventFirst(event)" AutoPostBack="false"></asp:TextBox>
<asp:TextBox ID="txtNNoIdentification" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventSecond(event)" AutoPostBack="false"></asp:TextBox>
<asp:Button id="btnAjouter" CssClass="ms-Button ms-Button--primary" onclick="btnAjouter_click" Text="+" ForeColor="White" runat="server" Width="30px" />
<input type="text" id="txtTest" /> <%-- Just for tests --%>
JS :
function EnterEventFirst(e) {
if (e.keyCode == 13) {
document.getElementById('txtTest').value = 'got it';
document.getElementById('<%=txtNNoIdentification.ClientID%>').focus();
}
}
function EnterEventSecond(e) {
if (e.keyCode == 13) {
document.getElementById('txtTest').value = 'Again';
__doPostBack('<%=btnAjouter.ClientID%>', "");
}
}
Code behind :
protected void btnAjouter_click(object sender, EventArgs e)
{
}
JavaScript functions are reached, because i can see "got it" and "Again" in the test TextBox, but just for half a second and then it desapear... The __DoPostBack funtion does not work.
Looks like when you press enter in a textBox, it automaticaly does a useless postback and page reload... And that is where i'm stuck

Use ClientID instead of UniqueID.

Well, textBox automaticaly postBack when enter is pressed, ok then.
I did it all on server side, I hate this but i kinda had no choice :
txtNNoSerie.Focus();
if (txtNNoSerie.Text != "")
txtNNoIdentification.Focus();
if (txtNNoSerie.Text != "" && txtNNoIdentification.Text != "")
btnAjouter_click(this, new EventArgs());
Server side code... If anyone can show me some working client side code i'll take it...

Related

C# method skipping over java script call

I have an ASP button that has an event listener attached to it. When pressed it calls the C# method and executes whatever code I may have within it.
I have a javascript function I want to call when the listener first executes. However, C# completely skips over the function call and moves on to the lines below it.
Here's the question: Why is it skipping over the call? And when I isolate just the call, ( have nothing in the method other than the call) IT WORKS. The very second I put another line of code below it, it stops being called. Any help would be greatly appreciated.
Here is the ASP button.
<asp:Button ID="crapJim" runat="server" Text="RateTest" OnClick="crapJim_Click"/>
And here is the C# Method
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
/* ClientScript.RegisterStartupScript(GetType(), "hwa", "getSessionName();", true);*/
string s = hfRaterName.Value;
Console.Write(s);
string stop = "";
}
Currently have the ClientScript commented out and trying the ScriptManager. Both work individually, but not when other code is with it. What I mean by that is:
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
}
Just this alone will work, but any other code with it, it will no longer fire. C# skips over it.
Oh and here is the Javascript code I am using.
function getSessionName() {
var hfRaterName = prompt("Please enter your session name");
hfRaterName.value = hfRaterName;
}
There's an easier way, if you don't have to use RegisterStartupScript.
.aspx:
// OnClientClick will call your javascript function first, then the code behind.
<asp:Button ID="btnPrompt" runat="server" Text="Prompt"
OnClientClick="doPrompt();"
OnClick="btnPrompt_Click" />
<br />
<asp:Label ID="lblPromptResult" runat="server"></asp:Label>
<br />
<asp:HiddenField ID="hfPrompt" runat="server" />
<br />
<script>
function doPrompt() {
document.getElementById("hfPrompt").value =
prompt("Please enter your session name");
}
</script>
Code behind:
protected void btnPrompt_Click(object sender, EventArgs e)
{
lblPromptResult.Text = hfPrompt.Value;
}
In the case anyone else comes across this same problem. I took wazz's advice and used the OnclientClick along with Onclick. Executing the Javascript first rather than having the C# call the Javascript.
//This is the HiddenField used to capture the users identified session name
//which I then store in a DB and use in a few other related pages.
<asp:HiddenField ID="HiddenField1" ClientIDMode="Static" runat="server" />
//This is the ASP button used to call both the Javascript and C# code behind
<asp:Button ID="btnRateBeazely" ClientIDMode="Static" runat="server" CssClass="btnbig" Text="Rate Beazley" OnClick="btnRateBeazely_Click" OnClientClick="getSessionName();" />
//The Javascript is simple, but does exactly what I want it to. DB has character
//limit to 50 so I ensure the user can't input higher than that. Assign the input
//to the hiddenfield ID and off we go.
function getSessionName() {
var SessionSet = prompt("Please enter your session name");
while (SessionSet.length > 49) {
alert("You have too many characters. Please enter again.")
var SessionSet = prompt("Please reenter your session name");
}
document.getElementById("HiddenField1").value = SessionSet;
}
//In the code behind I just assign a new string variable to the hidden field value

How to focus a error after disable button 1st click using asp.net?

I have written code in asp.net for disable button after 1st click. Code is below:
<asp:Button ID="btnNext" runat="server" CssClass="btn btnBlue btnStep" Text="Submit"
OnClick="btnSubmit_Click" CausesValidation="true" ValidationGroup="ServiceFee" OnClientClick="this.disabled = true; this.value = 'In progress...';__doPostBack('btnNext','')" UseSubmitBehavior="false" />
It is working fine no problem but now I need to add little extra functionality i.e. I need to focus on error. When user clicks on submit button without entering card details or personal details it will show error at empty text box and suddenly page will reload, because i have written dopostback in javascript. So how to focus on error and after postback need to show error?
In the btnNext event you can have something like
// Supose txtCardDetails is the TextBox with the card details
if (string.IsNullOrWhiteSpace(txtCardDetails.Text))
{
ClientScript.RegisterStartupScript(this.GetType(), "script", "document.getElementById('" + txtCardDetails.ClientID + "').focus();");
return; // Maybe you want to do something before leave the event method
}
this will send a script to focus the field, BUT, I recommend to do the validation in the client side (JS) and in the Server side (C#), so, validating this in the client side should be like this
<asp:Button ID="btnNext" runat="server" ...
OnClientClick="return SubmitIfValid(this);" ... />
function SubmitIfValid(el) {
if(document.getElementById('<%= txtCardDetails.ClientID %>').value === ''){
alert('invalid card details');
document.getElementById('<%= txtCardDetails.ClientID %>').focus();
return false;
}
// more validations
// if all is OK then...
el.disabled = true;
el.value = 'In progress...';
__doPostBack('btnNext','')
return true;
}
You can use validation controls like validationSummary. Managing errors like those by yourself can be very difficult.

Send Command.Value via Javascript to codebehind

I am fairly new to ASP.Net and I am stuck.
If my Hyperlink is clicked a Command.Value should be sent to the server. After getting that Command.Value the code behind should check if it is right and redirect to a specific site otherwise just reload the page.
Here is my Hyperlink:
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.FormServer.Command.value =
'test';document.FormServer.submit();"
>Test!!</asp:HyperLink>
First of all I want to ask if my Hyperlink is right. Furthermore I am a bit stuck on the code behind regarding where I need to insert my If statement.
I believe it's much easier to send a parameter by GET in the url of your link. But if for any reason you want to do it by post and using javascript then try this.
Web form: param1 is a hidden field which value will be set using Javascript. When the form is submitted the hidden field is posted with the form.
<form id="FormServer" runat="server" >
<input type="text" id="param1" name="param1" style="display:none;" />
<div>
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.getElementById('param1').value = 'test';document.forms['FormServer'].submit();"
>Test!!</asp:HyperLink>
</div>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
string param1Value = Request["param1"];
if (param1Value == "test")
Response.Redirect("~/Default.aspx");
else if(param1Value == "lost")
Response.Redirect("http://www.google.com");
}
In the code behind it might be useful to check this.IsPostBack. That tells you why the page is being loaded. If it's because the link was clicked then IsPostBack will be true.

how to disable button after first click in javascript

I am new to C#. I have a save button inside InsertItemTemplate. I have used the following code to disable the button after first click in java script but its not even working for the first click please help me.
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="this.disabled='true';return true;" />
You are modifying the "disabled" property of the DOM object on the browser, but the button will do a post back to the server when it's clicked, so any change to the DOM will be lost.
On the function where you handle the command "Add" in your server code you must retrieve the button from the InsertItemTemplate and set its "Enabled" property to false, that will disable the control from the server side.
If you want to avoid multiple clicks while the page has not been reloaded then you need a client function to avoid this, something like this:
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="return checkEnabled(this);" />
<!-- somewhere in your page -->
<script>
function checkEnabled(item)
{
if(item.disabled != 'true')
{
item.disabled = 'true';
return true;
}
return false;
}
</script>

Set enter key behavior on aspx form

Have the need to alter the behavior of pressing enter on my aspx page based on the last control that was interacted with. I have two textboxes and a dropdown. Each one of those controls has a corresponding button that takes the input and applies it to other fields on the page. Much like adding options to a master part.
Example: If button2 is pressed, the option in textbox2 would be applied, but not the option in textbox1, or the dropdown. The page is refreshed, and the user can continue to select options.
How would I alter the page to allow the user to type in text in a textbox and then hit enter to activate the code for the corresponding button. I've tried various js to set the page default, but have been unsuccesseful in changing this on the fly.
You can use ASP.Net Panel control's DefaultButton to accept enter key.
http://geekswithblogs.net/ranganh/archive/2006/04/12/74951.aspx
<asp:Panel ID="pnl1" runat="server" defaultbutton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" defaultbutton="Button2">
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
</asp:Panel>
Set event listeners for a user modifying the inputs and set a reference to the proper button. Then have a listener for the enter button to trigger submitting the referenced button. You didn't mention jQuery or any JS framework so I'll try writing it generally for plain javascript, I'd recommend using a framework though for cross browser support.
var myButtonId = null;
var storeInputButtonId = function(buttonId) {
return function(event) {
myButtonId = buttonId;
};
};
//Do following for inputs, or your preferred event binding pattern
var fld = document.getElementById('myInputId');
//Statically refer to button id or replace with suitable algorithm
var inputButtonId = "";
if (fld.addEventListener) {
//Could bind to other events with logic based on input element type
fld.addEventListener('keyup',storeInputButtonId(inputButtonId), false);
}
//Method to trigger the button click event
function submitData(event){
//Watch for the enter button
if ( event.which == 13 ){
document.getElementById(myButtonId).click();
}
}
//Bind the listener to the enter button
var bodyElement = document.getElementsByTagName('body')[0];
if (bodyElement.addEventListener) {
bodyElement.addEventListener('keydown',submitData, false);
}

Categories

Resources