ASP.net getting RadioButtonList value on content page with javascript - c#

I'm having a problem with my JavaScript code having moved it over to a content page in ASP.
It worked perfectly on a stand alone page.
<script type="text/javascript">
function validateQ12(oSrc, args) {
var rbtnList = document.getElementsByName('rbtn12');
var noClicked = false;
for (var i = 0; i < rbtnList.length; i++) {
if (rbtnList[i].checked) {
noClicked = rbtnList[i].value == "No";
break;
}
}
if (noClicked) {
args.IsValid = true;
}
else
args.IsValid = args.Value.trim().length > 0;
}
</script>
I have gone through the html on both pages, on the one that worked had
<input id="rbtn12_1" type="radio" name="rbtn12" value="No" checked="checked" onclick="Q12iNo();">
The new one inside a content page has
<input id="MainContent_rbtn12_1" type="radio" name="ctl00$MainContent$rbtn12" value="No" checked="checked" onclick="Q12iNo();">
Clearly the name change must be causing the problem. How do I reference this new name in my javascript code?

To get the rendered element name use the following:
<%= rbtn12.UniqueID %>
However in your case this may still not work as it looks like you need to loop through each radio button item.
See the following post:
Find out if radio button is checked with JQuery?
Which shows how to determine if a radio button collection has a selected value.

Can you possibly add a className to your control and use getElementByClassName?
<input id="MainContent_rbtn12_1" type="radio" name="ctl00$MainContent$rbtn12" value="No" checked="checked" onclick="Q12iNo();" CssClass="Radio">
<script type="text/javascript">
function validateQ12(oSrc, args) {
var rbtnList = document.getElementsByClassName('Radio');
var noClicked = false;
for (var i = 0; i < rbtnList.length; i++) {
if (rbtnList[i].checked) {
noClicked = rbtnList[i].value == "No";
break;
}
}
if (noClicked) {
args.IsValid = true;
}
else
args.IsValid = args.Value.trim().length > 0;
}
</script>

Related

Populating Blueimp carousel inks in codebehind

I'm using ASP.NET C# to display a catalog of items. When the user selects an item, I display the details of that item and I'd like to display one or more pictures. I tried a few methods for this and settled on the Blueimp carousel. It's working just fine if I populate the links div in the html, but I need to show different pics (from URLs in the SQL Server DB) depending on the item.
The code below works to populate the links div, but all I see is a blank space on the screen--no carousel, no images.
<div id="IllustrationDiv" runat="server">
<!-- Links div goes here -->
<script>
document.getElementById('links').onclick = function (event) {
event = event || window.event
var target = event.target || event.srcElement
var link = target.src ? target.parentNode : target
var options = { index: link, event: event }
var links = this.getElementsByTagName('a')
blueimp.Gallery(links, options)
}
</script>
<!-- The Gallery as inline carousel, can be positioned anywhere on the page -->
<div id="blueimp-gallery-carousel"
class="blueimp-gallery blueimp-gallery-carousel"
aria-label="image carousel">
<div class="slides" aria-live="off"></div>
<h3 class="title"></h3>
<a class="prev"
aria-controls="blueimp-gallery-carousel"
aria-label="previous slide"></a>
<a class="next"
aria-controls="blueimp-gallery-carousel"
aria-label="next slide"></a>
<a class="play-pause"
aria-controls="blueimp-gallery-carousel"
aria-label="play slideshow"
aria-pressed="false"
role="button"></a>
<ol class="indicator"></ol>
</div>
<script src="../Scripts/blueimp-gallery.min.js"></script>
<script>
blueimp.Gallery(document.getElementById('links').getElementsByTagName('a'), {
container: '#blueimp-gallery-carousel',
carousel: true
})
</script>
</div>
ViewState["illustration_details_dt"] = dt;
// Open div
System.Web.UI.HtmlControls.HtmlGenericControl newDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
newDiv.ID = "links"; //<---Give and ID to the div, very important!
newDiv.Attributes.Add("hidden", "hidden");
for (int i = 0; i < dt.Rows.Count; i++)
{
Image newImage = new Image();
HyperLink newHyperLink = new HyperLink();
newHyperLink.NavigateUrl = dt.Rows[i]["universal_resource_locator"].ToString();
newHyperLink.Target = "_blank";
newHyperLink.Text = dt.Rows[i]["document_id"].ToString();
newImage.ImageUrl = dt.Rows[i]["universal_resource_locator"].ToString();
newImage.AlternateText = dt.Rows[i]["document_id"].ToString();
newImage.BackColor = System.Drawing.Color.White;
newHyperLink.Controls.Add(newImage); // TODO - Commented for troubleshooting
newDiv.Controls.Add(newHyperLink); // TODO - Commented for troubleshooting
}
IllustrationDiv.Controls.AddAt(0,newDiv); // Add the new div to our already existing div
I'm looking for options. If populating the links div from codebehind isn't going to work, what would work? If populating the links div from codebehind does work, what am I doing wrong?
Thanks.
I found the answer. I'm using a master page on my site with a content placeholder for the subpages. Because I'm using a ContentPlaceholderID = "MainContent", MainContent_ is appended to each of the IDs on my page, so my blueimp script looking for document.getElementById('links') needed to have "MainContent_" prepended to "links". I change the script to:
<script>
document.getElementById('MainContent_links').onclick = function (event) {
event = event || window.event
var target = event.target || event.srcElement
var link = target.src ? target.parentNode : target
var options = { index: link, event: event }
var links = this.getElementsByTagName('a')
blueimp.Gallery(links, options)
}
var carouselOptions = {
startSlideshow: true
}
</script>
The links were populating just fine, but blueimp couldn't find them. This fixed it.

Single selection checkbox

I want to only allow a single checkbox to be selected inside my foreach loop, right now I can select multiple.I have a click event but this will not uncheck the other checkboxes when I make a checkbox selection. What's wrong here? Thanks
<div class="consulting-editors" data-bind="foreach: ConsultingEditors">
<input type="checkbox" name="Promote" data-bind="checked: Promote, click: $parent.promoterSelectedOnclick" /> Display as main editor
</div>
ConsultingEditors: KnockoutObservableArray<NavigatorAuthorApi> = ko.observableArray();
promoterSelectedOnclick = (selectedEditor: NavigatorAuthorApi) => {
if (this.ConsultingEditors().some(e => e.Promote)) {
this.ConsultingEditors().filter(e => e.AuthorRef != selectedEditor.AuthorRef).forEach((e) => {
e.Promote = false;
});
}
return this.ConsultingEditors();
}
export type NavigatorAuthorApi =
{
SortOrder: number,
FirmRef: number,
FirmName: string,
AuthorRef: number,
AuthorName: string,
DisplayString: string,
EditorImage: ByteString[],
Promote: boolean
}
Promote should be an observable if you want property change to reflect on the DOM.
class viewModel {
ConsultingEditors = ko.observableArray([
{ Promote: ko.observable(false), AuthorRef: 1},
{ Promote: ko.observable(false), AuthorRef: 2 },
{ Promote: ko.observable(false), AuthorRef: 3 }
]);
promoterSelectedOnclick = (selectedEditor) => {
this.ConsultingEditors().filter(e => e.AuthorRef != selectedEditor.AuthorRef).forEach((e) => {
e.Promote(false);
});
return true;
}
}
ko.applyBindings(new viewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="consulting-editors" data-bind="foreach: ConsultingEditors">
<input type="checkbox" name="Promote" data-bind="checked: Promote, click: $parent.promoterSelectedOnclick" /> Display
</div>
Two things,
You need your click function to return true otherwise the click binding will conflict with the checked binding.
Promote is being used as a boolean, but it needs to be an Observable for the UI to react to any changes to its value. Everything that the UI needs to react to has to be a knockout observable.
function viewModel(){
var self=this;
self.ConsultingEditors = ko.observableArray([
new NavigatorAuthorApi(false, 1),
new NavigatorAuthorApi(false, 2),
new NavigatorAuthorApi(false, 3)
]);
self.promoterSelectedOnclick = function(selectedEditor){
if (self.ConsultingEditors().some(e => e.Promote())) {
var others = self.ConsultingEditors().filter(e => e.AuthorRef != selectedEditor.AuthorRef);
others.forEach((e) => {
e.Promote(false);
});
}
return true;
}
}
function NavigatorAuthorApi(promote, authorRef)
{
var self = this;
self.SortOrder = null;
self.FirmRef = null;
self.FirmName = null;
self.AuthorRef = authorRef;
self.AuthorName = null;
self.DisplayString = null;
self.EditorImage = null;
self.Promote = ko.observable(promote);
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="consulting-editors" data-bind="foreach: ConsultingEditors">
<input type="checkbox" name="Promote" data-bind="checked: Promote, click: $parent.promoterSelectedOnclick" /> Display as main editor
</div>

javascript enable textbox on dropdown change event

i have five dropdown and five texbox and I'm checking on click of any of the dropdown the corresponding texbox should get enabled/disabled through javascript am using master page in asp.net
e.g: if am selecting dropdownlist1 then texbox1 should get enabled,for one textbox its working how to make it work for five textbox
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.id);
if (ControlName.value == 0)
{
document.getElementById('<%=txtComment1.ClientID%>').disabled = true;
}
else {
document.getElementById('<%=txtComment1.ClientID%>').disabled = false;
}
}
You can use JQuery, it is better way. Set two class to each textBox, first .textBox1 .myTexts,
the first class must include an id for text boxes. Such as .textBox1, .textBox2 ect. And your dropbox value must include just text box's id.
$(document).ready(function(){
$("#dropBoxID").change(function(){
$(".myTexts").attr('disabled','disabled');
$(".textBox"+$(this).val()).removeAttr("disabled")
});
});
try this
http://jsfiddle.net/3WJtM/
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.getAttribute("id"));
var idTxt = ControlName.getAttribute("txt");
if (ControlName.value == 0)
{
document.getElementById(idTxt).disabled = true;
}
else {
document.getElementById(idTxt).disabled = false;
}
}
on every object select, add an attribute txt with the name of te input text
In the javascript you search this textbox for enabled or disabled
for example
<select id="ddl1" txt="txt1" onchange="HideTextBox(this);" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="input" id="txt1" disabled/>

checkbox status lost after update panel works

I have an update panel, which fires every third seconds. I have this code into my asp.net page
<div ID="campaignDiv" runat="server" >
<ul>
</ul>
</div>
and I add its content dynamically like this:
private string CreateLiCheckbox(string checkBoxText)
{
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
}
if (!IsPostBack) {
List<string> comps = getCompainNames();
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++) {
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
My problem
when the page loads, the checkboxes are like this:
Then, I change the values to these:
but when the update pannel works, the page returns to its default statues, where nothing of the checkboxes are selected
could you help please?

How can I include hidden DIVs using CSS without them take up space?

I have a simple MVC 5 page with a single dropdown list. Based upon the selection made from this dropdown list I enable visibility for one of three divs on the page. The problem I am running into is each div takes space on the page, even if it is not visible. So when I select something from dropdown list that causes the second div to be visible I will see that content shifted down on the page.
Here is the code from the Controller to create the data for the dropdown list.
public ActionResult Index()
{
var searchBy = new List<SearchBy>
{
new SearchBy { Name = "Email Address", Value = "EmailAddress" },
new SearchBy { Name = "Last name, First name", Value = "Name" },
new SearchBy { Name = "Username", Value = "Username" }
};
ViewBag.SearchByOptions = new SelectList(searchBy, "Value", "Name");
return View();
}
Here is my markup for the Index.cshtml
#{
<script type="text/javascript">
$(document).ready(function() {
// Make all three <div>s hidden when the page loads...
document.getElementById("searchByEmail").style.visibility = "hidden";
document.getElementById("searchByName").style.visibility = "hidden";
document.getElementById("searchByUsername").style.visibility = "hidden";
});
function searchBy(selectedItem) {
if (selectedItem == "EmailAddress") {
// Make visible
document.getElementById("searchByEmail").style.visibility = "visible";
// Make in-visible
document.getElementById("searchByName").style.visibility = "hidden";
document.getElementById("searchByUsername").style.visibility = "hidden";
}
if (selectedItem == "Name") {
// Make visible
document.getElementById("searchByName").style.visibility = "visible";
// Make in-visible
document.getElementById("searchByEmail").style.visibility = "hidden";
document.getElementById("searchByUsername").style.visibility = "hidden";
}
if (selectedItem == "Username") {
// Make visible
document.getElementById("searchByUsername").style.visibility = "visible";
// Make in-visible
document.getElementById("searchByEmail").style.visibility = "hidden";
document.getElementById("searchByName").style.visibility = "hidden";
}
};
</script>
}
<h2>Index</h2>
<div>
Search for existing users by: #Html.DropDownList("SelectedItem", (SelectList)ViewBag.SearchByOptions, "-- Select One --", new { onchange = "searchBy($('#SelectedItem').val());" })
</div>
<div id="searchByEmail">
Emails...
</div>
<div id="searchByName">
Names...
</div>
<div id="searchByUsername">
Usernames...
</div>
}
I am not sure what trick is needed to get all of the divs to take the same "real estate" on the page as I will only be showing one of them at a time.
Assuming that you use jQuery, try:
#{
<script type="text/javascript">
$(document).ready(function() {
$("#searchByEmail").hide();
$("#searchByName").hide();
$("#searchByUsername").hide();
});
function searchBy(selectedItem) {
if (selectedItem == "EmailAddress") {
$("#searchByEmail").show();
$("#searchByName").hide();
$("#searchByUsername").hide();
}
if (selectedItem == "Name") {
$("#searchByName").show();
$("#searchByEmail").hide();
$("#searchByUsername").hide();
}
if (selectedItem == "Username") {
$("#searchByUsername").show();
$("#searchByEmail").hide();
$("#searchByName").hide();
}
};
</script>
}
<h2>Index</h2>
<div>
Search for existing users by: #Html.DropDownList("SelectedItem", (SelectList)ViewBag.SearchByOptions, "-- Select One --", new { onchange = "searchBy($('#SelectedItem').val());" })
</div>
Also, check what is the difference between CSS rules:
visibility:hidden
and
display:none
The first just hide the element, but preserve the placeholder the same size as it is visible.
The second removes it from the size and dimension calculations.
.style.display = "block"; /* or none to hide it */

Categories

Resources