I have a radio button list connect to a local sqldb. The table has 2 cols - cata and catab, the radiobuttonlist is binded with cata and it works properly. I can enter records and view records. Next I applied bootstrap toggle button css , when I click buttons it works like toggle button, but I don't see any change when I change from record to record.
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatLayout="Flow"
RepeatDirection="Horizontal" CssClass="btn-group" data-toggle="buttons"
SelectedValue='<%# Bind("cata") %>'>
<asp:ListItem class="btn btn-primary" Value="1"></asp:ListItem>
<asp:ListItem class="btn btn-primary" Value="2"></asp:ListItem>
<asp:ListItem class="btn btn-primary" Value="3"></asp:ListItem>
<asp:ListItem class="btn btn-primary active" Value="4" Selected="True"></asp:ListItem>
</asp:RadioButtonList>
![screen shot][1]
Try below javascript to make toggling between your radio buttons.
<script>
$(document).ready(function () {
$('.btn-primary').click(function () {
$(this).addClass('active');
var allspan = $('#<%= RadioButtonList1.ClientID %>').find('span');
for (var i = 0; i < allspan.length; i++) {
if (allspan[i] == this) {
$(this).find('input[type="radio"]').prop('checked', true);
alert($(this).find('input[type="radio"]').val());
}
else {
$(allspan[i]).removeClass('active');
}
}
});
});
</script>
Select radio button value on Page_Load event:
Javascript Function:
function selectRadioValue(value)
{
var allspan = $('#<%= RadioButtonList1.ClientID %>').find('span');
for (var i = 0; i < allspan.length; i++) {
var objInnerRdo = $(allspan[i]).find('input[type="radio"]');
alert(objInnerRdo.val());
if (objInnerRdo.val() == value)
{
$(allspan[i]).addClass('active');
$(allspan[i]).find('input[type="radio"]').prop('checked', true);
}
else {
$(allspan[i]).removeClass('active');
}
}
}
Call this function using RegisterStartupScript where you passing database value. For Ex. I'm passing value "2" on page load.
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Show Windows" + new Random().Next().ToString(), "selectRadioValue('2');", true);
}
Related
I have a simple Dropdownlist control that JS handles,
once the index changes, a div is opened/closed.
html code for initializing the Dropdownlist-
<select id="selectmethod" onchange="run()">
<option value="1" selected="selected">option1</option>
<option value="2" >option2</option>
</select>
JavaScript code to handle OnChange event-
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
Now when the user clicks on an <ASP:LinkButton ... />
a Postback event starts and the Dropdownlist index resets (so as the hidden div).
How can I maintain the Dropdownlist index after the Postback ?
Thanks!
To maintain the contents of the dropdownlist you either have to re-populate it on the server every time or use viewstate. For example you can populate the data once like this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.Items.Add(new ListItem() { Text = "option1", Value = "1", Selected = true });
DropDownList1.Items.Add(new ListItem() { Text = "option2", Value = "2" });
}
}
and in the page you can use an ASP control and enable view state:
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="true">
</asp:DropDownList>
Now the data will be posted back and forth and will be maintained on the client side
To maintain the value, there are multiple approaches.
1. Change the select to server control.
2. Add a hidden value and save your select tag value to this hidden value in your run(). And then set the select value
in document.ready().
<asp:HiddenField ID="yourHiddenValue" runat="server" />
Your run method.
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
$('#<%=yourHiddenValue.ClientID%>').val(value); // <--- added
}
This is document ready function.
$(function() {
var hiddenValue = $('#<%=yourHiddenValue.ClientID%>').val();
$('#selectmethod').val(hiddenValue);
}
If you want to persist the control's state in ASP.Net Web Form, you want to use DropDownList Server Control which uses ViewState under the hood.
<asp:DropDownList runat="server" ID="DropDownList1">
<asp:ListItem Text="Add New Course" Value="1" />
<asp:ListItem Text="Change Course" Value="2" />
</asp:DropDownList>
<div id="changecourseitems">Change course</div>
<div id="addnewcourseitems">Add new course</div>
<asp:LinkButton ID="LinkButton1" runat="Server" OnClick="LinkButton1_Click"
Text="Submit" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var selectMethod = function(){
if ($('#<%= DropDownList1.ClientID %>').val() === '1') {
$('#changecourseitems').hide();
$('#addnewcourseitems').slideDown();
} else {
$('#addnewcourseitems').hide();
$('#changecourseitems').slideDown();
}
}
$('#<%= DropDownList1.ClientID %>').change(selectMethod);
selectMethod();
});
</script>
<asp:DropDownList ID="selectmethod" ClientIDMode="Static" runat="server" EnableViewState="true">
</asp:DropDownList>
With the ClientIDMode=static you maintain the id as it is specify on the control
your js file should be:
$('#selectmethod').change(function () {
var value = $(this).val();
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
});
I have rad Combo box
<telerik:RadComboBox runat="server" ID="rcb" Height="150px" OnItemsRequested="rcb_ItemsRequested" AutoCompleteSeparator="," >
</telerik:RadComboBox>
I need to get Selected value from client side
i tried this
function getvalue()
{
var combobox = $find("<%= rcb.ClientID %>");
var value = combobox.get_selectedItem().get_value();
}
but get_selected Item get only last selected item .
I need to get all selected Item.
try the get_text() method http://www.telerik.com/help/aspnet-ajax/combobox-client-side-radcombobox.html to get the entire input
here is a basic sample that seems to do the trick
<telerik:RadComboBox runat="server" ID="rcb" Height="150px" OnItemsRequested="rcb_ItemsRequested" AutoCompleteSeparator=",">
</telerik:RadComboBox>
<asp:Button ID="Button1" Text="text" OnClientClick="getSel(); return false;" runat="server" />
<script>
function getSel() {
alert($find("rcb").get_text());
}
</script>
and
protected void rcb_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
for (int i = 0; i < 5; i++)
{
rcb.Items.Add(new RadComboBoxItem(i.ToString()));
}
}
In my markup for the page I have the following div:
<div id="utteranceFilterSection" runat="server" enableviewstate="true">
<asp:Label ID="lblShowFilterPrompt" runat="server" Text="Show: "></asp:Label>
<asp:DropDownList ID="ddlDetailsFilter"
AutoPostBack="true"
runat="server"
OnSelectedIndexChanged="ddlDetailsFilter_SelectedIndexChanged">
<asp:ListItem Value="All">All</asp:ListItem>
<asp:ListItem Value="Pass">Passed</asp:ListItem>
<asp:ListItem Value="Fail">Failed</asp:ListItem>
<asp:ListItem Value="Blocked">Blocked</asp:ListItem>
</asp:DropDownList>
</div>
I'd like to show or hide this div based on the contents of my session state. In Page_Load I have:
if (Page.IsPostBack)
{
//if (this.Session["ShowFilterControl"] != null)
//{
// this.utteranceFilterSection.Visible = true;
// this.Session.Remove("ShowFilterControl");
//}
this.utteranceFilterSection.Visible = true;
}
else
{
this.utteranceFilterSection.Visible = false;
}
Setting visible works fine if I use the uncommented postback code, however, if I try to do it using the commented out code, I see the code step through in the debugger but the div does not become visible. What am I doing wrong?
why don't you try to set a bool and evaluate that in the if statement along with the postback condition? like this:
bool showFilter = (bool)this.Session["ShowFilterControl"];
if (Page.IsPostBack && showFilter)
{
this.Session["ShowFilterControl"] = false;
this.utteranceFilterSection.Visible = true;
}
else
{
this.utteranceFilterSection.Visible = false;
}
On my page I have a text box that uses a custom validator:
<asp:CustomValidator ID="cv_Question" ControlToValidate="tb_Question" runat="server" ErrorMessage="*" OnServerValidate="ValidateQuestion" ClientValidationFunction="CheckQuestion" ForeColor="#FF0000" ValidationGroup="CreateUser"></asp:CustomValidator>
The client side validation script that I would like to use always returns 0 for the drop down list SelectedValue, even when the drop down list index has already changed.
I set the drop down list default index to 0 with !Page.IsPostBack
Here is the drop down list:
<asp:DropDownList ID="ddl_Question" runat="server" EnableViewState="true" AutoPostBack="true" onselectedindexchanged="ddl_Question_SelectedIndexChanged">
<asp:ListItem Selected="False" Text="Select a question" Value="0"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was the first movie I ever saw?" Value="1"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is the middle name of my oldest child?" Value="2"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what city was my father born?" Value="3"></asp:ListItem>
<asp:ListItem Selected="False" Text="Who was my favourite cartoon character as a child?" Value="4"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is my mother's middle name?" Value="5"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what year did I meet my significant other?" Value="6"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was my first pet's name?" Value="7"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of the maid of honour at my wedding?" Value="8"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of my best friend in elementary school?" Value="9"></asp:ListItem>
<asp:ListItem Selected="False" Text="Name of my all-time favourite movie character?" Value="10"></asp:ListItem>
<asp:ListItem Selected="False" Text="Create a question" Value="11"></asp:ListItem>
</asp:DropDownList>
Here is the client side validation:
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
<% if(Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{ %>
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
<% }
else
{ %>
alert(<%= Convert.ToInt32(ddl_Question.SelectedValue)%>);
args.IsValid = true;
return;
<% } %>
}
</script>
I only want to validate the tb_Question if the user has selected "Create a question" from the ddl_Question.
EDIT:
Here is my SelectedIndexChanged method. The tb_Question is made visible when the user selects "Create a question". This happens before any validation occurs.
protected void ddl_Question_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{
Question.Visible = true;
}
else
{
Question.Visible = false;
}
}
Well my recommendation is to use simple JavaScript
So instead of doing that, use JavaScript and maybe jQuery like this
jQuery Nuget: https://nuget.org/packages/jQuery
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
var questionID = '<%= this.ddl_Question.ClientID %>';
var currentQuestion = $("#" + questionID).val();
if (currentQuestion == '11')
{
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
}
else
{
alert(currentQuestion);
args.IsValid = true;
return;
}
}
</script>
The issue is more likely in the Convert.ToInt32 call since this utility method returns zero when the value passed to it is null (you can check MSDN to validate this. http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) The SelectedValue property is very likely null at this point even though the selected index is zero. Try setting the SelectedValue programmatically and see I that makes any difference.
I can't find a way to select multiple items in an ASP.NET ListBox in the code behind? Is this something needs to be done in Javascript?
You will have to use FindByValue method of the ListBox
foreach (string selectedValue in SelectedValuesArray)
{
lstBranch.Items.FindByValue(selectedValue).Selected = true;
}
Here's a C# sample
(aspx)
<form id="form1" runat="server">
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem Value="Red" />
<asp:ListItem Value="Blue" />
<asp:ListItem Value="Green" />
</asp:ListBox>
<asp:Button ID="Button1"
runat="server"
onclick="Button1_Click"
Text="Select Blue and Green" />
</form>
(Code Behind)
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.SelectionMode = ListSelectionMode.Multiple;
foreach (ListItem item in ListBox1.Items)
{
if (item.Value == "Blue" || item.Value == "Green")
{
item.Selected = true;
}
}
}
this is the VB code to do so...
myListBox.SelectionMode = Multiple
For each i as listBoxItem in myListBox.Items
if i.Value = WantedValue Then
i.Selected = true
end if
Next
In C#:
foreach (ListItem item in ListBox1.Items)
{
item.Attributes.Add("selected", "selected");
}
I like where bill berlington is going with his solution. I don't want to iterate through the ListBox.Items for each item in my array. Here is my solution:
foreach (int index in indicesIntArray)
{
applicationListBox.Items[index].Selected = true;
}