Im starting to learn JavaScript/jQuery and have the code below that works but there must be some shorter code to write for this simple function.
The function:
Font awesome icon to show and change when i choose access level in the boot strap button group.
$(document).ready(function() {
$("#access").html(' Alla');
$("#accessIcon").addClass('fa-globe');
$('#access_input').val(0);
});
/*
' access
' 0 = all
' 1 = friends
' 2 = private
*/
$(".access").click(function(e) {
var accessId = $(this).attr('id');
if (accessId == 0) {
//alert("Alla = "+ accessId);
$("#access").html(' Alla');
$("#accessIcon").removeClass('fa-group');
$("#accessIcon").removeClass('fa-eye');
$("#accessIcon").addClass('fa-globe');
$('#access_input').val(accessId);
} else if (accessId == 1) {
//alert("Vänner = "+ accessId);
$("#access").html(' Vänner');
$("#accessIcon").removeClass('fa-globe');
$("#accessIcon").removeClass('fa-eye');
$("#accessIcon").addClass('fa-group');
$('#access_input').val(accessId);
} else if (accessId == 2) {
//alert("Privat = "+ accessId);
$("#access").html('Privat');
$("#accessIcon").removeClass('fa-globe');
$("#accessIcon").removeClass('fa-group');
$("#accessIcon").addClass('fa-eye');
$('#access_input').val(accessId);
} else {
alert("inget alternativ valt! = " + accessId);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<!-- Start inputs -->
<input type="text" id="access_input" value="">
<br>
<div class="btn-group">
<button type="button" class="btn btn-default"><i id="accessIcon" class="fa "> </i> <span id="access">Action</span>
</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu">
<li><i class="fa fa-globe"></i> Alla
</li>
<li><i class="fa fa-group"></i> Vänner
</li>
<li><i class="fa fa-eye"></i> Privat
</li>
</ul>
</div>
Add to each links with class 'access' data attributes first for icon class name and second for title. Example for first link:
<a href="javascript:void(0);" class="access" id="0" data-icon="globe" data-title="Alla">
And your onclick can be simplified to:
$(".access").click(function(e) {
$("#access").html($(this).data('title'));
$("#accessIcon").removeClass();
$("#accessIcon").addClass('fa fa-' + $(this).data('icon'));
$('#access_input').val($(this).attr('id'));
});
Well, for starters, I would extract the UI details that are buried deep in your conditions, so that you may use variables instead:
var accessTypes = [
{ title: 'Alla', icon: 'fa-globe' },
{ title: 'Vänner', icon: 'fa-group' },
{ title: 'Privat', icon: 'fa-eye' }
];
Then you could simply do:
$(".access").click(function(e) {
var accessId = $(this).attr('id');
var access = accessTypes[accessId];
$("#access").html(' ' + access.title);
$("#accessIcon").attr('class', 'fa ' + access.icon);
$('#access_input').val(accessId);
});
Note that this works only because the id of your buttons are matching the array index in accessTypes. This solution will break down once you add a second set of buttons for something else.
I would suggest that you move away from relying on id to a data attribute for this purpose, and I would also use string identifiers, although doing just either one of them would be sufficient to solve the problem.
<a href="javascript:void(0);" class="access" data-id="all"> <!-- etc -->
You would then use:
var accessTypes = {
all: { title: 'Alla', icon: 'fa-globe' },
friends: { title: 'Vänner', icon: 'fa-group' },
'private': { title: 'Privat', icon: 'fa-eye' }
};
And...
$(".access").click(function(e) {
var accessId = $(this).data('id');
var access = accessTypes[accessId];
...
});
Related
I am trying to change the icon from chevron-down to chevron-up when clicked. Currently, it shows "Categories" and "Hide" when clicked. I would like to have it say "Categories" the whole time. Is that possible?
Here is the code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<h1 onclick="arata_ascunde(this);" class="btn btn-info " id="show_hide_bt">
<i class="fa fa-chevron-down"></i> Categories
</h1>
<div id="showhide" style="display:none;">
<ul>
<li>Hello World
</li>
</ul>
</div>
JS
function arata_ascunde(h1) {
var x = $('#showhide');
$(h1).find('i').remove();
if ($(h1).text().trim() == 'Categories') {
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).prepend('Hide ');
x.fadeIn();
}
else {
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).prepend('Categories ');
x.fadeOut();
}
}
CodePen: https://codepen.io/chadwicked123/pen/porRoOq
Your "if condition" is on something that can't be detected if it will be the same in all conditions. So it's better to change your condition to something more specific, like the tag's class. like this :
function arata_ascunde(h1) {
var x = $('#showhide');
if ($(h1).find('i').hasClass('fa-chevron-down')) {
$(h1).find('i').remove();
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).append(' Categories');
x.fadeIn();
} else {
$(h1).find('i').remove();
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).append(' Categories');
x.fadeOut();
}
}
I changed a few things to make your result more beautiful. This code still can be improved (I'm not a front-end developer).
I used basic javascript and some logic to change the HTML based on a class
Here's the codepen for it - Link
Here's the edited JS file :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<h1 onclick="arata_ascunde(this);" class="btn btn-info " id="show_hide_bt">
Categories<i class="fa fa-chevron-down"></i>
</h1>
<div id="showhide" style="display:none;">
<ul>
<li>Hello World
</li>
</ul>
</div>
and the edited JS file
function arata_ascunde(h1) {
var x = $('#showhide');
$(h1).find('i').remove();
if (document.querySelector("h1").classList.contains("down")) {
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).prepend('Categories ');
document.querySelector("h1").classList.remove("down")
x.fadeIn();
}
else {
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).prepend('Categories ');
document.querySelector("h1").classList.add("down")
x.fadeOut();
}
}
TL;DR: IntelliJ confirms to different scripts are identical, but they produce different results when ran in the browser (using IntelliJ with Tomcat). Exact details below.
I am creating a web project using Spring MVC that allows me to play chess. I am using the chess.js library and the chessboard.js library.
According to the chess.js library README, it has a methodpgn() that returns the moves of the game as a string. You can optionally pass in a JSON to set a max_length and a newline character so that there is a new line character after black moves. For example game.pgn({ max_width: 5, newline_char: '<br />' }).
Here's my problem. I made a script called initgame.js that instantiates a chess game using the libraries and attempted to use the example above so that the moves printed out would be formatted to print a new line after each turn.
It wasn't working as I had hoped. So I created another script test_game.js to experiment and when I got the behavior I wanted I copy and pasted the contents of test_game.js into initgame.js. Changed the <script> tag point to initgame.js again and it was ignoring the line breaks again. Used IntelliJ to compare the files and IntelliJ confirms that the files are indeed identical.
Now I am just dumbfounded. I tried rebuilding the project, cleaning the Artifacts, cleaning Maven. Nothing. I even closed out of IntelliJ and restarted. When I run the program with test_game.js it works as desired. When I run it with initgame.js it ignores the line breaks.
As a potential hint, this doesn't happen when I use Visual Studio and load it into the browser as an .html instead of a .jsp Any insight is appreciated! Code and screen shots of output are below as well as a screen shot IntelliJ comparing the files.
initgame.js
// NOTE: this example uses the chess.js library:
// https://github.com/jhlywa/chess.js
var board = null;
const game = new Chess()
var $status = $('#status');
var $fen = $('#fen');
var $pgn = $('#pgn');
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false;
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
// illegal move
if (move === null) return 'snapback';
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status);
$fen.html(game.fen());
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' }))
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = Chessboard('myBoard', config);
updateStatus();
test_game.js
// NOTE: this example uses the chess.js library:
// https://github.com/jhlywa/chess.js
var board = null;
const game = new Chess()
var $status = $('#status');
var $fen = $('#fen');
var $pgn = $('#pgn');
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false;
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
// illegal move
if (move === null) return 'snapback';
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status);
$fen.html(game.fen());
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' }))
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = Chessboard('myBoard', config);
updateStatus();
.jsp page
<!doctype html>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet"
href="${pageContext.request.contextPath}/static/javascript/chessboardjs/css/chessboard-1.0.0.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css">
<title>Hello, world!</title>
</head>
<body>
<main>
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h1>Hello World</h1>
Login
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
<i class="fas fa-chess-queen"></i>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<!-- Replace with Spring security Login form -->
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="container">
<div class="row justify-content-center mx-1 my-3">
<div id="myBoard" class="col-6"></div>
<div class="card bg-light col-3">
<div class="card-header">Header</div>
<div class="card-body">
<h5 class="card-title">PGN</h5>
<p class="card-text">Here are the moves of the game as printed by test_game.js</p>
<div class="card-text" id="pgn"></div>
</div>
<button type="button" class="btn btn-primary m-3">Reset Game</button>
</div>
</div>
<div class="row justify-content-center">
<label>Status:</label>
<div id="status"></div>
<label>FEN:</label>
<div id="fen"></div>
<!--
<label>PGN:</label>
<div id="pgn"></div> -->
</div>
</div>
</div>
</main>
<%-- jquery --%>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<script src="${pageContext.request.contextPath}/static/javascript/chessboardjs/js/chessboard-1.0.0.min.js"></script>
<script src="${pageContext.request.contextPath}/static/javascript/node_modules/chess.js/chess.js"></script>
<script src="${pageContext.request.contextPath}/static/javascript/test_game.js"></script>
</body>
</html>
With initgame.js
With test_game.js
The results of the IntelliJ compare function
try this : replace
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' c}))
by
var pgnn = game.pgn({ max_width: 5, newline_char: '<br />' })
pgnn = pgnn + " </br>"
$pgn.html(pgnn)
i'm not sure that it gonna work but i think
This question already has answers here:
How to add a list item to an existing unordered list
(14 answers)
Closed 3 years ago.
Trying to load dropdown dynamically to bootstrap dropdown using Jquery , Any idea if there is any issue with below code ?
main.html
<div class="form-group">
<div class="row">
<div class="col-md-6" class="form-control">
<div class="btn-group dropright">
<button type="button" class="btn btn-secondary btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Clients
</button>
<div class="dropdown-menu">
<ul class="dropdown-menu" id="projectSelectorDropdown"></ul>
</div>
</div>
</div>
</div>
main.js
(function dropdDOwndata(){
var data = [{
id: 1,
name: "Voyage"
},
{
id: 2,
name: "SDK"
},
]
$('.dropdown-menu a').click(function () {
$('#projectSelectorDropdown').val(data);
});
}());
You need to create list items for each data element in your array. Something like this should work:
$(function() {
var data = [
{
id: 1,
name: "Voyage"
},
{
id: 2,
name: "SDK"
}
];
$("#projectSelectorDropdown")
.empty()
.append(
data.map(d => `<li><a data-id=${d.id} href='#'>${d.name}</a></li>`)
);
$(".dropdown-menu a").click(function(e) {
console.log(e);
});
});
See:
https://codepen.io/tyschroed/pen/WNNNaoo?editors=0010
First, you need to listen to Bootstrap show.bs.dropdown event rather than click, which is prevented I suppose by data-toggle api. (See this)
Then, you need to loop over you data, and build a relevant HTML to insert into the empty -existing- dropdown menu.
Here a simple, perfectable, solution I wrote (to also train myself).
(function dropdDOwndata(document) {
var data = [{
id: 1,
name: "Voyage"
},
{
id: 2,
name: "SDK"
},
]
$(document).on('show.bs.dropdown', function(event) {
let $dropdown = $(event.target).find('.dropdown-menu');
for (var i = 0; i < data.length; i++) {
let $link = $('<A>').text(data[i].name + ' (' + data[i].id + ')');
let $li = $('<LI>').append($link);
$dropdown.append($li);
};
});
}(document));
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group">
<div class="row">
<div class="col-md-6" class="form-control">
<div class="btn-group dropright">
<button type="button" class="btn btn-secondary btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Clients
</button>
<div class="dropdown-menu">
<ul class="dropdown-menu" id="projectSelectorDropdown"></ul>
</div>
</div>
</div>
</div>
</div>
I have nested list item of <li> structured as below. What I am trying to do is to edit each item text from pop up modal and reflect change after I clicked on button Save.
However, the first list item I edited is working well, but from the second time onward, it does not work as expected.
$(document).ready(function() {
$('.modal').modal(); // modal
var child;
$('body').on('click', '.fa-pencil', function(e) {
var text = $(this).closest("li").clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
child = $(this).closest("li").children();
var li_element = $(this).closest('li');
console.log(li_element);
var dataActive = $(this).closest('li').attr('data-act');
var li_icon = li_element.attr('data-icon');
var modal1 = $('#modal1');
var modalBody = modal1.find('.modal-content');
modalBody.find('h4.itemdes').text('');
modalBody.find('.modalBody').html('');
var modalHeader = modalBody.find('h4.itemdes').attr('contenteditable', true).text(text);
dataActive = $(this).closest('li').attr('data-act') == 'Y' ? 'checked="checked"' : '';
ActiveOpt = '<p><label><input type="checkbox" id="active" class="filled-in" ' + dataActive + ' /><span>Active</span></label></p>';
IconOpt = '<p><i class="' + li_icon + '" id="icon_element" aria-hidden="true"></i></p>';
var datahtml = ActiveOpt + IconOpt;
modalBody.find('.modalBody').html(datahtml);
// modalBody.find('.modalBody').append(IconOpt);
$('body').on('click', '.saveChange', function() {
var textarea = $('.itemdes').text();
var appendItem = textarea;
li_element.text('').empty().append(appendItem).append(child);
// $(this).closest("li").text('').empty().append(appendItem).append(child);
ActiveOpt = '';
IconOpt = '';
// li_element = '';
});
// Function to check li data-Acive
$('body').on('change', '#active', function() {
li_element.removeAttr('data-act');
// console.log(li_element.prop('checked'));
if ($(this).prop('checked')) {
li_element.attr('data-act', 'Y');
// li_element.attr('checked','checked');
} else {
li_element.attr('data-act', 'N');
// li_element.removeAttr('checked');
}
})
});
})
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Materialized CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Modal Trigger -->
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<h4 style="width: auto; float: left;"><i class="fa fa-pencil-square-o" aria-hidden="true"> </i></h4>
<h4 class="itemdes">Modal Header</h4>
<div class="modalBody">
<p>A bunch of text</p>
</div>
Save
</div>
</div>
<ol class="example example2">
<li data-formdesc="User" data-act="Y" data-icon="fa fa-heart">
<i class="fa fa-heart"></i>User<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
<li data-formdesc="Cash Withdrawal" data-act="Y" data-icon="">
<i class=""></i>Cash Withdrawal<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
<li data-formdesc="Branch1" data-act="Y" data-icon="fa fa-futbol-o">
<i class="fa fa-futbol-o"></i>Branch1<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol>
<li data-formdesc="Customer Centre" data-act="Y" data-icon="">
<i class=""></i>Customer Centre<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
<li data-formdesc="Customers Detail Listing" data-act="Y" data-icon="">
<i class=""></i>Customers Detail Listing<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
</ol>
</li>
<li data-formdesc="2 two" data-act="Y" data-icon="fa fa-linkedin">
<i class="fa fa-linkedin"></i>2 two<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol>
<li data-formdesc="Cash Withdrawal" data-act="Y" data-icon="">
<i class=""></i>Cash Withdrawal<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
<li data-formdesc="Till to Till Transfer" data-act="Y" data-icon="">
<i class=""></i>Till to Till Transfer<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol>
<li data-formdesc="Disbursement Voucher" data-act="Y" data-icon="">
<i class=""></i>Disbursement Voucher<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
</ol>
</li>
<li data-formdesc="Income Posting" data-act="Y" data-icon="">
<i class=""></i>Income Posting<i class="fa fa-pencil modal-trigger" aria-hidden="true" data-target="modal1"></i>
<ol></ol>
</li>
</ol>
</li>
</ol>
For example, first time I edit list item 'User' to 'Users', after I clicked on save, the item text changed well. But at second time I edit another item, let's say 'Cash Withdrawal' to 'Cash Withdrawaling', after clicked Save, the item I edited change to 'Cash Withdrawaling', but list item 'Users' that I edited previously, also change to 'Cash Withdrawaling' as well.
I did not know what is incorrect with my JavaScript. How can I correct that? Thanks
At every click on .fa-pencil you add again event listeners to .saveChange and #active, using local variables like li_element, which are scoped to the callback function. This means that the second time you edit an item, two callbacks are executed, but the first still uses the previous value for li_element, thus setting the new value to the previous edited element too.
You should declare all the event listeners once, and move all the needed variables to the same level as var child.
This should work
$(document).ready(function() {
$('.modal').modal(); // modal
var child;
var li_element;
$('body').on('click', '.fa-pencil', function(e) {
var text = $(this).closest("li").clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
child = $(this).closest("li").children();
li_element = $(this).closest('li');
console.log(li_element);
var dataActive = $(this).closest('li').attr('data-act');
var li_icon = li_element.attr('data-icon');
var modal1 = $('#modal1');
var modalBody = modal1.find('.modal-content');
modalBody.find('h4.itemdes').text('');
modalBody.find('.modalBody').html('');
var modalHeader = modalBody.find('h4.itemdes').attr('contenteditable', true).text(text);
dataActive = $(this).closest('li').attr('data-act') == 'Y' ? 'checked="checked"' : '';
ActiveOpt = '<p><label><input type="checkbox" id="active" class="filled-in" ' + dataActive + ' /><span>Active</span></label></p>';
IconOpt = '<p><i class="' + li_icon + '" id="icon_element" aria-hidden="true"></i></p>';
var datahtml = ActiveOpt + IconOpt;
modalBody.find('.modalBody').html(datahtml);
// modalBody.find('.modalBody').append(IconOpt);
});
$('body').on('click', '.saveChange', function() {
var textarea = $('.itemdes').text();
var appendItem = textarea;
li_element.text('').empty().append(appendItem).append(child);
// $(this).closest("li").text('').empty().append(appendItem).append(child);
ActiveOpt = '';
IconOpt = '';
// li_element = '';
});
// Function to check li data-Acive
$('body').on('change', '#active', function() {
li_element.removeAttr('data-act');
// console.log(li_element.prop('checked'));
if ($(this).prop('checked')) {
li_element.attr('data-act', 'Y');
// li_element.attr('checked','checked');
} else {
li_element.attr('data-act', 'N');
// li_element.removeAttr('checked');
}
})
})
I'm struggling to create an input field that auto-suggests from a list of strings. I've been trying a few different tutorials and finally looked at a pretty simple example from the official documentation, but for some reason I just can't get anything to work.
HTML for the input box
<div id="searchfield">
<input type="text" id="CollegeNameInput"
class="form-control biginput"
placeholder="Search for your University"
onkeydown="submitCollegeNameForm(event)">
</div>
JavaScript for autocomplete
$("#CollegeNameInput").autocomplete({
lookup: collegeList,
onSelect: function (suggestion) {
alert('you selected '+suggestion.value+' which has data'+suggestion.data);
}
});
I've placed the full html file here and the full javascript file here in case these samples aren't enough. There's a few commented out lines here and there as I've changed a few things around from a tutorial I'd been following.
The idea is that I'd like people to start typing the name of their university and a list of suggestions will pop up from them to select from. For whatever reason I can't seem to get the jquery UI plugin to make any suggestions show up at all. Any suggestions would be greatly appreciated!
In your html page you have only jquery-ui and bootstrap libraries so I'm guessing you are using jquery-ui autocomplete in that case you don't have a lookup option there... you need to pass the option as a source
So
$("#CollegeNameInput").autocomplete({
source: collegeList,
onSelect: function (suggestion) {
//var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol:</strong> ' + suggestion.data;
//$('#outputcontent').html(thehtml);
alert('you selected ' + suggestion.value + ' which has data' + suggestion.data);
}
});
Also looks like you have forgot to include the jQuery UI css file, include that too
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/redmond/jquery-ui.css">
Demo
/**
* Created by Jake on 1/16/2015.
*/
window.onload = function() {
//$("CollegeNameInput").style = 'background-color: red;';
}
//setup college list
var collegeList = [{
value: 'Purdue University',
data: 'purdue'
}, {
value: 'Cal Poly Slo',
data: 'calpolyslo'
}, {
value: 'Sample College',
data: 'samplecollege'
}, ]
function submitCollegeNameForm(event) {
if (event.keyCode == 13 || event.which == 13) {
messageBox = getCollegeNameElement();
messageString = messageBox.value;
sessionStorage.setItem('uniName', messageString);
window.location.href = "classPage.html";
}
}
function getCollegeNameElement() {
var panel = document.getElementById("CollegeNameInput");
return panel;
}
//// setup autocomplete function pulling from currencies[] array
$("#CollegeNameInput").autocomplete({
source: collegeList,
onSelect: function(suggestion) {
//var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol:</strong> ' + suggestion.data;
//$('#outputcontent').html(thehtml);
alert('you selected ' + suggestion.value + ' which has data' + suggestion.data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--jQuery UI-->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<!--Bootstrap-->
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.js"></script>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">ClassChat</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home
</li>
<li>About
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="jumbotron" style="margin-top: 100px">
<h1>Jump into ClassChat!</h1>
<div class="row">
<div class="col-md-3">
<p>Enter your University:</p>
</div>
<div class="col-md-5">
<div id="searchfield">
<input type="text" id="CollegeNameInput" class="form-control biginput" placeholder="Search for your University" onkeydown="submitCollegeNameForm(event)">
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
</div>
<!-- /.container -->