<asp:RadioButtonList ID="rbl" runat="server" onMouseUp="Myf()">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
function Myf() {
var list = document.getElementById("<%=rbl.ClientID %>");
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].innerHTML);
}
}
I'm getting the value of Radiobuttonlist. How to get the Text of the Radiobuttonlist?
First of all the radio buttons do not have text in your code
Second, if you look at the source of the resulting html page, you can see that the radio buttons have labels that store the text.
So you can look for label instead of input in your function and it will get the text
function Myf() {
var list = document.getElementById("<%=rbl.ClientID %>");
var inputs = list.getElementsByTagName("label");
var selected;
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].innerHTML);
}
}
Use the getAttribute() method.
element.getAttribute("Text");
More info on: https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute?redirectlocale=en-US&redirectslug=DOM%2Felement.getAttribute
To get text you have to put "label" instead of "input" in getelement.
try like this:
var inputs = list.getElementsByTagName("label");
<asp:RadioButtonList ID="rbl" runat="server">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
$(document).ready(function () {
$('[id*="rdl"],[type="radio"]').change(function () {
if ($(this).is(':checked'))
console.log($(this).next('label').html());
});
});
try this
function Myf() {
$("#<%=rbl.ClientID %>").find('input').each(function () {
var this_input = $(this);
alert($("#<%=rbl.ClientID %>").find('label[for="' + this_input.attr('id') + '"]').text());
})
}
Related
I have a RadioButtonList. I want the button to be available when I click "Agree", and not available when I click "Disagree". Default is disabled.
Now whether I agree or disagree, my btnSubmit button will become available. And it won't change back to unavailable.
function acceptprotocol() {
if (document.getElementById("rblAccept").SelectValue == 0 {
document.getElementById("btnSubmit").disabled = true;
}
else {
document.getElementById("btnSubmit").disabled = false;
}
}
RadioButtonList:
<asp:RadioButtonList ID="rblAccept" runat="server"
RepeatDirection="Horizontal" style="margin:auto"
onclick="acceptprotocol()">
<asp:ListItem Value="0">Agree</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Against</asp:ListItem>
</asp:RadioButtonList>
How to solve it? Please help me.
Here's the code snippet for your solution:
RadioButtonList:
<asp:RadioButtonList ID="rblAccept" runat="server" RepeatDirection="Horizontal" style="margin:auto"
onclick="acceptprotocol()">
<asp:ListItem Value="0">Agree</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Disagree</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Enabled="false" />
Function:
function acceptprotocol() {
var radioButtonAccept = document.getElementById('<%=rblAccept.ClientID %>').getElementsByTagName("input");;
for (var i = 0; i < radioButtonAccept.length; i++) {
if (radioButtonAccept[i].checked) {
if (radioButtonAccept[i].value == 1) {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = true;
}
else {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = false;
//use this bellow line if you want the after enable button button will availble all time
document.getElementById('<%=rblAccept.ClientID %>').removeAttribute("onclick");
}
break;
}
else {
document.getElementById('<%=btnSubmit.ClientID %>').disabled = true;
}
}
}
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>
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>
Using C# I need the value in the Hiddenfield below, which is currently "test" to be the 'Text' of the DropDownList. Any Ideas?
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
.cs page.
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
theForm.Controls.Add(hiddenField);
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
.aspx
<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
<asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
<asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
<asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
<asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
<asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
</asp:DropDownList>
After binding your drop down to a data source, set the selected value of the drop down to the index of the text in the hidden field.
dropCallbackReason.SelectedIndex = dropCallbackReason.Items.IndexOf(dropCallbackReason.Items.FindByText(ValueHiddenField.Value.ToString()));
I'd say your function updateCallBackReason is not doing what is supposed to do (update hidden field value). If didn't get wrong your question, this is what you have to do.
string script = string.Format(#"function updateCallBackReason() {{
var ddl = document.getElementById('dropCallbackReason');
var callBackReason = document.getElementById('{0}');
callBackReason.value = ddl.options[ddl.selectedIndex].innerHTML;
}}", hiddenField.ClientID );
I have a user control that contains 3 dropdown for(date,month, year).I have called this user control on aspx page.
Please select Date From.
On my aspx page all fields are validated with javascript validation.
when I select date from this user control (not month & year) ,and click on submit button, it shows the error message.
but my problem is that if i select year (not date,month) then in this case neither it fire the error message nor it saves the data.
I want that it fired the message everytime when atleast one field(day,month,year) is not selected.I want to handle this problem on clentside. Please give me your suggetion.
function InputValidation(vg) {
var isValid = true;
try {
var j = 0;
var inputCtrlArr = new Array();
var key = 'block';
var inputIntputArr = document.getElementsByTagName('input');
var inputDdlArr = document.getElementsByTagName('select');
var inputTextareaArr = document.getElementsByTagName('textarea');
var c = 0;
for (var i = 0; inputIntputArr.length > i; i++) inputCtrlArr[c++] = inputIntputArr[i];
for (var i = 0; inputDdlArr.length > i; i++) inputCtrlArr[c++] = inputDdlArr[i];
for (var i = 0; inputTextareaArr.length > i; i++) inputCtrlArr[c++] = inputTextareaArr[i];
for (var i = 0; inputCtrlArr.length > i; i++) {
if (inputCtrlArr[i].getAttribute('required') == 'true' && inputCtrlArr[i].getAttribute('vg') == vg) {
if (inputCtrlArr[i].value.trim() == '') {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
if (inputCtrlArr[i].type == "checkbox") {
if (inputCtrlArr[i].checked == false) {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
}
var errorDivId = inputCtrlArr[i].getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
}
}
catch (ex) { }
}
function InputCntrlValidate(obj) {
try {
if (obj.getAttribute('required') == 'true') {
if (obj.value == '') {
key = 'block';
}
else {
key = 'none';
}
var errorDivId = obj.getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
} catch (ex) { }
}
function sanitizeInput(obj) {
if (obj.getAttribute('msg') == obj.value) {
alert("same value");
}
}
The problem is in your JavaScript. Since if it is working for the one dropdownlist then it should work for other two. Further you will have to check for month and date. If it is feb then the days should be 28 or 29 and it will depend on the year. So lots of effort will require to solve it.
You only need three RequiredFieldValidators with each ControlToValidate leading to one of your DropDownLists. If you've a default value of f.e. "please select" you should set this as InitialValue of the Validators.
Here is a sample(i've only added few ListItems instead of all for dates,months and years):
<asp:DropDownlist ID="DdlDate" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
<asp:ListItem Text="3"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqDate"
ControlToValidate="DdlDate"
InitialValue="please select"
ErrorMessage="Please select Date"
Display="Dynamic"
runat="server">
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlMonth" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="January"></asp:ListItem>
<asp:ListItem Text="February"></asp:ListItem>
<asp:ListItem Text="March"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqMonth"
ControlToValidate="DdlMonth"
InitialValue="please select"
ErrorMessage="Please select Month"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlYear" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="2010"></asp:ListItem>
<asp:ListItem Text="2011"></asp:ListItem>
<asp:ListItem Text="2012"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqYear"
ControlToValidate="DdlYear"
InitialValue="please select"
ErrorMessage="Please select Year"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:Button ID="BtnSubmit" runat="server" Text="submit" />
I would use the calendar control on the AjaxControlToolKit if it were me. No validation required then other than if the field is mandatory. It's a lot easier and looks a lot better. All client side.
Just down load the ajxcontrolkit dll and include in your project and use as per any custom control/third party component.
EDIT:
Ok if you just want at least one drop down to be selected then try JQuery e.g.
function isDropDownsValid()
{
var isValid = true;
$('select').map(function()
{
if($(this).val() == -1)
{
isValid = false;
}
});
return isValid;
}
Then wire into your submit button like so
<asp:Button ID="myButton" runat="server" OnClientClick="return isDropDownsValid" Text="Submit />
Here is a fiddle with a demo. You may need to change the selector $('select') to target the exact dropdowns you need.