Load second dropdown based on first - JQuery Dialog - c#

I need to update my second drop down list from database according to the value selected from first drop down list in the Jquery dialog.
ASPX
<asp:UpdatePanel ID="upnl" OnLoad="upnl_Load" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="dv" style="display: none;" title="Tile">
<table>
<tr>
<td>Parent</td>
<td>
<asp:DropDownList ID="ddlDialog1" runat="server" /></td>
</tr>
<tr>
<td>Child</td>
<td>
<asp:DropDownList ID="ddlDialog2" runat="server" /></td>
</tr>
</table>
</div >
</ContentTemplate>
</asp:UpdatePanel>
JQuery
function EditBookingDialog() {
jQuery(document).ready(function () {
$("#dvEditBooking").dialog({
draggable: true,
modal: true,
width: 500,
height: 400
,
open: function (type, data) {
$("#<%= ddlDialog1.ClientID %>").change(function () {
__doPostBack('<%= upnl.ClientID %>', "DialogOnChange");
});
}
});
});
}
Code behind
protected void upnl_Load(object sender, EventArgs e)
{
if (arg.ToString().IndexOf("DialogOnChange") > -1)
{
// Here ddlDialog1.SelectedValue is always " ", Even I get a data set of values,ddlDialog2 is not populated with new values
ddlDialog2.DataSource = objMngr.GetData(ddlDialog1.SelectedValue);
ddlDialog2.DataValueField = "Id";
ddlDialog2.DataTextField = "name";
ddlDialog2.DataBind();
}
upnl.Update();
}
Problem here is,
How to Populate second drop down list(ddlDialog2) upon value change in the first drop down list.
Any idea?

You need to add the Server side change event of the 1st dropdown.
Modify the html of 1st drop down as follows.
<asp:DropDownList ID="ddlDialog1" runat="server" OnSelectedIndexChanged="upnl_Load()" />
remove jquery change and manually calling _do postback
$("#<%= ddlDialog1.ClientID %>").change(function () {
$.ajax(function{
url: "/YourPage.aspx"
type:"POST"
data:{"FirstDropDownValue" : $(this).val() }
success:function(msg){
//bind your second dropdown here.
if(msg.d != null)
{
// Looping over list
$.each(msg.d, function (index, value) {
$("#ddlDialog1").append($("<option> </option>").val(value["Id"]).html(value["name"]));
});
}
});
Update the server side method as follows
[WebMethod]
public static List<Myclass> void upnl_Load( string FirstDropDownValue)
{
if (FirstDropDownValue != "-1")
{
return objMngr.GetData(FirstDropDownValue);
}
upnl.Update();
}

Related

When I append to an HTML table using jquery I can't trigger the table row click event

I'm using asp.net mvc. I'm trying to append to an HTML table using jquery. I get the rows from a getJSON call and append them to the table. The rows are appended but for some reason the added rows don't trigger the click event. I think maybe it has to due with the timing or something but I'm not sure.
controller
using System;
using System.Web;
using System.Web.Mvc;
namespace Test
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test(string x)
{
string strJson = "[{\"name\":\"tom\",\"number\":\"111\"},{\"name\":\"bill\",\"number\":\"222\"}]";
return Json(strJson, JsonRequestBehavior.AllowGet);
}
}
}
view
#{
Layout = null;
}
<style>
td {
border: 2px solid black;
}
</style>
<br />
<br />
<table id="table1">
<tr>
<td>
name
</td>
<td>
number
</td>
</tr>
</table>
<br />
<br />
<button id="button1" type="button">append rows</button>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script>
//table click event
$(document).ready(function () {
$("#table1 tr").click(function () {
alert("table row clicked");
});
});
//button click event
$(document).ready(function () {
$("#button1").click(function () {
$.getJSON('#Url.Action("Test")', { x: "1" }, function (y) {
y = $.parseJSON(y);
$.each(y, function (i, item) {
$('#table1').append('<tr><td>' + item.name + '</td><td>' + item.number + '</td></tr>');
});
});
});
});
</script>
The event isn't triggered because the row is added after the event handler is attached. Use:
$(document).on("click", "#table1 tr", function (){}

Load Additional Data While scrolling down a page using jQuery Ajax and ASP.NET

I am trying to apply the captioned feature in my project and decided to try it out to see how it works. But while testing it, it shows an Client script error with a message Undefined when I scroll to the bottom of the page. I do not know what I did wrong in my code and I don't know how to get it to work. I am hoping someone helps me out of this. Below is the code:
Repeater
<div id="dvCampaigns">
<asp:Repeater ID="rptUsers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="campaignname">
<%# Eval("CampaignName") %></span></u></b>
</td>
</tr>
<tr>
<td>
<b>Description: </b><span class="description">
<%# Eval("Description") %></span><br />
<b>ID: </b><span class="campaign-id">
<%# Eval("CampaignID") %></span><br />
<b>Date Created: </b><span class="datecreated">
<%# Eval("CreatedOn")%></span><br />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<img id="loader" alt="" src="../Images/loading.gif" style="display: none" />
</div>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
rptCampaigns.DataSource = GetUserData(1);
rptCampaigns.DataBind();
}
}
public static TList<POLLice.Entities.Campaigns> GetCampaignData(int pageIndex)
{
int totalData;
var items = new CampaignsService().GetAll(pageIndex, 10, out totalData);
return items;
}
[WebMethod]
public static string GetCampaigns(int pageIndex)
{
var dataset = GetUserData(pageIndex).ToDataSet(true);
return dataset.GetXml();
}
jQuery Script
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "UserProfile/Default.aspx/GetCampaigns",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var campaigns = xml.find("Campaigns");
campaigns.each(function() {
var campaign = $(this);
var table = $("#dvCampaigns table").eq(0).clone(true);
$(".campaignname", table).html(campaign.find("CampaignName").text());
$(".description", table).html(campaign.find("Description").text());
$(".campaign-id", table).html(campaign.find("CampaignID").text());
$(".datecreated", table).html(campaign.find("CreatedOn").text());
$("#dvCampaigns").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
Many Thanks.
In your ajax you have this line:
url: "UserProfile/Default.aspx/GetCampaigns",
Did you remove the full path including http for this post or is that the way it is in your code? That needs a relative or absolute path to the web method. Also when calling web methods with ajax you need to use:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] //or whatever your return format is
[WebMethod]

"CheckAll" checkbox works only with the first page of asp:Repeater. How to fix?

I have a Repeater with CheckBoxes:
<asp:Repeater ID="rpt_users" runat="server" OnItemCommand="rpt_users_ItemCommand" OnItemDataBound="rpt_users_ItemDataBound">
<HeaderTemplate>
<table id="usersTable">
<tr>
<th rowspan="2">All<br /><asp:CheckBox runat="server" ID="checkAll" OnCheckedChanged="checkAll_CheckedChanged"/></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="c0">
<td><asp:CheckBox ID="CheckSelect" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:Repeater>
Here's a script that I placed right after Repeater control:
<script type="text/javascript">
var repeater1Control = document.getElementById('<%= rpt_users.ClientID %>');
$('input:checkbox[id$=checkAll]', repeater1Control).click(function (e) {
if (this.checked) {
$('input:checkbox[id$=CheckSelect]', repeater1Control).attr('checked', true);
}
else {
$('input:checkbox[id$=CheckSelect]', repeater1Control).removeAttr('checked');
}
});
$('input:checkbox[id$=CheckSelect]', repeater1Control).click(function (e) {
//To uncheck the header checkbox when there are no selected checkboxes in itemtemplate
if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == 0) {
$('input:checkbox[id$=checkAll]', repeater1Control).removeAttr('checked');
}
//To check the header checkbox when there are all selected checkboxes in itemtemplate
else if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == $('input:checkbox[id$=CheckSelect]', repeater1Control).length) {
$('input:checkbox[id$=checkAll]', repeater1Control).attr('checked', true);
}
});
Unfortunately, It works only at the first page of repeater. If I go to the second page or further, then nothing happens when I press "CheckAll" checkbox in header. How to fix this issue?
try this
(function($){
var bindEvents = function(){
// bind events here;
var repeater1Control = document.getElementById('<%= rpt_users.ClientID %>');
$('input:checkbox[id$=checkAll]', repeater1Control).click(function (e) {
if (this.checked) {
$('input:checkbox[id$=CheckSelect]', repeater1Control).attr('checked', true);
}
else {
$('input:checkbox[id$=CheckSelect]', repeater1Control).removeAttr('checked');
}
});
$('input:checkbox[id$=CheckSelect]', repeater1Control).click(function (e) {
//To uncheck the header checkbox when there are no selected checkboxes in itemtemplate
if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == 0) {
$('input:checkbox[id$=checkAll]', repeater1Control).removeAttr('checked');
}
//To check the header checkbox when there are all selected checkboxes in itemtemplate
else if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == $('input:checkbox[id$=CheckSelect]', repeater1Control).length) {
$('input:checkbox[id$=checkAll]', repeater1Control).attr('checked', true);
}
});
};
// initial load
$(document).ready( bindEvents);
// every async load by update panel
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(bindEvents);
})(jQuery);

How to Enable/Disable button on TinyMCE textbox onkeyup or onkeydown

on a ascx page I have a tinymce editor and a button
<asp:TextBox ID="txtName" runat="server" Width="100%" ></asp:TextBox>
<test:tinymceextender runat="server" ID="TinyMceExtender" TargetControlID="txtName" Theme="Full"> </test:tinymceextender>
<asp:Button ID="btnSave" Text="Save" Enabled="false" runat="server" />
I want to check if, textbox is null, then btnsave should be disable, if textbox is not null its should be enable, for the first time its working(because i am checking it on Page_Load), as I am entering some text and deleting that text using backspace btn is in enable mode only. I tried it to do with onKeyUp, onKeyPress but its working working for TinyMCE
these 2 js I used but its not working
$(document).ready(function () {
document.getElementById('<%=btnSave.ClientID %>').disabled = true;
var my_editor = tinymce.get('<%=txtName.ClientID %>');
if ($(my_editor.getBody()).text() == '') {
$("#<%=btnSave.ClientID %>").attr('disabled', 'disabled');
}
else if ($(my_editor.getBody()).text() != '') {
$("#<%=btnSave.ClientID %>").removeAttr('disabled');
}
});
window.onload = function () {
document.getElementById('<%=btnSave.ClientID %>').disabled = true;
}
function ENABLE_BTN() {
var EN = tinymce.get('<%=txtName.ClientID %>');
if (EN == '') {
document.getElementById('<%=btnSave.ClientID %>').disabled = true;
} else {
document.getElementById('<%=btnSave.ClientID %>').disabled = false;
}
}
calling onkeydown="ENABLE_BTN() on txtName
on F12: my textbox code is looking something like this...
<fieldset>
<input id="BasePage_txtName" type="text" style="width: 100%; display: none;" name="BasePage$txtName" aria-hidden="true">
<span id="BasePage_txtName_parent" class="mceEditor defaultSkin" role="application" aria-labelledby="BasePage_txtName_voice">
<span id="BasePage_txtName_voice" class="mceVoiceLabel" style="display:none;">Rich Text Area</span>
<table id="BasePage_txtName_tbl" class="mceLayout" cellspacing="0" cellpadding="0" role="presentation" style="width: 100%; height: 100px;">
<tbody>
<tr class="mceFirst" role="presentation">
<tr class="mceLast">
</tbody>
</table>
</span>
</fieldset>
I would use the keyup event to check if the contents are empty like this. Edit: updated to use TinyMCE's weird eventhandler methods.
$(function () {
tinyMCE.init({
// adapt accordingly
mode : "exact",
theme : "simple",
elements : "txtName",
setup : function(ed) {
ed.onInit.add(function(ed) {
bindKeyUp(ed);
});}
});
});
function bindKeyUp(ed) {
if (tinyMCE.activeEditor) {
ed.onKeyUp.add(function() {
$('#btnSave').attr('disabled', !(textBoxEmpty()));
});
}
}
function textBoxEmpty() {
var contentLength = tinyMCE.get('#txtName').getContent();
if (contentLength.length) {
return true;
}
return false;
}
$(function () {
tinyMCE.init({
// adapt accordingly
mode : "exact",
theme : "simple",
elements : "txtName",
setup : function(ed) {
ed.onInit.add(function(ed) {
bindKeyUp(ed);
});}
});
});
function bindKeyUp(ed) {
if (tinyMCE.activeEditor) {
ed.onKeyUp.add(function () {
var contentLength = removeHTMLTags(tinyMCE.get('<%=txtName.ClientID %>').getContent());
if (contentLength.trim().length) {
document.getElementById('<%=btnSave.ClientID %>').disabled = false;
}
else {
document.getElementById('<%=btnSave.ClientID %>').disabled = true;
}
});
}
}

How to fetch the value of selected checkbox inside a checkboxList?

I want to know the selected value of the markup below. So that I can disabled a textbox, if one of the checkbox is selected.
<asp:CheckBoxList ID="ChkTest" runat="server" RepeatDirection="Horizontal" CssClass="toggleYesNo">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0">No</asp:ListItem>
</asp:CheckBoxList>
I tried using this function it doesnot seem to work
$(document).ready(function() {
$("#<%=ChkTest.ClientID %>").click(function() {
value = $(this).val();
if(value=='1') {
$('#atextbox').attr('disabled','');
}
else {
$('#atextbox').attr('disabled','disabled');
}
});
});
I also track the output HTML but the id the CheckBoxList the assigned to a table instead.
UPDATED
<table id="ChkTest" class="toggleYesNo" border="0">
<tr>
<td><input id="ChkTest_0" type="checkbox" name="ChkTest$0" /><label for="ChkTest_0">Yes</label></td><td><input id="ChkTest_1" type="checkbox" name="ChkTest$1" /><label for="ChkTest_1">No</label></td>
</tr>
</table>
Ok, I solved it
my jQuery function is
$(document).ready(function() {
$("#<%=ChkTest.ClientID %> input").click(function() {
value = $(this).attr('checked');
if(value==true) {
$("#TxtName").removeAttr("disabled");
}
else {
$("#TxtName").val('');
$("#TxtName").attr("disabled","disabled");
}
});
});
This totally solved it
It could be the selector; can you try changing
$("#<%=ChkTest.ClientID %>").click(function() {
To:
$('.ToggleYesNo').click(function() {
If that doesn't help, can you comment with the output you get from:
alert($("#<%=ChkTest.ClientID %>"));
alert($('.ToggleYesNo'));
try
$(document).ready(function() {
$("#ChkTest").click(function() {
value = $(this).find(':checked').val();
if(value=='1') {
$('#atextbox').attr('disabled','');
}
else {
$('#atextbox').attr('disabled','disabled');
}
});
});
EDIT based on UPDATED by the OP
$(document).ready(function() {
$("#ChkTest :checkbox").click(function() {
value = $(this).next().text().toLowerCase();
if(value=='yes') {
$('#atextbox').attr('disabled','');
}
else {
$('#atextbox').attr('disabled','disabled');
}
});
});

Categories

Resources