$(this).attr('id'); Not Working - javascript

Good day to all I am building a page and everything is going good until this last step.
Here's the code:
$(document) .ready(function(){
var a;
var b=0;
var z="";
var menu = [
{ name: "LOGO", items: [] },
{ name: "BANNERS", items: ["Banner", "Banner inside the Body"] },
{ name: "HEADERS", items: ["Header1", "Header2", "Header3", "Header4", "Header5"] },
{ name: "BODY TEXT", items: [] },
{ name: "LISTS", items: ["List1", "List2", "List3"] },
{ name: "TABLES", items: ["Table", "Table Text"] },
{ name: "GRAPHS", items: ["Graph1", "Graph2"] },
{ name: "HEADERS/FOOTERS SECTION", items: [] },
{ name: "SPECIAL SECTION", items: ["Special Section1", "Special Section2", "Special Section3", "Special Section4", "Special Section5"] },
];
for (a=0; a<menu.length; a++){
z+='<div class="menu-enclosure" id="butt-'+a+'"><button class="btn">'+menu[a].name+'</button>';
while (b<menu[a].items.length) {
z+='<button class="sub" id="subt-'+b+'">'+menu[a].items[b]+'</button>';
b++;
}
b=0;
z+="</div>";
}
$('.menu-holder') .append(z);
$(document) .on('click', '.menu-enclosure', function(){
var clicked =$(this).attr('id');
var z = clicked.replace(/\D/g, '');
var x =0;
$('.content-holder') .html("");
$('.content-holder') .append('<div class="title-bar"><span class="reg-wht">'+menu[z].name+'</span></div><BR><div class="photo-holder"><img alt="'+menu[z].name+'" src="'+menu[z].name+'"></div>');
$('.sub') .hide();
while (x<menu[z].items.length) {
$('#'+clicked+' #subt-'+x) .show();
x++;
}
x=0;
$(document) .on('click', '.sub', function(){
var clicked =$(this).attr('id');
$('.content-holder') .append(clicked);
});
});
});
Also, here's the JS Fiddle.
https://jsfiddle.net/453azpLr/embedded/result/
If you've visited my fiddle, you will notice that everything works fine except for the last part (lines 50 and so on).
As you can see when you click in the menu, the Text of whatever is clicked is then reflected to the content-holder div. But when i click on the sub menu it doesn't work.
I don't know what the main problem is or if I'm looking at it correctly but I have tried changing line 51 to various things like the once below:
var clicked =$(this).children("button").attr('id');
var clicked =$(this).find("button").attr('id');
var clicked =$(this).children().attr('id');
I also have tried changing the selector (.menu-enclosure) to the classed and ids of the buttons but to no avail.
As for the time being, I am trying to figure out if clicking gets the correct id thus the code:
$('.content-holder') .append(clicked);
Help pls

It should work if you change the first bit to this :
$(document).on('click', '.menu-enclosure', function(e) {
var clicked = e.target.id || this.id;
This will retrieve the actual element the click originated from instead of the parent. When changing it to this, the element that is returned when opening the menu will no longer be the wrapper div itself but the first child button. This has no id but a class, so if it turns up empty it will look at the parent div next.
Note that this won't work anymore whenever <button class="btn"> would get it's own id. You could leave the second check out if these buttons get the id transferred from the .menu-enclosure parent.
https://jsfiddle.net/37eyppnh/
By the way, when the ids from .menu-enclosure are transferred to the buttons this would also work :
$(document).on('click', '.menu-enclosure button', function() {
var clicked = this.id;

Related

For in Javascript does not work for events from a JSON

I recive this part of a JSON:
"out": {
"gen": [
{
"title": "Options",
"opt": [
{
"label": "Button1",
},
{
"label": "Button2",
},
And, I try to put as a button, every labale value with this, because I need to send the value of those buttons to a function. The send() function:
var options = '';
var p;
for(let i=0;i<q.out.gen[0].opt.length;i++) {
var opt=options +=`<input id='element' type='button' value="${q.out.gen[0].opt[i].label}">`;
$(document).ready(function(){
$("#element").click(function(){
p = ($(this).attr("value"));
send(p);
});
});
}
var resp = rch(
`<b>${opt}<br>`,
);
The code puts the buttons I need but at the time of executing it, only the first label of the first button works, and sends twice
"Button1" "Button1"
And the second button that is "Button2" not working.
How can i fix this? That each label is a button and at the moment of pressing it send the value of each button that would be "Button1" and "Button2". Thanks
Can you try switching id='element' to class='element'?
Might be a fix with $(document).on("click", ".element", function() {...} as well if still not working after change using event delegation..

How to open and close a div if its clicked on Twice

This is my jsfiddle
http://jsfiddle.net/1ty1v8u1/5/
If an element is clicked on twice , how can i achieve toggle behavior for that particular div ?
If i click on office twice in the jsfiddle how to make it open and close ??
This is my code
function showRestaurantDetailsByLocation(response,locationname)
{
$('.restListings').remove();
$('.addNewRestaurant').remove();
var ulhtml = $('<ul class="restListings"></ul>');
var divhtml = $('<div class="inner-intit"><sub class="sub">Your Favorite Area</sub></div>');
divhtml.append('<br>');
var $newbutton= $('<input/>').attr({ type: 'button', location:locationname , name:'btn1', class:'btn btn-success addNewRestaurant', value:locationname});
for(var i=0;i<response.length;i++)
{
divhtml.append('<li><h6>'+response[i].area+'</h6><p>'+response[i].address+'</p><span id="delete" class="inDelete inDeleteSub"></span></li>');
}
divhtml.append($newbutton);
ulhtml.append(divhtml);
$("#"+locationname).append(ulhtml);
}
You are appending the new elements on click. Just check for previously appended element in same div. If it exist then simply remove it, if not then add new:
$(document).on('click', '.lielement', function() {
var locationname = $(this).attr("id");
if($(this).find('.restListings').length)
$(this).find('.restListings').remove()
else
displayingRestaurantByArea(locationname);
});
Working Demo

Hide a text input on a dialog box of CKEditor

I'm working on a plugin in CKEditor which have as a goal to hide or show element depending on which of my check box is checked. I have those element defined :
contents :
[
{
id : 'tab1',
label : 'Configuration Basique',
elements :
[
{
type : 'checkbox',
id : 'check',
label : 'Vers une page web',
'default' : 'unchecked',
onClick : function(){
}
},
{
type : 'text',
id : 'title',
label : 'Explanation',
}
]
},
{
id : 'tab2',
label : 'Advanced Settings',
elements :
[
{
type : 'text',
id : 'id',
label : 'Id'
}
]
}
],
so now what i would like to do is to hide no disable the text input with the label and print it only when the box is checked. So i've seen that i should use something like that :
onLoad : function(){
this.getContentElement('tab1','title').disable();
},
but the thing is i don't want to disable it i want to hide and then print it if the user check the box (which is why i put a onClick function in my checkbox). i've tryed to use the hide() function but it doesn't work and also the setAttribute('style','display : none;')
Tia :)
If you actually want to hide (and not disable) the element you can do this using
this.getContentElement('tab1','title').getElement().hide();
The extra getElement() call returns the litteral DOM object for your contentElement object, so you can call hide()/show() at will on it.
The onClick properties is available and does work on uiElement although it is not documented. The biggest problem is the definition of "this" is not the same inside the event than other place in the config. You first have to get the dialog to get other fields:
{
type: 'checkbox',
id: 'check',
label: 'check',
onClick: function() {
var dialog = this.getDialog()
if(this.getValue()){
dialog.getContentElement('tab1','title' ).disable();
} else {
dialog.getContentElement('tab1','title' ).enable()
}
}
}
Your checkbox definition is correct but there's no such thing like onClick property in dialog uiElement definition. All you got to do is to attach some listeners and toggle your field. Here you go:
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( isThisYourDialog? ) {
...
// Toggle your field when checkbox is clicked or dialog loaded.
// You can also use getInputElement to retrieve element and hide(), show() etc.
function toggleField( field, check ) {
field[ check.getValue() ? 'enable' : 'disable' ]();
}
var clickListener;
dialogDefinition.onShow = function() {
var check = this.getContentElement( 'tab1', 'check' ),
// The element of your checkbox.
input = check.getInputElement(),
// Any field you want to toggle.
field = this.getContentElement( 'tab1', 'customField' );
clickListener = input.on( 'click', function() {
toggleField( field, check );
});
// Toggle field immediately on show.
toggleField( field, check );
}
dialogDefinition.onHide = function() {
// Remove click listener on hide to prevent multiple
// toggleField calls in the future.
clickListener.removeListener();
}
...
}
});
More docs: uiElement API, dialog definition API.

Suppressing a Kendo UI Grid selectable event when clicking a link within a cell

I have a Kendo grid that has links, which I also set to selectable, snippet here:
columns: [{
field: 'link', title: 'Link',
template: 'Click Here'
}],
...
selectable: 'row',
change: function(e) {
var rowUid = this.select().data('uid');
rowDs = this.dataSource.getByUid(rowUid);
console.log('Went (1): ' + rowDs);
return false;
}
When I click on the external link <a>, I also select the row. Is there any way to suppress the selectable event?
You can also detect what element triggered the click by giving the column a CSS class. Then you would put an if-statement in the change event to detect if the column was clicked or not:
columns: [
{
title: ' ',
command: {
text: 'My Button',
click: function (e) {
e.preventDefault();
//GET SELECTED DATA
var data = this.dataItem($(e.currentTarget).closest('tr'));
//DO SOMETHING
}
},
attributes: {
'class': 'actions'
}
}
]
Then in the change you would have this:
change: function (e) {
//GET TRIGGER SOURCE TO DETERMINE IF ACTION CLICKED
var eventTarget = (event.target) ? $(event.target) : $(event.srcElement);
var isAction = eventTarget.parent().hasClass('actions');
//SELECT ITEM IF APPLICABLE
if (!isAction) {
var grid = e.sender;
var dataItem = grid.dataItem(this.select());
if (dataItem) {
//DO SOMETHING
}
}
}
I just stumbled across a forum post by a Kendo UI dev stating that "the selection of the grid cannot be prevented" (link). I guess that means I will have to work around this.
Edit: I actually just want to get the row's uid attribute so I can select the selected dataItem from the dataSource. I've discovered that you can get it while you're defining your columns template,
columns: [{
field: 'link', title: 'Link',
template: 'Manual Edit Link'
}],
And use it to retrieve the selected row's dataItem.
var selectedRow = $('#gridId').data('kendoGrid').dataSource.getByUid(rowUid);
Will close this question in a while, in case anyone else can help.

OnBlur effect for select dropdown

I have a select dropdown and if a user clicks 'outside' of that select dropdown, I want it to disappear. This is what I currently have:
$(this).html($("<select/>", {
id: 'sel',
change: function() {
selectdone(this, title_id, status_type);
},
blur: function() {
selectdone(this, title_id, status_type);
},
In the above, if I click outside of the dropdown, nothing happens. The only time the function is firing is if I change the value of the select dropdown.
How would I accomplish the above, such that when a user clicks anywhere on the document outside of the select dropdown, it fires this function?
I don't think this is possible. As pointed out in another answer, it appears that the active <select> is prohibiting other input from being accepted.
See my updated fiddle. Notice that when you click the background you get the alert test when the select isn't expanded. When it is expanded and you click off, the alert doesn't fire. This appears to be the default behavior of the browser. It appears to be ignoring all other inputs (mouse movements included) while the select is activated.
I was, however, able to get your event to fire for any selected element by setting the selectedIndex to -1. This way any valid option will result in a change.
Example
$(function(){
var title_id = '', status_type = '';
$('body').html(
$("<select/>", {
id: 'sel',
change: function() {
selectdone(this, title_id, status_type);
},
blur: function() {
selectdone(this, title_id, status_type);
}
})
.append($('<option />', { 'text':'one'}))
.append($('<option />', { 'text':'two'}))
);
$('#sel').prop('selectedIndex', -1);
});
function selectdone(element, titleid, statustype){
$(element).hide().prop('selectedIndex', -1);
}

Categories

Resources