Is it possible to place two buttons in the same position in an aspx page. Depending on some condition, it has to display one among them.
<asp:ImageButton ID="btnapply" ImageUrl="../images/apply.gif" runat="server"
ImageAlign="Right" OnClick="imgApply_Click" ValidationGroup="0" />
<asp:ImageButton ID="btnremove" ImageUrl="../images/remove.gif" runat="server"
ImageAlign="Right" OnClick="imgremove_Click" ValidationGroup="0" />
Option 1: If you can make the decision as the page is rendered, i.e. server-side:
In your code-behind:
protected void Page_Load()
{
if (variableToSwitchOn == true)
{
button1.Visible = true;
button2.Visible = false;
}
else
{
button1.Visible = false;
button2.Visible = true;
}
}
In your .aspx page:
<div>
<asp:button runat="server" ID="button1" Text="Button 1" />
<asp:button runat="server" ID="button2" Text="Button 2" />
</div>
Option 2: If you need to make the decision client-side
In your .aspx page:
<div>
<asp:button runat="server" ID="button1" Text="Button 1" />
<asp:button runat="server" ID="button2" Text="Button 2" />
</div>
<script language="javascript" type="text/javascript">
var button1Id = '<%=button1.ClientId%>';
var button2Id = '<%=button2.ClientId%>';
</script>
You can now have a piece of javascript that controls whether the buttons are visible, for example:
function ChangeWhichButtonIsVisible()
{
var button1 = document.getElementById(button1Id);
var button2 = document.getElementById(button2Id);
if (someCondition == true)
{
button1.style.display = 'none';
button2.style.display = 'block';
}
else
{
button1.style.display = 'block';
button2.style.display = 'none';
}
}
Why not use one button and change the text and action based on the said condition?
Sure. Put them each in a DIV, and hide/show those DIVs as appropriate. To expand a little:
<div id="button1" style="display:none">Button 1 goes here</div>
<div id="button2" style="display:block">Button 2 goes here</div>
And then you can toggle the display with a bit of Javascript:
function showHide() {
if (document.getElementById("button1").style.display == "none")) {
document.getElementById("button1").style.display = "block";
document.getElementById("button2").style.display = "none";
} else {
document.getElementById("button1").style.display = "none";
document.getElementById("button2").style.display = "block";
}
}
Instead of using two buttons change the properties of the button based on the condition in the code behind or do the same in the Client side with CSS/Java Scripting.
Related
I have been trying to create a radio button that shows/hides the two drop-down lists when they are unchecked and checked.
My problem is that whenever I try to check another radio button, the drop-down list for the other radio button does not hide as intended. For example, if I checked rbtnTwocolor, the drop-down list for rbtnOnecolor does not hide.
I wanted to use radio button list but I couldn't insert a drop-down list in between the radio button list items.
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>
for show/hide dropdown when select radiobutton , you can use ways below :
1: use jquery in client side:
<script>
$(document).ready(function () {
$('#rbtnTwoColor').change(
function () {
if ($(this).is(':checked')) {
$('#twocolor').show();
$('#onecolor').hide();
}
});
$('#rbtnOneColor').change(
function () {
if ($(this).is(':checked')) {
$('#onecolor').show();
$('#twocolor').hide();
}
});
});
</script>
2: use server side event (OnCheckedChanged):
markup:
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor"runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnTwoColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnOneColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>
and code behind:
protected void rbtnTwoColor_CheckedChanged(object sender, EventArgs e)
{
ddlTwoColor.Visible = true;
ddlOneColor.Visible = false;
}
protected void rbtnOneColor_CheckedChanged(object sender, EventArgs e)
{
ddlOneColor.Visible = true;
ddlTwoColor.Visible = false;
}
3: use javascript in client side:
add below code to rbtnTwoColor radiobutton
onclick="twoColorClick()"
add below code to rbtnOneColor radiobutton
onclick="oneColorClick()"
now in end of body tag add this code
<script>
function oneColorClick() {
document.getElementById('onecolor').style.display = 'block';
document.getElementById('twocolor').style.display = 'none';
}
function twoColorClick() {
document.getElementById('twocolor').style.display = 'block';
document.getElementById('onecolor').style.display = 'none';
}
</script>
good luck
I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}
I have a textbox, on click, it allows you to select date from calendar control. If the date is deleted, it should uncheck the checkbox available just next to the textbox.
With below code, I am able to achieve everything other than making the textbox readonly so that user is not able to type anything. Also, once the text is selected, checkbox gets checked but when text is deleted the checkbox doesn't get unchecked.
Can anyone suggest what needs I might be doing wrong here ?
<asp:CalendarExtender ID="CalForDate" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" PopupPosition="BottomLeft" DefaultView="Days"></asp:CalendarExtender>
<asp:TextBox runat="server" ID="txtDate" AutoPostBack="true" EnableViewState = "false" onKeyPress="javascript:return ChkCheckBox()" OnTextChanged="txtDate_OnTextChanged"></asp:TextBox>
The javascript code:
function ChkCheckBox() {
var txtDate = document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_txtDate').value;
if (txtDate.length == 9) {
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = true;
}
else
{
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = false;
}
In pageload I have added:
if (!IsPostBack){
txtDate.Attributes.Add("readonly", "readonly");}
And on text changed:
public void txtDate_OnTextChanged(object o, EventArgs e){
if (!(string.IsNullOrEmpty(txtDate.Text)))
{
chkDate.Visible = true;
chkDate.Checked = true;
}
else
{
chkDate.Visible = true;
chkDate.Checked = false;
} }
You can easily achieve this using jquery. I am sending you the sample code. Please don't hesitate to ask further assistance if needed.
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').on('change', function () {
//console.log('Tested');
if ($(this).val().toString().trim() != '') {
$('[Id*=ckTest]').attr('checked', 'checked');
}
else {
$('[Id*=ckTest]').removeAttr('checked');
}
});
$('#btnClear').click(function () {
$('#txtDate').val('');
$('#txtDate').trigger('change');
});
});
</script>
The code file is as below.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" ClientIDMode="Static"></asp:TextBox>
<asp:CheckBox ID="ckTest" runat="server" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" />
<button id="btnClear">Clear</button>
</div>
</form>
Just add jquery to project i used
jquery-2.1.4.min.js
Long story short I need to have one dropdownlist (ddlGenres) hide until the user clicks "Genre" in ddlSearchOptions. To do this without a postback I made a simple script but in order for this script to work I needed to set ddlGenres' style to display:none. The problem is that after a postback ddlGenres hides again because of that property.
I need to figure out how to keep it visible after a postback.
<script type="text/javascript">
$(document).ready(function () {
$('#ddlSearchOptions').change(function (e) {
e.p
if (this.value == "Genre") {
$('#ddlGenres').show();
}
else {
$('#ddlGenres').hide();
}
});
});
</script>
<div class="jumbotron">
<h1>Find a book...</h1>
<p>
<asp:TextBox ID="txtFindBook" runat="server" CssClass="DefaultPageSearchBox"></asp:TextBox>
<asp:DropDownList ID="ddlSearchOptions" ClientIDMode="Static" runat="server">
<asp:ListItem>Keyword</asp:ListItem>
<asp:ListItem>Title</asp:ListItem>
<asp:ListItem>Author</asp:ListItem>
<asp:ListItem>Genre</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlGenres" runat="server" style="display:none" ClientIDMode="Static"></asp:DropDownList>
<asp:Button ID="btnFindBook" runat="server" Text="Search" OnClick="btnFindBook_Click" Height="36px" />
<p>Enter your search terms in the box above, then click "Search" to begin your search.</p>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
The condition you're writing in change event, just put it outside the event too. To run it on document ready:
$(document).ready(function () {
//check "ddlSearchOptions" initial value
if ($('#ddlSearchOptions').value == "Genre") {
$('#ddlGenres').show();
}
else {
$('#ddlGenres').hide();
}
//subscribe event handler
$('#ddlSearchOptions').change(function (e) {
e.p
if (this.value == "Genre") {
$('#ddlGenres').show();
}
else {
$('#ddlGenres').hide();
}
});
});
It feels so good to answer my own question though all of your help has led up to this.
What I did was simply add this:
if(<%=(Page.IsPostBack).ToString().ToLower()%>){$('.genre-list').show();}
You can also use this as a !IsPostBack statement.
if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){$('.genre-list').show();}
JavaScript:
<script type="text/javascript">
$(document).ready(function ()
{
//check "ddlSearchOptions" initial value
if ($('.search-optins').value == "Genre")
{
$('.genre-list').show();
}
else
{
$('.genre-list').hide();
}
//subscribe event handler
$('.search-optins').change(function (e)
{
e.p
if (this.value == "Genre")
{
$('.genre-list').show();
}
else {
$('.genre-list').hide();
}
});
if(<%=(Page.IsPostBack).ToString().ToLower()%>){$('.genre-list').show();}
});
</script>
Drop Down Lists:
<asp:DropDownList ID="ddlSearchOptions" CssClass="search-optins" ClientIDMode="Static" runat="server">
<asp:ListItem>Keyword</asp:ListItem>
<asp:ListItem>Title</asp:ListItem>
<asp:ListItem>Author</asp:ListItem>
<asp:ListItem>Genre</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlGenres" CssClass="genre-list" runat="server" ClientIDMode="Static"></asp:DropDownList>
It seems I am struggling with the order of the page life cycle. Based on the user selecting button 1 or 2, I need to have respective controls added dynamically during the Page_Load event. My problem is when a button is clicked the Page_Load event is executed before Button_Click event code is read. There for my variable "doWhat" is not assigned a value until after the Page_Load event. How can I have the "doWhat" variable assigned a value to be read during the Page_Load?
Below is asp.net form code for the two buttons:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Below is the code behind:
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
doWhat = Convert.ToUInt16(ViewState["doWhat"]);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.ID == "Button1")
{
doWhat = 1;
}
else
{
doWhat = 2;
}
ViewState.Add("doWhat", doWhat);
}
If you are comfortable with javascript then you can achieve it by making following changes in your design and code. Add a hidden field in your aspx page. Your HTML code should be like this.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" OnClientClick="return doWhatAction(1);" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" OnClientClick="return doWhatAction(2);" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />
<script type="text/javascript">
var doWhatAction = function (actionIndex) {
//alert(actionIndex);
document.getElementById("<%=HiddenField1.ClientID%>").value = actionIndex;
return true;
}
</script>
</div>
</form>
And your code will be something like...
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
//doWhat = Convert.ToUInt16(ViewState["doWhat"]);
doWhat = Convert.ToUInt16(HiddenField1.Value);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
//Do Nothing
//Button btn = sender as Button;
//if (btn.ID == "Button1")
//{
// doWhat = 1;
//}
//else
//{
// doWhat = 2;
//}
//ViewState.Add("doWhat", doWhat);
}
You can use jquery or javascript i this case.
Took on hidden variable in form
initialize it on click event of button in javascript
Read value of hidden variable in page load
<head >
<title>Hidden Variable</title>
<script type="text/javascript">
function SetHDNValue()
{
var hdnControlID = '<%= hdnControl.ClientID %>';
document.getElementById(hdnControlID).value=1;
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="hdnControl" type="hidden" runat="server" />
<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="SetHDNValue()"
/>
</div>
</form>
</body>
And in code behind file hdnControl.value
Since long ago I am not working with asp.net forms. And forgot doing things.But I found how you can do. As on stackoverflow link like answers is wrong. I copied main statements from the link which indicate how post-back events works and how you can use it for your purpose. For more http://aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
Here is how generated __doPostBack looks:
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</script>
The __doPostBack function simply stores the below two arguments in two hidden fields
eventTarget – The name of the control that caused the postback
eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true
Finally, here is how you can distinguish by getting control's ID that caused the postback :
if (IsPostBack)
{
string CtrlID = string.Empty;
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] != string.Empty)
{
CtrlID = Request.Form["__EVENTTARGET"];
/****implement Your logic depending on control ID****/
}
}