JQuery - select-result show message on select - javascript

plugin demo: http://jqueryui.com/selectable/#serialize
Hello, I don't quite understand this "plugin" and specifically
result.append( " #" + ( index + 1) ); &
<span>You've selected:</span> <span id="select-result">none</span>.
I want the user to be able to select one of the following "buttons" and then a message to show in place of the Number selected (as in the demo)
So: You've selected: #2.
Would be: You've selected: UK, please goto this and do that etc...
im guessing the easiest way is with JavaScript
if "select-result" = 1 then
else
Sort of thing?
Any help Would be great! i hope this isn't a stupid question...
Code:
<html>
<head>
<title>jQuery UI Selectable - Serialize</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery- ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>
<script>
$(function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" ).empty();
$( ".ui-selected", this ).each(function() {
var index = $( "#selectable li" ).index( this );
result.append( " #" + ( index + 1) );
});
}
});
});
</script>
</head>
<body>
<p id="feedback">
<span>You've selected:</span> <span id="select-result">none</span>.
</p>
<ol id="selectable">
<li class="ui-widget-content">UK</li>
<li class="ui-widget-content">USA</li>
<li class="ui-widget-content">FR</li>
<li class="ui-widget-content">AU</li>
<li class="ui-widget-content">CA</li>
<li class="ui-widget-content">DE</li>
</ol>
</body>
</html>

the example in the plugins is showing the selected index.. you don't need to do that... what you need to do is get the text of selected and show it in span.. so use.. html() or text()..
try this
$(function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" );
result.html($(this).html()); // result.text($(this).text());
}
});
});

var index = $( "#selectable li" ).index( this );
This grabs the index of the element we've been passed. We don't need this line.
result.append( " #" + ( index + 1) );
The index is the position at which the element occurs while descending the DOM.
We can change the above lines to one simple thing.
$( ".ui-selected", this ).text().appendTo(result);
Edit: See above, this may refer to the entire ul, so we need to filter it by the item that is selected. If you are allowing for a multi-select, then see below.
$( ".ui-selected", this ).each(function(){
$(this).text().appendTo(result);
});

Related

jQuery sortable - Bind new on('dblclick') to cloned element

I have connected lists using jQuery sortable().
The lists are initialized with
$( "#held, #notheld" ).sortable({
connectWith: ".connectedSortable",
}).disableSelection();
When the page loads I also bind dblclick
$('#held li').on('dblclick', function() {
var litem = $(this).clone();
litem.appendTo($('#notheld'));
$(this).remove();
update_holding(litem.attr('id'), 'remove');
$( "#held, #notheld" ).sortable( "refresh" );
});
$('#notheld li').on('dblclick', function() {
var litem = $(this).clone();
litem.appendTo($('#held'));
$(this).remove();
update_holding(litem.attr('id'), 'add');
$( "#held, #notheld" ).sortable( "refresh" );
});
Once the cloned LI is appended to the other list it needs to have the correct .on('dblclick') function bound. If I clone with true boolean as an arg the bindings get copied but I do not want the original function but rather the one associated with the list to which it now belongs.
The elements can still be dragged to new list without error.
I have tried adding the binding function to the activate, change, and update events in the initializing call in the hope that refresh() would see new element and do the .on() assignment but these were ineffective.
I also tried re-writing the initial bindings like so
$('#notheld li').on('dblclick', function() {
var litem = $(this).clone();
litem.appendTo($('#held'));
$(this).remove();
update_holding(litem.attr('id'), 'add');
litem.on('dblclick', function() {
var litem2 = $(this).clone();
litem2.appendTo($('#notheld'));
$(this).remove();
update_holding(litem2.attr('id'), 'remove');
});
});
But this does not call the function correctly? Perhaps the use of $(this) is not correct?
The update_holding() function should not bear on the issue as it is just an ajax post to another script managing the database updates.
Here is a working example: https://jsfiddle.net/qn6v42c9/
Also read
jQuery clone() not cloning event bindings, even with on() and
jquery .on() doesn't work for cloned element
I would use click event delegation on sortable container itself so I would not have to bind the dbclick again and again, here is the code for it
$("#held, #notheld").sortable({
connectWith: ".connectedSortable",
}).disableSelection();
$('#held').on('dblclick', 'li', function() {
var litem = $(this).clone();
litem.appendTo($('#notheld'));
$(this).remove();
update_holding(litem.attr('id'), 'remove');
$("#held, #notheld").sortable("refresh");
});
$('#notheld').on('dblclick', 'li', function() {
var litem = $(this).clone();
litem.appendTo($('#held'));
$(this).remove();
update_holding(litem.attr('id'), 'add');
$("#held, #notheld").sortable("refresh");
});
// dropped
$('#held').on('sortreceive', function(event, ui) {
update_holding(ui.item.attr('id'), 'add');
});
// dropped
$('#notheld').on('sortreceive', function(event, ui) {
update_holding(ui.item.attr('id'), 'remove');
});
function update_holding(EntityNumber, action) {
// ajax here
}
#held, #notheld {
border: 1px solid #eee;
width: 272px;
min-height: 20px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
}
#held li, #notheld li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 250px;
cursor:move;
}
#notheld li {
float: left;
clear: none;
display: inline-block;
}
div#notheld-container, div#held-container {
width: 300px;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div id="notheld-container">
<h3>Properties Not Held by <em>Client</em></h3>
<ul id="notheld" class="connectedSortable">
</ul>
</div>
<div id="held-container">
<h3>Current Holdings</h3>
<ul id="held" class="connectedSortable ui-sortable">
<li class="ui-state-highlight ui-sortable-handle" id="12">Farragut (12)</li><li class="ui-state-highlight ui-sortable-handle" id="1010" style="">King Street (1010)</li>
<li class="ui-state-highlight ui-sortable-handle" id="07">Annandale (07)</li>
<li class="ui-state-highlight ui-sortable-handle" id="13">Aquahart (13)</li>
</ul>
</div>

Selecting consecutive elements using jQuery selectable

I am trying the Serialize sample in jQuery.
I notice one behavior that I can select unrelated elements using mouse and Ctrl key.
I only want to select consecutive elements and not all elements on mouse clicks.
This is what is happening currently, its taking Item 1, 2 and 6 as the selections.
I want to only select consecutive elements and not unrelated elements by mouse click and add a validation error that you can only add consecutive elements like in the following screenshot.
This is the code, I am working on, currently:
$(function() {
$(`#selectable`).bind("mousedown", function(e) {
e.metaKey = true;
}).selectable({
selected: function(event, ui) {
//For toggling between select clicks
if ($(ui.selected).hasClass('click-selected'))
$(ui.selected).removeClass('ui-selected click-selected');
else {
$(ui.selected).addClass('click-selected');
console.log(ui.selected.innerText);
let selectedID = ui.selected.id;
$("#select-result").append(ui.selected.innerText);
}
},
unselected: function(event, ui) {
$(ui.unselected).removeClass('ui-selected click-selected');
}
});
});
#feedback {
font-size: 1.4em;
}
#selectable .ui-selecting {
background: #FECA40;
}
#selectable .ui-selected {
background: #F39814;
color: white;
}
#selectable {
list-style-type: none;
margin: 0;
padding: 0;
width: 60%;
}
#selectable li {
margin: 3px;
padding: 0.4em;
font-size: 1.4em;
height: 18px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Selectable - Serialize</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p id="feedback">
<span>You've selected:</span> <span id="select-result">none</span>.
</p>
<ol id="selectable">
<li class="ui-widget-content">Item 1</li>
<li class="ui-widget-content">Item 2</li>
<li class="ui-widget-content">Item 3</li>
<li class="ui-widget-content">Item 4</li>
<li class="ui-widget-content">Item 5</li>
<li class="ui-widget-content">Item 6</li>
</ol>
</body>
</html>
Here's the fiddle, which I am working on.
I think that there is 2 cases,
First case is when no item is selected on your list so you can select any element.
Second case : when one or many items are selected so you have to be sure that the item to select is neighbor of the selected items.
$(function () {
$(`#selectable`).bind("mousedown", function (e) {
e.metaKey = true;
}).selectable({
selected: function (event, ui) {
//For toggling between select clicks
if ($(ui.selected).hasClass('click-selected'))
$(ui.selected).removeClass('ui-selected click-selected');
else {
//case when no Item is selected on your list
let noItemIsSelected = !$(".ui-widget-content").hasClass('click-selected');
//Case when on of neighbor's Item selected
let oneOfNeighborsIsSelected = $(ui.selected).next().hasClass('click-selected') || $(ui.selected).prev().hasClass('click-selected');
if (noItemIsSelected || oneOfNeighborsIsSelected) {
$(ui.selected).addClass('click-selected');
console.log(ui.selected.innerText);
let selectedID = ui.selected.id;
console.log(event);
$("#select-result").append(ui.selected.innerText);
} else {
$(ui.selected).removeClass('ui-selected click-selected');
}
}
},
unselected: function (event, ui) {
$(ui.unselected).removeClass('ui-selected click-selected');
}
});
});
You can see the updated version of your code here

Jquery Sortable List with getJSON method

I am working on a tutorial that uses getJSON to add list items to the DOM. There also needs to be the JqueryUI sortable plugin to sort the lists. For some reason unknown to me the plugin does not work. What am I missing here? Should the sortable function be inside the getJSON callback? Any suggestions would be great.
here is my code I have so far:
$(function () {
$('body h1').append('My Todo List');
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
});
HTML File:
<!DOCTYPE html>
<html>
<head>
<title>Jquery ToDo List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="todo.js"></script>
<script>
$(function () {
$("#sortable").sortable("refresh");
$("#sortable").disableSelection("refresh");
});
</script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 14px; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
</head>
<body>
<h1></h1>
<div id="container">
</div>
</body>
</html>
JSON
[
{"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
{"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
{"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
{"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}
]
you have to call the sortable after appending the data. In your $.getJSON callback call the sortable again like given below. jquery will wire the sortable only if the element is present in the DOM when the dom is ready. you are adding the elements dynamically so you have to call the sortable again after adding the elements into the DOM.
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
Edit
Here is the bin http://jsbin.com/IPubElE/1/
demo uses the in-memory data but it should work fine even inside the callback method.

How to activate menu tab after refreshing

How can I activate a menu tab after refreshing?
Here are my code
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 600px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href='#'>One</a></li>
<li><a href='#'>Two</a></li>
<li><a href='#'>Three</a></li>
<li><a href='#'>Four</a></li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
Can anyone tell me How to resolve this issue ?
Just like #Johan said, store your last active tab in a localStorage or cookie. Since there is no noticeable difference in performance between the two. I suggest you use localStorage because it's much easier to use. Like this:
function make_button_active(tab) {
//Get item siblings
var siblings = tab.siblings();
//Remove active class on all buttons
siblings.each(function(){
$(this).removeClass('active');
})
//Add the clicked button class
tab.addClass('active');
}
//Attach events to menu
$(document).ready(function(){
if(localStorage){
var ind = localStorage['tab']
make_button_active($('.menu li').eq(ind));
}
$(".menu li").click(function () {
if(localStorage){
localStorage['tab'] = $(this).index();
}
make_button_active($(this));
});
});
Check out this fiddle.

Why is this alert being fired three times instead of once

In this jsBin file an alert (which just displays 'fired') is called three times.
It should be just called once since its just added to :
.data( "autocomplete" )._renderItem = function( ul, item ) {
Here is the bin file :
http://jsbin.com/welcome/55641/edit
How can the code be amended so that the alert is just fired once ?
The entire code :
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
fieldset {width: 60%; margin: 0 auto;}
div.row {clear: both;}
div.row label {float: left; width: 60%;}
div.row span {float: right; width: 35%;}
</style>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Custom data and display</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
padding: 0;
}
</style>
<script>
$(function() {
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
alert('fired');
return $("#suggestionsDiv").append("<div class='row'> <label for='first-field'>The first field</label><span><input type=text id='first-field' size='15' /></span></div>");
};
});
</script>
</head>
<body>
<div id="project-label">Select a project (type "j" for a start):</div>
<img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
<input id="project" />
<input type="hidden" id="project-id" />
<p id="project-description"></p>
<fieldset>
<legend>Suggestions</legend>
<div id ="suggestionsDiv">
<div class="row">
<label for="first-field">The first field</label>
<span><input type="text" id="first-field" size="15" /></span>
</div>
<div class="row">
<label for="second-field">The second field with a longer label</label>
<span><input type="text" id="second-field" size="10" /></span>
</div>
<div class="row">
<label for="third-field">The third field</label>
<span><input type="text" id="third-field" size="5" /></span>
</div>
</div>
</fieldset>
</body>
</html>
​
When you type j in the field as suggested, three items are returned. For each item, the _renderItem method is being called to render each item, resulting in three alerts. It is working as intended.

Categories