Here is a part of my ASP.NET page.
<asp:DropDownList ID="DropDownList1" runat="server"
OnChange="return ListChange(this.value)"
onselectedindexchanged="DropDownList1_SelectedIndexChanged1"
AutoPostBack="True" >
<asp:ListItem Selected="True">Today</asp:ListItem>
<asp:ListItem>Yesterday</asp:ListItem>
<asp:ListItem Value="1">Specific Day</asp:ListItem>
<asp:ListItem>All Time</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
Here is the Javascript.
function ListChange(txtVal) {
if (txtVal != 1 ) {
document.getElementById("txtDate").setAttribute("style", "visibility:hidden;");
return true;
}
else {
document.getElementById("txtDate").setAttribute("style", "visibility:visible;");
return false;
}
}
Here the objective is to show certain data according to the option selected by the user. In the Specific Day option, a textbox is shown to the user to insert date through javascript. But the onselectedindexchanged event is also raised which calls to server. I want to stop the event when "specific day" option is selected, but run when other options selected.
The code on OnChange="return ListChange(this.value)" is not stopping the event as used to when using a form with button.
It is one of the options that you can use.
Remove the selected index change event from markup.
on change event , check whether your validation has ran correctly.
if they have run make ajax request and do your stuff.
you do not need to call two separate functions simultaneously. Here is some jquery code that will do the trick in just a few lines.
$(document).ready(function(){
$('#DropDownList1').change(fnction(){
if($(this).text() != 'Specific Day') {
document.getElementById("txtDate").setAttribute("style", "visibility:hidden;");
return true;
} else {
document.getElementById("txtDate").setAttribute("style", "visibility:visible;");
return false;
}
});
});
By default ASP.Net will post back if you give AutoPostBack =true.
It is not considering return values.
Below is the code rendered at execution time. it uses settimeout and executed _doPostBack for submitting Form
onchange="return ListChange(this);setTimeout('__doPostBack(\'ctl00$MainContent$DropDownList1\',\'\')', 0)"
We need to think about stopping a form submit by setting a flag like Page_IsValid=false;
I would suggest that you do the show & hide using the .net code.
For example in VB.net
Put the following code in the DropDownList1_SelectedIndexChanged1 sub.
If DropDownList1.SelectedValue = "1" Then
txtDate.Visible = True
Else
txtDate.Visible = False
End If
Rather than have 3 different on click/change events.
Then remove the JS and the on change and on client click events, just leave it with onselectedindexchanged="DropDownList1_SelectedIndexChanged1"
UPDATE:
If you want to avoid postback for some events in your code do :
If isPostBack = True
//Don't fill form stuff
Else
//Fill form stuff
End If
First try to check what value is coming in your javascript function.
If its not showing the selceted value use the following code
var index = document.getElementById(selectItem).selectedIndex;
alert("value =" + document.getElementById(selectItem).value);
alert("text =" + document.getElementById(selectItem).options[index].text);
or using jQuery
$("#yourdropdownid option:selected").text();
Related
Java Script
function outputtax()
{
var tamount = parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value);
var cash = parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value);
if (isNaN(tamount) != true && isNaN(cash) != true && isNaN(tax) != true)
{
document.getElementById('<%=txtPtotalamout.ClientID%>').value =
Math.round(parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value)
- parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value))
return false;
}
}
<asp:TextBox ID="txtPtotalamout" runat="server" ReadOnly="true">
</asp:TextBox>
.CS
objsupplyPL.totalamount = Convert.ToDouble(txtPtotalamout.Text.ToString());
Value is displaying on the textbox but when i click save button txtptotalamount is getting
null value.If I placed readonly="false" it's working fine.
From http://codecorner.galanter.net/2009/10/09/postback-disabled-textbox/
Let’s say in your ASP.NET application you set a TextBox control’s property ReadOnly to True (or Enabled to False) to prevent user from entering data directly. But you still want to update that text box’s value via client-side JavaScript. Which is happening, the value can be updated. But during postback to the server – surprise, surprise! – the new value doesn’t persist. This is due to security precaution – if the value wasn’t meant to be changed – the change is not allowed. But there is a way around this.
The trick is - to keep ReadOnly = False and Enabled = True and simulate their behavior. Add following line of to your server-side code:
TextBox1.Attributes["onclick"] = "this.blur();"
where TextBox1 is your textbox control. What this line does is adds client-side behavior to the textbox. As soon as user tries to click the textbox, focus immediately gets lost, preventing user from entering data, making the textbox essentially read-only. For further effect you can set the texbox’s background to something like “LightGray” making it appear disabled.
You want to be able to save the result from the "txtPtotalamout" but you don't want it to be editable.
You could just use
<div id="PTotalAmount"><asp:Label id="PTotalAmount" runat="server" /></div>
<asp:HiddenField ID="hPTotalAmount" runat="server" />
To display it, and update the contents of that DIV and the hidden field in the javascript.
Then you could display the total amount in that DIV when you load the form (and populate the hidden field). You could even format the DIV to look like a text box if you wanted.
Im trying to have my drop down list make four controls visible on the selectedindexchanged event for the control.
Basically when the user chooses "Server" from the drop down list the event should fire and the user should see two extra options.
Tried a tonne of approaches so far including text_changed event but nothing.
Here is what i got so far
//adds new fields to the form when the user selects server as the asset type
protected void AddNewFields(object sender, EventArgs e)
{
//If the asset is a server then make the extra controls available
if (TypeDDL.Text.Equals("Server"))
{
DNLabel.Visible.Equals(true);
//DNLabel.Visible = true;
DomainNameTB.Visible = true;
RoleLabel.Visible = true;
RoleDDL.Visible = true;
}
}
<asp:DropDownList ID="TypeDDL" runat="server" DataSourceID="AssetTypeDS"
DataTextField="AssetTypeDescription" DataValueField="AssetTypeID" OnTextChanged="AddNewFields">
</asp:DropDownList>
Add AutoPostback="True" to your DropDownList and the above code should trigger
As for an explanation: The drop down list doesn't automatically post back to the server. Changing a selection happens on the client side. Once you add the above, it'll repost the page. If you don't want the whole page to flicker each time someone changes a selection, you can either use some client side Javascript or Jquery, or use an asp:UpdatePanel
Please set AutoPostBack="True" property of a DropdownList...
add AutoPostBack="true" in dropdown
<asp:DropDownList ID="TypeDDL" runat="server" DataSourceID="AssetTypeDS" AutoPostBack="true"
DataTextField="AssetTypeDescription" DataValueField="AssetTypeID" OnTextChanged="AddNewFields">
</asp:DropDownList>
I have the following text box control ;
<asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
OnTextChanged="txtAmount_TextChanged" ></asp:TextBox>
Here, if there any value change in the text box , txtAmount_TextChanged will be called because AutoPostBack="true" is there in the control.
So if we put a non numeric value in the textbox, validation error will fire from the attribute Class using Jquery, but this error which pops up as a red box from the textbox wont stays for more than 3 seconds, it vanishes when the page posts back within 3 seconds, This post back is happening just because there is a AutopostBack="true".
I cannot do Autopostback="false" because, I need to do some calculation based on this text box value change on the spot.
If I do Autopostback="false", page will not post back and error message stays for ever, but I cannot do any calculations on "txtAmount_TextChanged" event as this event will never be called on textchcange if Autopostback="false".
So, what I do to prevent this postback, if there is any validation error in this textbox?
function txtAmount_TextChanged(){
//do validations here, Eg: validate if txtAmount is valid amount and "> 0"
return false; //if somethings's wrong, else true
}
You'll need to add a client-side event handler, and return false from it when you don't want a PostBack to happen.
<asp:TextBox onkeydown="return doMyCheck()" ID="txtAmount" runat="server"
AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
OnTextChanged="txtAmount_TextChanged"></asp:TextBox>
JavaScript:
function doMyCheck() {
if (// call your jQuery validity check)
return false;
}
Use Input event to check the added text in Textbox using jquery
jQuery('#txtAmount').live('input', function()
{
// do your Validation
// If Valid return True
// If Invalid Return False
}
)
you can use jquery change function
$('#txtbox').change(function() { if(validationfail){return false;} );
you can use keychange event also
$('#txtbox').keyup(function() {
if(validationfail){return false;}
});
I know this is a basic question, but I am curious as to what the different options are, and what the best practice would be.
If I have a form that is responsible for saving reservations into a system, how can I prevent the form from being posted twice if the user hits the button twice really quickly?
I know there are a few ways in which I can accomplish this, but I am not quite sure which is the standard way of preventing this. Partially because I am new to web forms, and am used to dealing with MVC.
Thanks ahead of time.
I've used two approaches to this problem:
Use a token based approach. Each page has a hidden input with the current random token. This token is also stored in the user's session. Once the postback occurrs, I compare tokens and, if they are valid, generate a new session token and continue processing. When the second postback occurs, the token no longer matches and prevents processing.
Use javascript to disable the submit button. If you take this approach, and need the button event handler to fire, you'll need to create a hidden input with the name attribute of the button before submitting. The hidden input is required because disabled inputs do not end up in the post data.
I would recommend a client-side onClick event handler that disables the button or makes it invisible, preferably the latter, and replace the button with a label that reads "Processing..." or something like this
I have been using something like this when using an asp:Button for submitting:
1) Set the submit button's UseSubmitBehavior="false"
2) Set the submit button's OnClientClick="pleaseWait(this, 'Please Wait...');"
3) Include javascript code in the page:
function pleaseWait(obj, message) {
if (typeof(Page_ClientValidate) == 'function') {
if (Page_ClientValidate()) {
obj.disabled = true;
obj.value = message;
return true;
}
}
return false;
}
This solution is nice because it is simple but still accounts for client-side javascript validations. It isn't perfect, because it still relies on Javascript, which could be turned off, but that's unlikely to be done by someone who doesn't have the sense to click once and wait for a response. :)
Easy way - use the ajax AnimationExtender control.http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Animation/Animation.aspx
Simply attach the extender to the button and add a disable action.
<asp:Button ID="CopyScenarioButton" ClientIDMode="Static" OnClick="CopyScenarioButton_Click"
OnClientClick="setTimeout( function() {$('#CopyScenarioButton').attr('disabled', 'disabled');},0)"
EnableViewState="false" Text="Save New Scenario" ToolTip="Save New Scenario"
CssClass="btnNormal" runat="server" />
or the later version that includes some validation first:
function PreSaveHybrid() {
var doSave = PreSave();
if (doSave !== false) //returns nothing if it's not a cancel
setTimeout(function () { $('#btnSave').attr('disabled', 'disabled'); }, 0);
return doSave;
}
In one of my web page, there are 12 checkbox controls in a div tag. I want to make sure the user check at least one checkbox in a div after they submit the form.in one of my asp.net web page. Any idea? I mean server side. I have done client side, but as you know, no one could guarantee all client browser enable javascript.
Since you're using ASP.Net, you may want to consider using the
<asp:CheckboxList />
control, and add an <asp:CustomValidator> plus validation functions that ensure one checkbox was checked.
While I agree with what others said about the validators, this code does what you want:
int i = 0;
foreach (Control ctl in myForm.FindControl("myDiv").Controls)
{
if (ctl is CheckBox)
{
if (((CheckBox)ctl).Checked)
i++;
}
}
Can you use JQuery? If so, check this out:
Get a list of checked checkboxes in a div using jQuery
Does it have to be is C#? Sounds a lot simplier if you just did it in javascript.
You want to look at the OnClientClick property of the asp:CheckBox control.
Here is an example:
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
In your javascript code (called by the handler) you can loop through all children of the div, looking for checkbox type inputs. jQuery is best for that. You could use something like this:
function countChecked() {
return $("input:checked").length;
}
That function above will return the number of checked checkboxes. After that it's trivial to validate your form. Just remember to return false from the handler called by OnClientClick to avoid a postback (in the event your form doesn't validate).
I just realized you edited your question while I was typing an answer. The above is a client side solution only.
If you just want a server side check for this and dont mind autopostback, give this a try. Just set an event handler for the SelectedIndexChanged event and check to see if an option is selected there. You can then display an error of your choice.
Here is the checkboxlist code:
<asp:CheckBoxList ID="chkBxList" runat="server" AutoPostBack="true"
onselectedindexchanged="chkBxList_SelectedIndexChanged">
<asp:ListItem>option1</asp:ListItem>
<asp:ListItem>option2</asp:ListItem>
<asp:ListItem>option3</asp:ListItem>
</asp:CheckBoxList>
<asp:Label id="lblError" runat="server"></asp:Label>
Codebehind:
protected void chkBxList_SelectedIndexChanged(object sender, EventArgs e)
{
bool oneSelected = false;
foreach (ListItem item in chkBxList.Items)
{
if (item.Selected)
oneSelected = true;
}
if (!oneSelected)
lblError.Text = "Please select an option from the checkbox list.";
else
lblError.Text = "At least one checkbox is selected";
}
Even if the client disables JS this will still make sure they choose at least one.