Hide/Show form based on Dropdownbox selection - c#

I have looked around and haven't found anything concrete.
Is there any tutorials on how to show/hide a form or textbox based on if a value is selected.
I have something like this Dropdown box with (Add, item1, item2,item3 ect..)
if add is selected show a form to add add with some attributes such as (First Name, last Name ect..) else it will just do an action with the selected item.

<select id="target">
<option value="option1" selected="selected">Add</option>
<option value="option2">Item1</option>
</select>
<input type="text" class="textboxclass" />
<div class="someform">
//content
</div>
Default css display property for someform class is none eg:
.someform{display:none;}
Jquery script
<script>
$('#target').change(function() {
var name = $('#target option:selected'),text(); //Item1
var id = $('#target').val(); // option2
if(id =="option2"){
//your logic for this option
//hide textbox
$('.textboxclass').hide();
$('.someform').show();
}else{
$('.textboxclass').show();
$('.someform').hide();
}
//other if else logic
});
</script>
Not tested since im on laptop without any software installed.

I would wire this up in the client-code. Handle the select's onchange event in JavaScript or jQuery and bind a handler to it. Since "Add" is the only one that will show the form, in your handler check for the value selected and if it's the value for "Add", show the form. If it's any other value, hide the form.
If you want to do this in the server code, just handle the event for the selection changed and set the visibility property of your form that way. Either way should be pretty easy.
Doing this on the client allows you to avoid coding around postbacks while removing responsibility of processing the request from the server.

if you want to do this from server side you will need to set the AutoPostBack propetry of DrowpDown list to true,
and in the SelectedIndexChanged event of DropdownList
try this,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
entryForm.Visible = true;
viewForm.Visible = false;
}
else if (DropDownList1.SelectedIndex == 1)
{
entryForm.Visible = false;
viewForm.Visible = true;
}
but this is not a good aproach, i will suggest to follow the answers given above, and do it with JavaScript or JQuery

Related

How manage two jQuery and c# event of one div?

I have a div like below I want to do some work when I click div:
with jQuery click I want to show another div that contain ListView (that must show messages) and by another click hide that div.
with C# click event I want to get Messages and bind to ListView
jQuery works but C# event does not work.
Another problem is that if I click div for second time the div will hide and I don't want bind messages
How should I do these works?
<div id="div1" class="Message" runat="server" onclick="ShowMessage">
jquery code:(this works)
$('#div1').click(function (e) {
e.stopPropagation();
if ($("#div2").is(":hidden")) {
$("#div2").show(500);
}
else {
$("#div2").hide(500);
}
});
and my code behind:(does not work)
protected void ShowMessage(object sender, MouseEventArgs e)//this will bind messages to ListView inside of div2
{
using (MYEntities en = new MyEntities())
{
///...
}
}
If you are using button then javascript click event of the button will get call and at the end just write return true then it will go to ServerSide click event of the button.
$('#btnClick').click(function(){
// your code
return true;
}
Protected void btnClick_Click()
{
}

how change textbox text after clicking on a button inside a gridview

i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>

Custom Validation when TextBox has value and CheckBox does not

I have a situauation that I need to check on a button click if the user has entered a value into a textbox, but have not checked a checkbox. They need to be advised that they can not enter a value in the textbox without first checking the checkbox. I know I need to use a CustomValidator Control, but other than that I'm lost. Can anyone help me?
In OnClientClick event you can call a javascript method which will do this validation for you.
This should point you in the right direction.
I think the easiest way to do so will be enabling/disabling the textbox base on whether the checkbox is checked.
However, if you want to do the check on button_click, maybe just do checks on both the checkbox and textbox? And output error message to a label or something?
if(TextBox1.Text.Trim() != "")
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
Or, you can do checks when TextBox1.Text has changed.
private void Textbox1_TextChanged(object sender, EventArgs e)
{
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
}
You can implement this functality using javascript/Jquery.Set the onClientClick property of button as below:
<asp:Button ID="btnSubmit" runat="server" onClientClick="ValidateData();"/>
Below is the jquery code:
function ValidateData()
{
if(!$('#checkboxID').is(':checked') && $.trim($('#textBoxID').val())!='')
{
alert('Please check the checkbox before entering text');
}
}
You can try this...
First you must have a button like this...
<asp:Button ID="btnCheck" runat="server" CssClass="m-btn purple" Text="Check" onclintclick="Validate()"/>
Now we can write the validation script...
<script type="text/javascript" language="javascript">
function Validate() {
if(document.getelementid('checkbox1').checked==true)
{
if(document.getelementid('Textbox1').value=="")
{
//Write your code here..
}
}
else
{
alert('Please check the checkbox..');
}
}
</script>
Please feel free to mark as answer if it satisfies you....

Hide button on drop down selection -1

I need my create button to be hidden unless a facility is selected in my dropdown. When it is at -1 message i need my button to be hidden.
Code for button
<asp:Button ID="btnCreate" runat="server" Text="Create New" Width="89px" Font-Size="X-Small" OnClick="btnCreate_Click" />
Drop down code
private void ResetForm()
{
try
{
//facility dropdown
ddlFacility2.Items.Clear();
ddlFacility2.DataSource = this.DataLayer.model.MS_spGetFacilityInfo(null).OrderBy(x => x.FacilityName);
ddlFacility2.DataTextField = "FacilityName";
ddlFacility2.DataValueField = "FacilityID";
ddlFacility2.DataBind();
ddlFacility2.Items.Insert(0, new ListItem("All Facility Records..", "-1"));
BindGrid();
}
catch (Exception ex)
{
this.SetMessage(ex.ToString(), PageMessageType.Error);
AISLogger.WriteException(ex);
}
}
in first time page load if the default value selected is -1 you can set your button visible false as default.
in your droupdown list selected index change event you can enable/dissable button based on droupdown list selected value.
Add a OnSelectedIndexChange event to your dropdown list or add a clientside event to your dropdownlist. Double Click on your ddl you will see a function named ddlFacility2_OnSelectedIndexChanged in you code behind and add the below code to it.
Add AutoPostBack=true to you ddl
protected void ddlFacility2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if(ddlFacility2.SelectedIndex>-1)
{
btnCreate.Enabled = true;
}
else
{
btnCreate.Enabled = false;
}
}
You can wire up a JQuery script that can bind to your DropDownList's selected value...
In this example, the button's visibility is bound on a click from another button:
$('#Button1').bind("click", function() {
$("#Button2").hide();
});
I dont know the exact syntax to use for the binding to selected value, but the above code should be a good place to start.

End user add values to a dropdownlist?

I'm populating a dropdownlist in c# asp.net-MVC from a SQL table using Linq2Sql. I'd like for the user to be able to enter something that isn't in the list into the drop down and have it add to the table. Is this possible?
Sounds like you need to add a radio button labeled "Other". When the user clicks the radio button a text box would appear that allows the user to input a new value that you can save to your DB and display in the drop down.
EDIT:
Quick snippet to enable the control using JavaScript:
<script language="javascript" type="text/javascript">
function radioclicked() {
textObj = document.getElementById('<NAME OF TEXT BOX');
textObj.disabled = false;
}
</script>
You can use a check box instead of a radio button so that the enabled property can be toggled.
To completely hide the text box then you will have to look into jQuery/Ajax.
Why can't we use a lightweight Add-on like www.combodropdown.info for this purpose? You can even consider AutoComplete plugin from jQuery, if your app already references jQuery.
Also a combobox will allow a user to enter a value in addition to picking from a list.
My MVC is not so so, but I assume this still applies as MVC is just model view controller.
What if you throw a drop down on your form visible=true, and a textbox on your form visible =false.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>
Fill your drop down:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> s = Enumerable.Range(1, 10).ToList();
DropDownList1.DataSource = s;
DropDownList1.DataBind();
DropDownList1.Items.Add("Other");
}
}
Add an event to handle if someone selects other. If they do make the textbox visible:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.DropDownList1.SelectedItem.Text)
{
case "Other":
this.TextBox1.Visible=true;
break;
default:
this.TextBox1.Visible=false;
break;
}
}
Now you can enter your value and re-store back to the db.

Categories

Resources