Hossain Ehsani Hossain Ehsani - 3 years ago 152
Javascript Question

selectedLi not working while adding Li using JQuery

i have two dropDowns on a view.

SessionDateSelect
will get its contents from DB and
SessionSelect
will get is content from Db based on
SessionDateSelect
selectedLi. everything works fine so far. but when i click on contents of the
SessionSelect
dropDown nothing works:
here is my code :

div id="SessionDateSelect">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="btn-DateSelect" data-toggle="dropdown">انتخاب تاریخ شروع کلاس
<span class="caret"></span></button>
<ul class="dropdown-menu" id="dateList">
@{
var dateCollection = Session["classDates"] as List<string>;
if (dateCollection != null)
{
foreach (var item1 in dateCollection)
{
<li><a id="@item1" href="#">@item1</a></li>
}
}
}
</ul>
</div>
</div>


<div id="SessionSelect">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="btn-SessionSelect" data-toggle="dropdown">انتخاب جلسه
<span class="caret"></span></button>
<ul class="dropdown-menu" id="classSessions">

</ul>
</div>
</div>


and here is js codes :

<script type="text/javascript">
var selectedDate=null;
$("#SessionDateSelect").find("li a").click(function() {
$('.selectedLi').removeClass('selectedLi');
$(this).addClass('selectedLi');
selectedDate = $('.dropdown-menu').find("li a.selectedLi").attr('id');
var attgrade1 = $('.dropdown-menu').find("li a.selectedLi").text();
$('#btn-DateSelect').html("تاریخ شروع دوره" + " " + attgrade1 + '<span class="caret"></span>');
if (selectedDate != null) {
$.ajax({
url: '@Url.Action("GetSessions", "Main")',
type: 'POST',
traditional: true,
data: { 'date': selectedDate },
success: function (data) {
alert(data);
var mySelect = $('#classSessions');
for (var i = 1; i <= data; i++)
{
mySelect.append(' <li><a id="' + i + '"href="#">' + i + '</a></li>');

}

}
});
}
});

var selectedSession;
$("#SessionSelect").find("li a").click(function () {
alert('click');
$('.selectedLi').removeClass('selectedLi');
$(this).addClass('selectedLi');
selectedSession = $('.dropdown-menu').find("li a.selectedLi").attr('id');
var attgrade = $('.dropdown-menu').find("li a.selectedLi").text();
$('#btn-SessionSelect').html("جلسه شماره" + " " + attgrade + '<span class="caret"></span>');

});



</script>

Answer Source

thanks 'Stephen Muecke' changed the js code and everything works fine :

 var selectedSession;
            $("#classSessions").on('click', 'li', function() {
                var selected = $(this).text();
                $.ajax({
                    url: '@Url.Action("ActionName", "Controller")',
                    type: 'POST',
                    traditional: true,
                    data: {'sessionNumber': selected}
                    });

            });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download