How to make "this" refer to the element firing the event - javascript

I'd like to make "this" refer to the element which is actually firing the event:
<div class="input-group">
<span class="input-group-addon header-text" id="action-header-text">Action</span>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="action-dropdown" data-toggle="dropdown" aria-expanded="true" style="min-width:250px;">
<span class=" caret">
</span>
</button>
<ul id="action-menu" class="dropdown-menu" role="menu"></ul>
</div>
</div>
Filling Ajax Request:
function UpdateActionDropdown() {
$.ajax({
url: 'FrontEnd/Action',
type: 'POST',
dataType: 'json',
data: {
lid: document.getElementById('selected-language-id').value
},
success: function (data) {
document.getElementById('action-dropdown').firstChild.data = data.UnSelectable[0].ActionTrailer.DescriptionText;
$('#action-menu').html(null);
for (var i = 0; i < data.UnSelectable.length; i++) {
$('#action-menu').append("<li role='presentation' class='disabled'><a role='menuitem' tabindex='-1'>" + data.UnSelectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
$('#action-menu').append("<li role='presentation' class='divider'></li>");
for (var i = 0; i < data.Selectable.length; i++) {
$('#action-menu').append("<li role='presentation'>" +
"<a role='menuitem' tabindex='-1' text='" + data.Selectable[i].DescriptionText + "' value='" + data.Selectable[i].ActionTrailer.ID + "'\" href='#'>" + data.Selectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
}
});
}
global listener:
$('.dropdown').on('click', '#action-menu li', function(){
// Inside here I want to access the li-element which got clicked.
});
I assume that "this" inside the onclick Handler would refer to the document (or window) itself - is it possible to refer to the actual event firing element?
Thanks in advance!

Use $(this) which will be a DOM(in the context of jQuery) element when you are in a callback function
$('.dropdown').on('click', '#action-menu li', function(){
$(this)// It will be the li element clicked
});
See jQuery: What's the difference between '$(this)' and 'this'? and https://remysharp.com/2007/04/12/jquerys-this-demystified

Related

Convert html select dropdown to single button Nav bar

I have requirement for dynamic menu Navbar output like below with this design.
But now i am getting like below
I am getting dynamic menu data from database below is my code
<select id="dropdownlist" class="form-control" style="color:black">
</select>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/CDO/Menu",
data: "{}",
success: function (data) {
var s = '<option>All History</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id + '">' + data[i].type + '</option>';
}
$("#dropdownlist").html(s);
}
});
You can create a tags for button dropdown inside for-loop and then add that generated html inside your dropdown-menu.
Demo Code :
//just for demo :)
var data = [{
"Id": "1",
"type": "abc"
}, {
"Id": "2",
"type": "abc2"
}]
$(document).ready(function() {
var s = "";
/* $.ajax({
type: "GET",
url: "/CDO/Menu",
data: "{}",
success: function(data) {*/
for (var i = 0; i < data.length; i++) {
//generate a tag here ..
s += ' <a class="dropdown-item" href="#"> ' + data[i].Id + ' - Type : ' + data[i].type + '</a>'
}
$("#dropdownlist").html(s);
/* }
});*/
//on click of a tag inside dropdown
$(document).on('click', '.dropdown-menu a', function() {
console.log($(this).text())
$(".dropdown-toggle").text($(this).text()) //change text of button if needed
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div class="dropdown">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
All History
</button>
<div class="dropdown-menu" id="dropdownlist">
<!--here options will come -->
</div>
</div>

Accordion List Using Jquery and Ajax

I'm Trying to Implement an accordion list. So basically this a bootstrap accordion. The title of the accordion is already set by PHP. When the user clicks the accordion it must display list of the session that is coming from server. I am using an ajax call for this, the issue every time I click the accordion only first elements get the results. Other elements didn't get the result just a blank view is displayed. I am fairly new to jquery. Here is my Html Code
<div class="accordion" id="myAccordion">
<?php foreach($modules as $module): ?>
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button id="<?php echo $module->id;?>" type="button" class="btn" data-toggle="collapse"
data-target="#collapse<?php echo $module->id; ?>"><?php echo $module->module_name; ?></button>
</h2>
</div>
<div id="collapse<?php echo $module->id; ?>" class="collapse" aria-labelledby="headingOne"
data-parent="#myAccordion">
<div class="card-body">
<ul id="sessionlist" class="list-group list-group-flush">
<li class="list-group-item">
<i class="icon-play_circle_outline text-blue"></i>'+data[i].session_name+'' +
</li>
</ul>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
This is my Jquery and ajax code
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$.ajax({
url: "<?php echo base_url(); ?>dashboard/displaysession/" + this.id,
type: 'GET',
data: {},
error: function () {
alert('Something is wrong');
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var myhtmlstring = '<li class="list-group-item">' +
'<i class="icon-play_circle_outline text-blue"></i><a href="#">' +
data[i].session_name + '</a>' +
'</li>';
console.log($.parseHTML(myhtmlstring));
$("#sessionlist").append($.parseHTML(myhtmlstring));
}
},
dataType: 'json'
});
});
});
</script>
Really appricate your help
You need to give your sessionlists unique ids aswell. Because when you append your myhtmlstring to #sessionlist it only ever takes the first one.
<ul id="sessionlist<?php echo $module->id; ?>" class="list-group list-group-flush">
<li class="list-group-item">
<i class="icon-play_circle_outline text-blue"></i>'+data[i].session_name+'' +
</li>
</ul>
then you can append it to the right sessionlist in your ajax success:
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
const currentModuleId = this.id
$.ajax({
url: "<?php echo base_url(); ?>dashboard/displaysession/" + currentModuleId ,
type: 'GET',
data: {},
error: function () {
alert('Something is wrong');
},
success: function (data) {
$("#sessionlist" + currentModuleId ).html("");
for (var i = 0; i < data.length; i++) {
var myhtmlstring = '<li class="list-group-item">' +
'<i class="icon-play_circle_outline text-blue"></i><a href="#">' +
data[i].session_name + '</a>' +
'</li>';
console.log($.parseHTML(myhtmlstring));
$("#sessionlist" + currentModuleId ).append($.parseHTML(myhtmlstring));
}
},
dataType: 'json'
});
});
});
</script>

Change icons in children after click button in parent - ajax

I have a sortable list with topics and pages.
I want to do the follow thing: when I click in a eye button in a topic, the topic and your page children will be hide, changing their view icons. That is, if you change the icon on a topic, it changes for all your children.
For example:
Currently I can change the view icons in topic only. How do I do to change the view icon in pages children too?
PHP code:
//printing topic
if($list[$i]->getObj()->getSTop_view() == 0){
$view_icon = '<img id="imgEye" title="Hide" name="hide" src="/imgs/icons/ic_hide_16x16.png">';
} else {
$view_icon = '<img id="imgEye" title="Show" name="show" src="/imgs/icones/ic_show_16x16.png">';
}
$html.= '<li class="dd-item dd3-item" data-id="'.$list[$i]->getObj()->getTop_id().'" view-value="'.$list[$i]->getObj()->getTop_view().'">
<div class="dd-handle dd3-handle">'.$list[$i]->getObj()->getTop_name().'</div>
<div class="dd3-content">
<span style="font-weight: bold; font-size: 14px;">'.$list[$i]->getObj()->getTop_name().'</span>
<span class="span-right">
<a id="UpdateViewTop" name="'.$list[$i]->getObj()->getTop_id().'">'.$view_icon.'</a>
<a class="edit-button" href="..."><img title="Edit" src="/imgs/icons/ic_edit_16x16.png"></a>
<a class="del-button"><img title="Delete" src="/imgs/icons/ic_delete_16x16.png"></a>
</span>
</div>';
for($j=($i+1);$j < $cont_int;$j++) { //if the topic have children
//printing pages
if($list[$j]->getObj()->getPag_view() == 0) {
$view_icon = '<img id="imgEye" title="Hide" name="hide" src="/imgs/icons/ic_hide_16x16.png">';
} else {
$view_icon = '<img id="imgEye" title="Show" name="show" src="/imgs/icones/ic_show_16x16.png">';
}
$html.= '<ol id="stopitem" class="dd-list">
<li id="pagstopitem" class="dd-item dd3-item" data-id="'.$list[$j]->getObj()->getPag_id().'" view-value="'.$list[$j]->getObj()->getPag_view().'">
<div class="dd-handle dd3-handle"></div>
<div class="dd3-content">
<span>'.$list[$j]->getObj()->getPag_name().'</span>
<span class="span-right">
<a id="UpdateViewPag" name="'.$list[$j]->getObj()->getPag_id().'">'.$view_icon.'</a>
<a class="edit-button" href="..."><img title="Edit" src="/imgs/icons/ic_edit_16x16.png"></a>
<a class="delpagstop-button" name="'.$list[$j]->getObj()->getPag_id().'"><img title="Delete" src="/imgs/icons/ic_delete_16x16.png"></a>
</span>
</div>
</li>';
...
}
Javascript and Ajax code:
$(document).on('click', '#UpdateViewTop', function(e){
e.preventDefault();
var uid = $(this).attr('name');
var img = $(this).children('#imgEye');
var eye = img.attr('name');
var myData_IC_hide = '/imgs/icons/ic_hide_16x16.png';
var myData_IC_show = '/imgs/icons/ic_show_16x16.png';
$.ajax({
url: '/admin/control/ajax/view.php',
type: 'POST',
data: {id: uid},
dataType: 'html',
success: function() {
//here change the icon in topic when I click in eye button
//that's works fine!
//Now I want to change the icon in page children
if(eye == "show") {
img.attr('src', myData_IC_hide);
img.attr('name', 'hide');
img.attr('title', 'Hide');
} else if(eye == "hide") {
img.attr('src', myData_IC_show);
img.attr('name', 'show');
img.attr('title', 'Show');
}
}
});
});

Modifying a list in AngularJS

Attempting to make list items clickable without a checkbox. I want those items to to get a strike through when clicked and still have the delete option at the end. This functions properly, but I can't seem to maintain that when I try to make the items clickable. How do I need to modify this code to make it work?
<p class="lead" ng-bind="vm.list.content"></p>
<div class="list-group">
<span data-ng-repeat="item in vm.list.items|orderBy:'name'"
class="list-group-item" ng-class="{strike: item.check}">
<input type="checkbox" ng-model="item.check" ng-click="vm.cross(item)">
<a class="btn btn-default pull-right" ng-click="vm.remove(item)">
<i class="glyphicon glyphicon-trash"></i></a>
<h4 class="list-group-item-heading" ng-bind="item.name + ' - ' + item.priority"></h4>
</span>
</div>
Controllers:
function remove(item){
var removedItem = $scope.vm.list.items.indexOf(item);
$scope.vm.list.items.splice(removedItem, 1);
if (vm.list._id) {
vm.list.$update(successCallback, errorCallback);
} else {
vm.list.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('lists.view', {
listId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;}
}
function cross(item){
if (vm.list._id) {
vm.list.$update(successCallback, errorCallback);
} else {
vm.list.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('lists.view', {
listId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;}
}
Why not to move the checkbox behavior to the item wrapper? In this case, if click on the trash, the outer click handler will not be triggered because we stop event from further propagation.
<div class="list-group">
<span data-ng-repeat="item in vm.list.items|orderBy:'name'" class="list-group-item" ng-class="{strike: item.check}" ng-click="item.check = true; vm.cross(item)">
<a class="btn btn-default pull-right" ng-click="vm.remove(item);$event.stopPropagation();">
<i class="glyphicon glyphicon-trash"></i>
</a>
<h4 class="list-group-item-heading" ng-bind="item.name + ' - ' + item.priority"></h4>
</span>
</div>
If you want to cross/uncross item by click, you can implement a method like toggleCross and use it instead of "item.check = true" statement:
item.toggleCheck = function() {
this.check = !this.check;
}

if not count===0, I want the background of my notificiation box to turn red...how do I do this?

So if (count == 0)
{I want no effect on notification box}
else
{I want notification box to turn red}
so this is what I did, but it doesn't work. by doesn't work I mean nothing happens, I checked css through inspect element but nothing is there...
<style>
{% block style %}
#notification_dropdown.notification { background: red; }
{% endblock %}
</style>
<li class="dropdown">
<a href="#" class="dropdown-toggle notification-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class='glyphicon glyphicon-inbox' aria-hidden="true"></span>
<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu" id='notification_dropdown'>
</ul>
</li>
<script>
$(document).ready(function(){
$(".notification-toggle").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'get_notifications_ajax' %}",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$("#notification_dropdown").html(' <li role="presentation" class="dropdown-header">Notifications</li>');
var count = data.count
console.log(count)
if (count == 0) {
$("#notification_dropdown").removeClass('notification');
var url = '{% url "notifications_all" %}'
$("#notification_dropdown").append("<li><a href='" + url+ "'>View All Notifications</a></li>")
} else {
$("#notification_dropdown").addClass('notification');
$(data.notifications).each(function(){
var link = this;
$("#notification_dropdown").append("<li>" + link + "</li>")
})
}
console.log(data.notifications);
},
error: function(rs, e) {
console.log(rs);
console.log(e);
}
})
})
})
</script>
I added $("#notification_dropdown").removeClass('notification');
and $("#notification_dropdown").addClass('notification');
after if and else.
and then I use css...
what am I doing wrong?
Here is a minimalized example to answer your question:
HTML with your element and a button to trigger/test the JS code:
<ul class="dropdown-menu" role="menu" id='notification_dropdown'>
Notification text
</ul>
Button
CSS:
#notification_dropdown{
background-color: green;
}
#notification_dropdown.notification{
background-color: red;
}
and the JavaScript code:
myButton = $("#button");
count = 0;
myButton.click( function() {
myQuery = $("#notification_dropdown");
console.log( count );
if( count == 0 )
{
myQuery.removeClass( "notification" );
}
else
{
myQuery.addClass( "notification" );
}
// This is done just for the test matter
count++;
});
Simply click multiple times on the Button to trigger the associated click function which also changes count (for testing purpose).
The JQuery is save in the variable myQuery in order to avoid realizing the same query multiple times for no clear purpose.
Try is on JSFiddle

Categories