I'm using 'label1' like a global variable to pass info from 1 script (type="text/javascript") to another script (runat="server"), however the setAttribute("src",...) with a variable doesn't seem to work. Note that it does work if hardcoded. Here is a portion of my ASP.Net code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript" >
var soundObject = null;
function PlaySound() {
if (soundObject != null) {
document.body.removeChild(soundObject);
soundObject.removed = true;
soundObject = null;
}
soundObject = document.createElement("embed");
soundObject.setAttribute("src", label1.Text);
soundObject.setAttribute("hidden", true);
soundObject.setAttribute("autostart", true);
document.body.appendChild(soundObject);
}
window.onload = PlaySound;
</script>
<script runat="server" >
void Selection_Change(Object sender, EventArgs e)
{
label1.Text = SongList.SelectedItem.Value.ToString();
Response.Write(SongList.SelectedItem.Value);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DropDownList id="SongList" AutoPostBack="True" OnSelectedIndexChanged="Selection_Change"
runat="server">
<asp:ListItem Selected="True" Value="Love Is All Around.mp3">
Love Is All Around.mp3</asp:ListItem>
<asp:ListItem Value="Om.mp3">Om.mp3</asp:ListItem>
<asp:ListItem Value="Nights In White Satin.mp3">
Nights In White Satin.mp3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="label1" Text="Om.mp3" runat="server" />
<input type="button" onclick="PlaySound()" value="Play Sound" />
Your issue is, that your javascript does not find the label1 variable.
You can not just reference asp.net server controls in javascript - javascript doesn't know about them.
Find your label1 via javascript with getElementById and then read the content of the element (in javascript this will be a span). The ID you use in getElementById has to be the ClientID of your label, so if you want to use label1 for an id, you need to set the ClientIDMode property to static.
Related
I have the following code, in which I am trying to transfer some text in a previous page's textbox control (located in the master page) to the same master page textbox control. However it is not working. Please let me know if you can spot the error.
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox placeholder =
(TextBox)PreviousPage.Master.FindControl("TextBox1");
if (placeholder != null)
{
TextBox searchBox = (TextBox)Master.FindControl("TextBox1");
string search = placeholder.Text.ToString();
searchBox.Text = search;
}
}
}
this is the .aspx of the master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="AlexBookShop.Site1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.auto-style1 {
margin-bottom: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Children</asp:ListItem>
<asp:ListItem Value="1">Finance</asp:ListItem>
<asp:ListItem Value="3">Non-Fiction</asp:ListItem>
<asp:ListItem Value="4">Technical</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Log Out" OnClick="Button2_Click" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
For transferring data from one page to other page via MasterPAge you need to do cross page posting.
you need to assign the PostBackUrl property of a button control on the first page to point to the second one. like
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/Secondpage.aspx"/>
set the PreviousPage directive on the second page:
<%# PreviousPageType VirtualPath="~/firstpage.aspx" %>
Then whenever second page receives a postback, get the data you need from the first page:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox placeholder =
(TextBox)PreviousPage.Master.FindControl("TextBox1");
if (placeholder != null)
{
TextBox searchBox = (TextBox)Master.FindControl("TextBox1");
string search = placeholder.Text.ToString();
searchBox.Text = search;
}
}
}
<td>Type:
</td>
<td>
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
For this dropdownlist, I put validation like this
var ddltype = document.getElementById('<%=ddltype.ClientID%>');
var type = ddltype.options[ddltype.selectedValue].value;
if (type == 0) {
alert("Please Select setter/getter type.");
return false;
}
but it is not firing. How can I write this?
You should really get familiar with ASP.NET validators. Javascript can be disabled.
<asp:DropDownList ID="ddltype" runat="server" AutoPostBack="true">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1"></asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList><br />
<asp:RequiredFieldValidator ID="reqType" runat="server"
InitialValue="---select---"
ControlToValidate="ddltype"
ErrorMessage="Required: Please select a Type"
Display="Dynamic"
CssClass="blah">
</asp:RequiredFieldValidator>
The InitialValue is important. Otherwise ---select--- would be a valid selection.
Note that i've also added AutoPostBack="true" to the DropDownList, maybe you want to postback immediately as soon as the user has selected an item.
Side-note: use a ValidationSummary with ShowMessageBox="true" and EnableClientScript="true" if you want to show the messages in a javascript alert.
Try this
var ddltype = document.getElementById('<%=ddltype.ClientID%>').text;
if (type == "---select---") {
alert("Please Select setter/getter type.");
return false;
}
Try this way ! but you can use asp.net validation control .
Any way ,my solution will validate two type ,for the dropdown selected vale or dropdown selected item
function Validate()
{
var e = document.getElementById('<%=ddltype.ClientID%>');
//if you need value to be compared then use
var strUser = e.options[e.selectedIndex].value;
//if you need text to be compared then use
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0) **//for text use if(strUser1=="---Select---")**
{
alert("Please Select setter/getter type.");
return false;
}
}
The below code has change your some code and working good for me
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validation() {
debugger;
var e = document.getElementById('<%=ddltype.ClientID%>');
var strUser1 = e.options[e.selectedIndex].value;
if (strUser1 == 0) {
alert("Please Select setter/getter type.");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="validation();" OnClick="btnSave_Click" />
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
and see this line
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
But you missed set value in that item , So it's get error, Now set value 0 in that line , and now your code working (See my sample code), Or you need to use .text and check the condition for
if(strUser1=="---Select---")
{
//alert
}
I have 3 drop down boxes, created using the HTML select tag. On page load, the first box has a few names. Now, when I click on one of the names in the first box, some more names should appear in the second and when I click on a name in the second box, some more names should appear in the third box. How can I achieve this using AJAX? I have to use ASP.Net and MS SQL Server only. I'm a complete noob to AJAX and I've been educating myself about it, but nothing's working out. I've been looking for the code for close to a week. I looked up w3schools.com, but when I tried that code, it didn't work. Please help me out and please tell me step by step, the things required in order to make it work, and what goes where. I have a deadline that is fast approaching and am at my wit's end trying to make it work. HELP ME!!
I would recommend placing the three dropdownlists in an UpdatePanel and adding a trigger to each for the updatepanel. Then, when the value changes, re-populate the dropdown and let the updatepanel push the update. Also keeps session-state in case you want to submit the values.
I don't have a compiler in front of me, but if need be just post a comment and I'll post the code tomorrow.
Working Example
I'm using the "Traditional template" that comes with visual studio and the master page, so excuse the content place holders. But this should demonstrate what I mean:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="MultiDropDown.aspx.cs" Inherits="AppSettingsRetrieval.MultiDropDown" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
String[] options = new[] { "ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZA" };
foreach (String option in options)
{
this.DropDownList1.Items.Add(new ListItem(option, option));
}
}
}
public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.DropDownList2.Items.Clear();
this.DropDownList2.Items.Add(new ListItem("--- Please Select One ---"));
String[] options = new[] { "123", "456", "789", "101", "112", "131", "415", "161", "718" };
foreach (String option in options)
{
var str = String.Format("{0} {1}", this.DropDownList1.SelectedValue, option);
this.DropDownList2.Items.Add(new ListItem(str, str));
}
this.DropDownList2.Enabled = true;
this.DropDownList3.Enabled = false;
}
public void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.DropDownList3.Items.Clear();
this.DropDownList3.Items.Add(new ListItem("--- Please Select One ---"));
String[] options = new[] { "test", "testing", "tester", "foo", "bar", "foobar" };
foreach (String option in options)
{
var str = String.Format("{0} {1}", this.DropDownList2.SelectedValue, option);
this.DropDownList3.Items.Add(new ListItem(str, str));
}
this.DropDownList3.Enabled = true;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<ContentTemplate>
<fieldset>
<legend>Consecutive Dropdown List</legend>
<p>
Primary Filter:
<asp:DropDownList runat="server" ID="DropDownList1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="---Please Select One---" />
</asp:DropDownList>
</p>
<p>
Secondary Filter:
<asp:DropDownList runat="server" ID="DropDownList2" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" Enabled="false">
<asp:ListItem Text="---Please Select One---" />
</asp:DropDownList>
</p>
<p>
Final Filter:
<asp:DropDownList runat="server" ID="DropDownList3" Enabled="false">
<asp:ListItem Text="---Please Select One---" />
</asp:DropDownList>
</p>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:RadioButtonList ID="RdoBtnHasNotified" runat="server" RepeatDirection="Horizontal" AutoPostBack="True" OnSelectedIndexChanged="RdoBtnHasNotified_SelectedIndexChanged">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0" Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="TxtHowNotified" runat="server" TextMode="MultiLine" MaxLength="100"></asp:TextBox>
I want to enable the TextBox by clicking on the RadioButtonList, without using autopostback=true. How can I do this with JavaScript?
You can use jQuery to manipulate input's enabled state (HTML translation for TextBox) or you can use ASP.NET Ajax so you can set both controls inside of update panel in this case you won't see page being reloaded on postback which must happen in order for you to change status of TextBox on some other event.
Tbh i would go with ASP.NET Ajax because my experience shows that jQuery does not work that well with ASP.NET controls when it comes to complex stuff ie. ASP.NET uses javascript for event activation which can cause either jQuery or ASP.NET not to work as you may expected.
Good luck with update panels...
Using jQuery, you can have a fairly custom result by hooking in to the changes on the radio buttons...
$("#<%= RdoBtnHasNotified.ClientID %> > input[type=radio]").change(function(){
// this function is called whenever one of the radio button list's control's change
// the $(this) variable refers to the input control that triggered the event
var txt = $("#<%= TxtHowNotified.ClientID %>");
if($(this).val()=="1") {
txt.removeAttr("disabled");
} else {
txt.attr("disabled", true);
}
});
Each ListItem renders a radio button with the same name parameter; I would suggest running the app and looking at the generated source to get an idea of what you need to do to listen for the radio button events. Essentially the ID of the radio button list is the name parameter, so you can get the group of radio buttons as (using JQuery):
$("input[name='<%= rbl.ClientID%>']").click(function() {
var tb = $("#textboxid");
//do something here; this points to the radio button
});
HTH.
Here you go:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void RdoBtnHasNotified_PreRender(object sender, EventArgs e)
{
foreach (ListItem item in RdoBtnHasNotified.Items)
item.Attributes.Add("onclick", string.Format("toggleTextBox(this,'{0}');", TxtHowNotified.ClientID));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function toggleTextBox(radioButton, textBoxId) {
document.getElementById(textBoxId).disabled = radioButton.value != "1";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="RdoBtnHasNotified" OnPreRender="RdoBtnHasNotified_PreRender"
runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0" Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="TxtHowNotified" runat="server" TextMode="MultiLine" MaxLength="100" Enabled="false"></asp:TextBox>
</div>
</form>
</body>
</html>
Write the code in the following way
<script type="text/javascript">
$(document).ready(function() {
$("input[name='RdoBtnHasNotified']").change(function() {
$("input[name='RdoBtnHasNotified']:checked").val() == '1' ? $('#TxtHowNotified').removeAttr("disabled") : $('#TxtHowNotified').attr('disabled', 'true');
});
});
</script>
and also disable the textbox (Enabled="false") since initialy the value of the "RdoBtnHasNotified" is "No".
$('#<%= RdoBtnHasNotified.ClientID %> > input[type=radio]').click(function()
{
var txtbox = $('#<%= TxtHowNotified.ClientID %>');
if($(this).val() == '1')
{
document.getElementById('#<%= TxtHowNotified.ClientID %>').disabled = false;
}
else
{
document.getElementById('#<%= TxtHowNotified.ClientID %>').disabled = true;
}
});
I think using change event will not fire in IE.
i've noticed that popup shows BEFORE text gets updated in the textbox, i guess js gets called before the page gets rendered ... that would explain the 'undefined' popup ... how do i make sure js gets called AFTER the page is rendered?
rewriting to make it as simple as possible:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtRcaNotes" runat="server" TextMode="MultiLine" Width="800px"></asp:TextBox><br />
<asp:Button ID="btnDoneWithRcs" runat="server" OnClick="btnDoneWithRcs_Click" Text="Action Completed / Update Notes" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(
function(){doStuff();}
);
function doStuff()
{
$(document).ready(function() {
$('txtRcaNotes').hide();
alert($('txtRcaNotes').attr('id'));
});
}
</script>
</body>
Code Behind:
protected void btnDoneWithRcs_Click(object sender, EventArgs e)
{
txtRcaNotes.Text += "asdfadf";
}
TEXTBOX DOESN'T GET HIDDEN, ALERT() RETURNS 'UNDEFINED'
You're just missing your id selector syntax. Try:
$('#<%= txtRcaNotes.ClientID %>').hide();
alert($('#<%= txtRcaNotes.ClientID %>').attr('id'));
Note the addition "#" prepended before each selector.
One thing you could try is using Firebug, or some other DOM inspector and check the actual element IDs that are being generated by ASP.NET before and after your AJAX call and see if they are the same.