My web form has 2 controls, drpBloodType and rbUnknownBloodType.
I need to disable the list whenever the button is checked.
I tried:
protected void rbUnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
drpBloodType.Enabled = false;
}
and
<script>
$(function () {
$('#rbUnknownBloodType').change(function () {
if ($(this).is(':checked')) {
$('#drpBloodType').attr('disabled', 'disabled');
} else {
$('#drpBloodType').removeAttr('disabled');
}
});
});
</script>
but neither worked.
You need to assign change event handler to all radio-buttons in the same group as '#rbUnknownBloodType'. The change event on a radio-button does not fire when the radio-button becomes unchecked - the line
$('#drpBloodType').removeAttr('disabled');
in your code will never execute.
$(".test").change(function(){
console.log(this.value, this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="radio" name="test" value="1"/>
<input class="test" type="radio" name="test" value="2"/>
Hm, I looked at the picture in your question. Will a checkbox be better there?
If you have the following aspx markup you can do the following in code-behind. Note the usage of AutoPostBack="true" on the CheckBox.
<asp:DropDownList ID="BloodType" runat="server">
<asp:ListItem Text="Select..." Value=""></asp:ListItem>
<asp:ListItem Text="A+" Value="A+"></asp:ListItem>
<asp:ListItem Text="A-" Value="A-"></asp:ListItem>
<asp:ListItem Text="B+" Value="B+"></asp:ListItem>
<asp:ListItem Text="B-" Value="B-"></asp:ListItem>
<asp:ListItem Text="O+" Value="O+"></asp:ListItem>
<asp:ListItem Text="O-" Value="O-"></asp:ListItem>
<asp:ListItem Text="AB+" Value="AB+"></asp:ListItem>
<asp:ListItem Text="AB-" Value="AB-"></asp:ListItem>
</asp:DropDownList>
<asp:CheckBox ID="UnknownBloodType" OnCheckedChanged="UnknownBloodType_CheckedChanged"
runat="server" AutoPostBack="true" />
Code behind.
protected void UnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
//set the dll to default
BloodType.SelectedValue = "";
//cast the sender back to a checkbox and disable the dll based on it's checked status
BloodType.Enabled = !((CheckBox)sender).Checked;
}
Or the jquery solution. This saves a PostBack, but it loses the disabled state after a PostBack. %= UnknownBloodType.ClientID %> only works on the aspx page itself. If you do not want to use it then look into ClientIdMode=Static
<script>
$(function () {
$('#<%= UnknownBloodType.ClientID %>').change(function () {
var dll = $('#<%= BloodType.ClientID %>');
if ($(this).is(':checked')) {
dll.val('');
dll.attr('disabled', 'disabled');
} else {
dll.removeAttr('disabled');
}
});
});
</script>
Related
The issue that I am facing at getting multiple values according to dropdowns selection, it should work like this:
A user selects the first value (quantity) and then the second value which is the fruit. It should display the values selected and finally the user press the button to save all of the selected values in the database.
Here's my code:
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="lstQuota">
<asp:ListItem Text="100 units" Value="1" />
<asp:ListItem Text="50 Units" Value="2" />
<asp:ListItem Text="10 Units" Value="3" />
</asp:DropDownList>
<asp:ListBox ID="lstFruits" CssClass="DropdownList1" runat="server" SelectionMode="Multiple" AutoPostBack="true">
<asp:ListItem Text="Mango" Value="1" />
<asp:ListItem Text="Apple" Value="2" />
<asp:ListItem Text="Banana" Value="3" />
<asp:ListItem Text="Guava" Value="4" />
<asp:ListItem Text="Orange" Value="5" />
</asp:ListBox>
</div>
<asp:Button Text="Submit" runat="server" OnClick="Unnamed_Click" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('[id*=lstFruits]').multiselect({
includeSelectAllOption: true
});
$('.DropdownList1').change(function () {
alert("Handler for .change() called.");
var mySelection = $("#<%= lstQuota.ClientID %>").val();
alert(mySelection);
});
});
</script>
C# CODE:
protected void Unnamed_Click(object sender, EventArgs e)
{
string message = "";
foreach (ListItem item in lstFruits.Items)
{
if (item.Selected)
{
message += item.Text + " " + item.Value + "\\n";
}
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}
It should display the information selected as:
100 Units - Mango
50 Units - Orange
100 Units Apple
In the code behind, it should save every one of them as new rows.
Can somebody help me out with this?
Thanks in advance.
I found by myself, the way is very simple.
There is an asp.net control named "ListBox" which will be populated once the onselectedindexchanged method is running, but this needs to be encapsulated under an UpdatePanel control. Here is a good reference about the UpdatePanel UpdatePanel Control in ASP.Net.
Then just create a simple string variable which captures the value from the 1st dropdown and the 2nd dropdown button, then create a new ListItem ListItems and ListBox and finally itinerates the listBox items.
Does anyone know how can I make sure that they are at least one radio been click when submit in C# .net?
I have the following code:
<asp:RadioButtonList ID="billingType" runat="server" CssClass="cl_billing_method"
RepeatDirection="Horizontal" data-messages="{required:'Billing methods is required'}">
<asp:ListItem Text="Email" Value="1"></asp:ListItem>
<asp:ListItem Text="Digital Mailbox" Value="2"></asp:ListItem>
<asp:ListItem Text="Paper" Value="0"></asp:ListItem>
</asp:RadioButtonList>
How can I validate it so that when submit button is been clicked and it will do the client check and show error if there have no radio button been selected?
<script type="text/javascript" language="javascript">
function Validate_Checkbox()
{
var chks=document.getElementsByTagName('input');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please select at least one checkbox..!");
return false;
}
return true;
}
</script>
and on Submit Button you have to write
write
OnClientClick="return Validate_Checkbox()"
Better option is use a asp:RequiredFieldValidator it will looks like this:
<asp:RequiredFieldValidator ErrorMessage="Billing methods is required"
ControlToValidate="billingType" runat="server" ValidationGroup="validateBill" />
Add ValidationGroup to the button:
<asp:Button Text="Submit" ID="btnSubmit" runat="server" ValidationGroup="validateBill"/>
If you are getting some error saying "UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery' ..." then add the following lines to the config:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
I have a bit of jQuery code that applies a phone number mask to a text field in a form:
<script type="text/javascript" src="../../../js/jquery.maskedinput.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.mask.definitions['~'] = '[+-]';
$('.phone').mask('(999) 999-9999');
});
</script>
It works just fine when the user first enters the form or if the use refreshes the page. However, there is a DropDownList that will allow users to select a different shipping address. This DropDownList has its AutoPostBack Property set to "true."
<tr id="trAddressBook" runat="server">
<th>Ship To:</th>
<td>
<asp:DropDownList ID="AddressBook" runat="server" Width="200px" DataTextField="Value" DataValueField="Key" AppendDataBoundItems="true" AutoPostBack="true">
<asp:ListItem Text="Billing Address" Value="0" />
<asp:ListItem Text="New Address" Value="-1" />
</asp:DropDownList>
</td>
</tr>
Whenever the user select an option from this DropDownList, the phone mask jQuery code no longer appears in the phone number textbox(es). I don't see any errors when I inspect the page in Google Chrome.
Is there someway to maintain the phone mask code regardless of whether the user uses the DropDownList or not?
Here is the Page_Load function from the code behind:
protected void Page_Load(object sender, EventArgs e)
{
// DETERMINE IF THE SHIPPING FORM MUST BE INITIALIZED
bool initShipAddress;
if (Page.IsPostBack)
{
// ON POSTBACK, WE ONLY INITIALIZE THE SHIPPING FORM IF THE ADDRESS SELECTION WAS CHANGED
initShipAddress = (Request.Form["__EVENTTARGET"] == AddressBook.UniqueID);
}
else
{
// ON FIRST VISIT, WE INITIALIZE SHIPPING FORM IF THE SHIPPING ADDRESS IS NOT THE BILLING
initShipAddress = (GetShippingAddressId() != _User.PrimaryAddress.Id);
}
if (initShipAddress) InitializeShippingAddress();
}
I may be wrong as it's been a long time since I worked with ASP.NET, but I believe you can simply change $(document).ready(function () { ... }); to $(window).load(function() { ... });
$(window).load(function () {
$.mask.definitions['~'] = '[+-]';
$('.phone').mask('(999) 999-9999');
});
Failing that, ASP.NET executes a function called pageLoad every time a page loads:
function pageLoad() {
$.mask.definitions['~'] = '[+-]';
$('.phone').mask('(999) 999-9999');
};
I have drop-down box where users can select Yes or No, if user selects Yes from the drop-down then i want to show a confirmation box that shows Yes or No option. If only user selects Yes in the confirmation box then i want to proceed calling my other function which makes an update to the backend database. If user selects No in the confirmation box then i don't want to proceed and cancel the operation. Here is my drop-down code:
OnSelectedIndexChanged="CheckDropDownSelection"
runat="server" AppendDataBoundItems="true" Height="16px">
<asp:ListItem Text="-- Please Selet --" Value="-- Please Selet --"></asp:ListItem>
<asp:ListItem Text="YES" Value="YES"></asp:ListItem>
<asp:ListItem Text="NO" Value="NO"></asp:ListItem>
</asp:DropDownList>
here is my code behind:
protected void CheckDropDownSelection(Object sender, EventArgs e)
{
if (ddl_CloseTask.SelectedValue == "YES")
{
CloseTask();
}
else
{
}
}
protected void CloseTask()
{
// here is where i close the task
}
Read my full post regarding same : Calling Server Side function from Client Side Script
This is how you can achieve with sever and client side code
attach event of client code mostly in page_load
yourDropDownList.Attributes["onChange"] = "jsFunction(this);";
Client script
function jsFunction(mlist){
var myselect = mlist;
if(myselect.options[myselect.selectedIndex].value == "YES")
{
if(confirm("Delete item!"))
{
$.ajax({
type:"POST",
url: window.location.pathname + "/CloseTask";,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
}
}
}
});
}
}
}
serverside code
[WebMethod]
protected void CloseTask()
{
//code to close task
}
The code has too many Yes/No. I hope it won't confuse to user -
If a user selects YES in DropDownList, a Confirmation Message will be prompted.
If the user selects YES in Confirmation Message, DropDownList will post back to server.
<asp:DropDownList ID="ddl_CloseTask" Width="157px"
AutoPostBack="true"
OnSelectedIndexChanged="CheckDropDownSelection"
runat="server"
AppendDataBoundItems="true" Height="16px">
<asp:ListItem Text="-- Please Selet --" Value="-- Please Selet --"></asp:ListItem>
<asp:ListItem Text="YES" Value="YES"></asp:ListItem>
<asp:ListItem Text="NO" Value="NO"></asp:ListItem>
</asp:DropDownList>
<script type="text/javascript">
var selectlistId = '<%= ddl_CloseTask.ClientID %>',
selectlist = document.getElementById(selectlistId);
selectlist.onchange = function() {
if (selectlist.options[selectlist.selectedIndex].value == "YES") {
if (confirm("Are you sure you want to do this?")) {
__doPostBack(selectlistId, '');
}
}
};
</script>
Credit to this answer.
Updated:
If the user selects NO from the Confirmation Box, set DropDownList value to the first value.
<script type="text/javascript">
var selectlistId = '<%= ddl_CloseTask.ClientID %>',
selectlist = document.getElementById(selectlistId);
selectlist.onchange = function() {
if (selectlist.options[selectlist.selectedIndex].value == "YES") {
if (confirm("Are you sure you want to do this?")) {
__doPostBack(selectlistId, '');
} else {
// User selected NO, so change DropDownList back to 0.
selectlist.selectedIndex = 0;
}
}
};
</script>
You would want to prompt the user on the "onchange" event of your DropDownList control. You can add the call to your javascript function in the aspx markup or in the code behind. (I used the code behind in this case).
So, your code behind would look something like this:
protected void Page_Load( object sender, EventArgs e )
{
ddl_CloseTask.Attributes.Add("onchange", "return validate(this);");
}
protected void CheckDropDownSelection(object sender, EventArgs e)
{
if (ddl_CloseTask.SelectedValue == "YES")
{
CloseTask();
}
else
{
// do stuff
}
}
private void CloseTask()
{
// do stuff
}
And your aspx markup would look something like this:
<asp:DropDownList ID="ddl_CloseTask" runat="server" AutoPostBack="True" OnSelectedIndexChanged="CheckDropDownSelection">
<asp:ListItem Text="-- Please Select --" Value="-- Please Select --" />
<asp:ListItem Text="YES" Value="YES" />
<asp:ListItem Text="NO" Value="NO" />
</asp:DropDownList>
<script type="text/javascript">
function validate(ddl) {
var selected = ddl.options[ddl.selectedIndex].value;
if (selected == 'YES' && !confirm('Close the task?')) {
return false;
}
__doPostBack(ddl.id, '');
}
</script>
I was able to implement the selectbox but onchange and OnSelectedIndexChanged are not firing. Any insights?
<div class="hasJS">
<asp:DropDownList class="custom" ID="myid" runat="server" OnSelectedIndexChanged="change" OnTextChanged="change" onChange="myChange();">
<asp:ListItem>Hello</asp:ListItem>
<asp:ListItem>Hello1</asp:ListItem>
<asp:ListItem>Hello3</asp:ListItem>
<asp:ListItem>Hello4</asp:ListItem>
<asp:ListItem>Hello5</asp:ListItem>
<asp:ListItem>Hello6</asp:ListItem>
<asp:ListItem>Hello7</asp:ListItem>
<asp:ListItem>Hello8</asp:ListItem>
</asp:DropDownList>
</div>
<script type="text/javascript">
$(function () {
$("select.custom").each(function () {
var sb = new SelectBox({
selectbox: $(this),
height: 150,
width: 200
});
});
});
function myChange() {
alert("Hai");
}
</script>
set autopostback=true for DropDownList ;
<asp:DropDownList class="custom" autopostback="true" ID="myid" runat="server" OnSelectedIndexChanged="change" OnTextChanged="change" onChange="myChange();">
i just copied your code and guess what it was working fine with AutoPostBack="True",first it shows alert message then twice event was getting fired for both event.i guess you must have implemented below snippet in your code behind file.
protected void change(object sender, EventArgs e)
{
}
for the case of onChange add return to the javascript call
<asp:DropDownList ID="cbProduct" runat="server"
CssClass="common_transaction_textbox_style" onchange="return LoadProductBatchByName();" Height="23px" Width="200px">
</asp:DropDownList>
function LoadProductBatchByName() {
{
alert('test');
}