How to make <li> editable on click? - javascript

I have a menu that looks like this:
I want to make it possible that when the user clicks on + the <li> element that it's located inside becomes like an editable input form, where a new menu item name can be created and saved (by entering the name and clicking Enter).
The code of the current item is
<li id="addNewContext" class="menu-item-divided">+</li>
Is there a snippet of code I could use to make that field editable that could save the name entered into an array, which I can then use to repopulate the menu?
Thanks!

HTML5 allows for a ContentEditable attribute to be added to any HTML element. Assign a function to the onclick event for the list item, and make it set the ContentEditable attribute to true.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_Editable
var list = document.querySelector('ul');
var editList = document.querySelector('.edit-list');
editList.onclick = function() {
//or you can use list.setAttribute("contentEditable", true);
list.contentEditable = true;
}
<ul>
<li>list item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li><span class="edit-list">+</span>
</li>
</ul>
JSFiddle as well: http://jsfiddle.net/b8m35wwk/1/

I want to make it possible that when the user clicks on + the <li> element that it's located inside becomes like an editable input form, where a new menu item name can be created and saved (by entering the name and clicking Enter).
This sample also remove + sign on click:
$('#addNewContext')
// on click, make content editable.
.click(function() {
$(this).html("").attr('contenteditable', 'true');
})
// on hit enter,
.keyup(function(e) {
if (e.keyCode == 13) {
var val = $(this).text();
$(this)
// create a new li item
.before("<li>" + val + "</li>")
// set plus sign again
.html("+")
// make contenteditable to false, when clicked the process start again.
.attr('contenteditable', 'false');
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>not edit me</li>
<li>not edit me</li>
<li>not edit me</li>
<li>not edit me</li>
<li id="addNewContext" class="menu-item-divided">+</li>
</ul>

You can use contentEditable
let list_1_e = document.getElementById('addNewContext');
list_1_e.contentEditable = true;

Related

Adding item to html list with JS when there is no ID

I'm working on a script to add some extra features to a menu. The current user-menu is a drop-down list with links such as My profile, My reports, etc. I'm looking to add another item, "My posts".
I'm having a couple of difficulties due to the way the site is working.
This is the code for the drop down:
<li class="user expandable">
*list items*
</li>
I'm using document.getElementById to pick up elements but have no idea how to pick up the list and add an item to it. I believe there are other element pickers such as class but they didn't seem to work either.
Adding item to html list with JS when there is no ID
To get the first found item document.querySelector then use a css selector for example document.querySelector('div') to find the first div or document.querySelector('.user') to find the first element with class user
to get every item that matches document.querySelectorAll which will return an array of all the items matched.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
const list = document.querySelector('.user.expandable');
function addMyNewRow(message, index = 0) {
const node = document.createElement('li');
node.innerHTML = message
list.insertBefore(node, list.childNodes[index]);
}
function addChild() {
addMyNewRow('clicked and added in first');
}
addMyNewRow("added in second", 2)
<ul class="user expandable">
<li>old list item</li>
<li>old list item</li>
<li>old list item</li>
<li>old list item</li>
</ul>
<button onclick="addChild()">add list </button>
I think this is something similar to what you're looking for:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn2").click(function(){
$(".user").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>
<ol class="user expandable">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn2">Append list item</button>
</body>
</html>
$( "li" ).hover(
function() {
$( this ).append( $( hfhfhfha ) );
}
);
"this" keyword gives you the reference you need.

Find if there is any repeat content in a list and remove repeated instances

Basically what I'm trying to do is identify if there is any duplicate content from a list of items that all share the same class, and then remove any duplicates.
Here's my attempt so far but has been unsuccessful:
var listItemContent = $(".featured-listing").textContent;
if (listItemContent === listItemContent) {
$('.featured-listing').hide();
}
This isn't really working, and I'm not surprised as js is not my strong suit and even reading it it looks like it would take the content of an instance of ".featured-listing", compare it to itself and then hide it, resulting in all instances of that class being hidden. The problem is I'm not really sure how to:
Check if DIFFERENT instances of that class have matching text content
Remove any duplicated content
Try this snippet:
var listItemContents = [];
$(".featured-listing li").each(function() {
var text = $(this).text();
if (listItemContents.indexOf(text) == -1) {
listItemContents.push(text);
}
else {
$(this).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="featured-listing">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
<li>Text 1</li>
<li>Text 4</li>
<li>Text 2</li>
</ul>
It just loop through all items checking their content by an array. If the text isn't found in the array, it adds the item. If it is found, it removes the list item.
I'm not sure if that html is like yours since you didn't added it in your post. If you do, we can have a clearer idea of what would works better for you.
Get all the featured-listings. Define a main object which holds all the texts and then delete an element if there is the same text:
var elements = {};
$('.featured-listsing').each(function () {
var currentText = $(this).text();
if ( elements[currentText] )
$(this).remove();
else
elements[currentText] = true;
});
You can filter your jQuery list object taking those that are repeated and hide them. Check the next fiddle, the technique is to check those items that have a previous sibling with the same text content and create a new jQuery list with them:
let items = $(".featured-listing li");
let repes = items.filter((ind, itm) => $(itm).prevAll(`:contains(${itm.innerText})`).length);
repes.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="featured-listing">
<li>1 - Content 01</li>
<li>2 - Content 02</li>
<li>1 - Content 01</li>
<li>3 - Content 03</li>
<li>4 - Content 04</li>
<li>2 - Content 02</li>
<li>5 - Content 05</li>
<li>6 - Content 06</li>
<li>2 - Content 02</li>
<li>7 - Content 07</li>
</ul>

jQuery Sortable - moving elements between list with Double-Click

I would like to add a functionality to the original jQuery Sortable Connect List example at: http://jqueryui.com/sortable/#connect-lists
Since my second list (#sortable2) is kind of large... I would like to be able to scroll the page down and once I found the item that I need to select/move... just Double.Click on it in order to move it to the other list.
I need to move the items (li) from #sortable2 to #sortable1 as well as from #sortable1 to #sortable2. The idea is just to Double-Click and not Dragging.
THANKS!
Your html
<ul id="sortable1" class="sortable_list connectedSortable">
<li class="ui-state-default">sortable1 Item 1</li>
<li class="ui-state-default">sortable1 Item 2</li>
</ul>
<ul id="sortable2" class="sortable_list connectedSortable">
<li class="ui-state-default">sortable2 Item 1</li>
<li class="ui-state-default">sortable2 Item 2</li>
</ul>
Only from id = sortable2 you will have the items appended to sortable1 with li.class = ui-state-default. This adds one li item at a time from sortable2 to sortable1 .
script
//attach on load
$(function() {
$("#sortable2 .ui-state-default").dblclick(function(){
$("#sortable1").append(this);
});
});
$(function() {
$("ul li").dblclick(function(){
var parentID = $(this).parent().attr('id'); //sortable1 or sortable2
if(parentID.match(/^(sortable1)$/g))
$("#sortable2").append(this);
else if(parentID.match(/^(sortable2)$/g))
$("#sortable1").append(this);
});
});

How to get selected dropdown value

I have a dropdown menu like this:
<ul class="dropdown-menu" id="Appdropdown">
</ul>
which I am populating dynamically using this code:
for (var i = 0; i < arrdropdownMenuItems.length; i++)
{
dropdownMenuhtml += '<li>' + arrdropdownMenuItems[i] + '</li>';
}
$('#ApplicationNames').css("visibility", "visible");
$('#Appdropdown').append(dropdownMenuhtml);
And now when the user clicks on an <a>, I need to get the selected dropdown value. - I've tried this:
$('ul#Appdropdown').click(function ()
{
var cache = $('.btn-primary').children();
$('.btn-primary').text($(this).text()).append(cache);
}
but it's not giving the selected value from the dropdown.
Though it is not correct to listen click on parent element rather than child event, still your requirement can be accomplished using following code.
Basically you can fetch actual element that is clicked from event data that is passed by click event by default.
$('ul#Appdropdown').click(function (ev) {
var a = $(ev.target);
if(a.is("a"))
$('#selectedText').text($(a).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" id ="Appdropdown">
<li>Test A</li>
<li>Test B</li>
<li>Test C</li>
<li>Test D</li>
<li>Test E</li>
</ul>
<div id="selectedText"></div>
Several things missing in you code.
First ensure you are writing entire piece of code in document.ready,then make sure you fire the click event on li click instead of ul.Next as you are creating the control dynamically use .on.
$(document).ready(function() {
$('ul#Appdropdownli li').on('click', function() {
var selctedtext = $(this).find('a').html();
console.log(selctedtext);
});
});
You can get the selected drop-down value using the following code.
Please note, a reference of #selectedText is kept outside the event handler for a so no additional dom query is necessary.
var selectedText = $('#selectedText');
$('#Appdropdown > li > a').on('click', function(event) {
selectedText.text($(event.target).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" id="Appdropdown">
<li>Test A</li>
<li>Test B</li>
<li>Test C</li>
<li>Test D</li>
<li>Test E</li>
</ul>
<div id="selectedText"></div>
You could add a class/id to each option, and then add an event listener to that class, like this:
Html:
<ul class="dropdown-menu">
<li><button class="dropdown-option">Option 1</button></li>
<li><button class="dropdown-option">Option 2</button></li>
<li><button class="dropdown-option">Option 3</button></li>
<li><button class="dropdown-option">Option 4</button></li>
<li><button class="dropdown-option">Option 5</button></li>
</ul>
JavaScript:
$('.dropdown-option').click(function () {
console.log($(this).html());
});
$(this) is the actual element that is being clicked.
Pretty simple solution, which could also easily be converted to vanilla javascript.
JSfiddle example

post ajax when item on index page clicked

I have an index page, where a user can activate one item at a time. When a user clicks the activate button I want to do something to the item. My predicament is how do I identify which item was clicked on the page. Is there a way I can have 1 javascript function that could be used to handle any of the items clicked on?
html:
<ul>
<li> item 1 </li>
<li> item 2 </li>
<li> item 3 </li>
</ul>
js:
$('.li').click(function() {
$.ajax({
url: "/activate,
type: 'post',
dataType: "json",
data: {
item: { id: 1 }
},
success: function(data){
alert("you did it")
}
})
})
To expand upon the other comments, once the other errors are fixed (such as your selector, the lack of semicolons, etc), you can use the this variable to retrieve the information you're looking for. In addition, you can add an id to each li element so you know which one you're looking at. For example:
HTML
<ul>
<li id="li1"> item 1 </li>
<li id="li2"> item 2 </li>
<li id="li3"> item 3 </li>
</ul>
Javascript
$('li').click(function() {
console.log($(this).attr('id'));
});
If you're trying to select the <li> element, in the jQuery change .li to li(just remove the dot).
You only use to dot "." when you're selecting a class ("#" for selecting an id). So basically you've been selecting a class called li instead of the element <li>
Once you select the element you want, inside the jQuery selector you can use $(this) to refer to the same element that was clicked.
eg:
Changethe color
$("li").click(function(){
//Button was clicked
$(this).css("color", "#ff0000"); // Change color of clicked li
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>test 1</li>
<li>test 2</li>
</ul>
There is a parameter event passed to your function that handle the click. From that you can find the target element:
$('.li').click(function(event) {
var target = event.target;
....
});
Another way is this indicator:
$('.li').click(function() {
$(this).text();
});

Categories