How to create input suggestions with JQuery - javascript

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 -->

Related

When I load two identical (confirmed by IntelliJ) JS scripts into my web app one produces different results than the other

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

How to load Header HTML file in each page

I have an HTML Header page which is consist of nav bar which is loaded dynamically and i have several other pages also.
i want to include the Navbar (Header.html) in each of my page to reduce the code i am doing the right thing like this using J Query .load function and it is working fine also
the issue i a facing is my i have Bootstrap 4 navbar and in other pages i have an form by clicking on the submit of the form i am rendering an HTML table which has an export button also,and i am using table2export cdn to export table into the excel
so when i load my header with the table it shows an error Uncaught TypeError: $(...).table2excel is not a function when i remove and writing the navbar code in each page rather than loading it into each page then it is working fine
HTML
<div id="header"></div>
<h4 class="text-center">Date wise Outlet wise Sales Summary :</h4>
<form id="formId" method="get">
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()" />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()"/>
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div><br>
</div>
<div>
<br>
<button id="button" class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
<div class="loader"></div>
<div class="overlay"></div>
<div id="tbl"></div>
<button id="export-btn">
<i class="fa fa-file-excel-o" aria-hidden="true"></i> Export
</button>
<div style="padding-bottom: 100px">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gijgo#1.9.6/js/gijgo.min.js"
type="text/javascript"></script>
<script src="https://rawgit.com/unconditional/jquery able2excel/master/src/jquery.table2excel.js"></script> //using this one to export
<script type="text/javascript" src="JS/Datewiseolwise.js"></script> // this is for table rendering js code
<script type="text/javascript" src="JS/headerfooter.js"></script> //this is my header javascript file
<script type="text/javascript" src="JS/Date.js"></script>
<script type="text/javascript" src="JS/Outletlist.js"></script>
**javascript for loading the header in each page**
$(document).ready(function() {
$("#header").load("Header.html");
});
and here is my navbar code
<nav
class="navbar navbar-expand-sm bg-dark navbar-dark navbar fixed-top">
<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 id="navbarId" class="navbar-nav mr-auto">
</ul>
</div>
<a class="navbar-brand" href="Header.html">HOME</a>
</nav>
<div style="padding: 30px"></div>
<div class="col-sm-12">
<div class="name"></div>
<hr style="border: solid 1px black">
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="JS/Header.js">
</script>
i thing there is problem in placing thecdn of table2excel at right place but i have tried hard its not working and throwing same error
anyone out there please check what i am missing
header5.js script
$(document).ready(function() {
$.ajax({
url : "HeaderServlet",
method : "GET",
success : function(data) {
for (var item in data) {
var _menu = "";
var _submenuData = data[item];
if(_submenuData.length > 0) {
var _submenu = "";
for(var i = 0; i < _submenuData.length; i++) {
_submenu += "<a class='dropdown-item' href='" + _submenuData[i]["link"] + "'>" + _submenuData[i]["type"] + "</a>";
}
_menu = "<li class='nav-item dropdown'>"
+ "<a class='nav-link dropdown-toggle' href='' id='navbardrop' data-toggle='dropdown'> " + item + " </a>"
+ "<div id='drop' class='dropdown-menu'>"
+ _submenu
+ "</div>"
+ "</li>";
}
$("#navbarId").append(_menu);
}
var _logout = "<li class='nav-item'>" +
"<a class='nav-link' href='Logout'> Logout </a>" +
"</li>";
$("#navbarId").append(_logout);
}
});
$.ajax({
url : "LoginServlet",
method : "GET",
success : function(data) {
$(".name").text("Welcome '" +data[0].Name + "'-" +data[0].Companyname)
}
});
});
Hello first of open console and write simple "table2excel" check library load or not ?
If library is loaded then use like
$("#yourHtmTable").table2excel({
exclude: ".excludeThisClass",
name: "Worksheet Name",
filename: "SomeFile" //do not include extension
});
CDN

Boot strap button group change jQuery

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];
...
});

AngularJS : call a Controller method with ng-click [duplicate]

I have a simple loop with ng-repeat like this:
<li ng-repeat='task in tasks'>
<p> {{task.name}}
<button ng-click="removeTask({{task.id}})">remove</button>
</li>
There is a function in the controller $scope.removeTask(taskID).
As far as I know Angular will first render the view and replace interpolated {{task.id}} with a number, and then, on click event, will evaluate ng-click string.
In this case ng-click gets totally what is expected, ie: ng-click="removeTask(5)". However... it's not doing anything.
Of course I can write a code to get task.id from the $tasks array or even the DOM, but this does not seem like the Angular way.
So, how can one add dynamic content to ng-click directive inside a ng-repeat loop?
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
http://jsfiddle.net/JSWorld/Hp4W7/34/
One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:
<button ng-click="removeTask(1234)">remove</button>
I saw:
<button ng-click="removeTask(task.id)">remove</button>
However, the latter works!
This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.
Further, if you wanted to pass the task object itself, you can like:
<button ng-click="removeTask(task)">remove</button>
Also worth noting, for people who find this in their searches, is this...
<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
<div class="bb-button-label">{{ button.label }}</div>
<div class="bb-button-description">{{ button.description }}</div>
</div>
Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);
app.controller('usersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {
console.log(response.data)
$scope.users = response.data;
$scope.setKey = function (userId){
alert(userId)
if(localStorage){
localStorage.setItem("userId", userId)
} else {
alert("No support of localStorage")
return
}
}//function closed
});
});
#header{
color: green;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>HyperCrud</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<!-- NAVBAR STARTS -->
<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="#">HyperCrud</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li class="dropdown">
Apps<span class="caret"></span>
<ul class="dropdown-menu">
<li>qAlarm »</li>
<li>YtEdit »</li>
<li>GWeather »</li>
<li role="separator" class="divider"></li>
<li>WadStore »</li>
<li>chatsAll</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>Register</li>
<li>Services<span class="sr-only">(current)</span></li>
</ul>
</div>
</div>
</nav>
<!--NAVBAR ENDS-->
<br>
<br>
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<center>
<h1 id="header"> Users </h1>
</center>
</div>
</div>
<div class="row" >
<!--ITERATING USERS LIST-->
<div class="col-sm-6 col-md-4" ng-repeat="user in users">
<div class="thumbnail">
<center>
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">
<hr>
</center>
<div class="caption">
<center>
<h3>{{user.name}}</h3>
<p>{{user.email}}</p>
<p>+91 {{user.phone}}</p>
<p>{{user.address.city}}</p>
</center>
</div>
<div class="caption">
DELETE
UPDATE
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a href="/regiser/">
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">
</a>
</div>
</div>
</div>
<!--ROW ENDS-->
</div>
</body>
</html>
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>

How to update a textfield based on other form elements

I'm writing a little database query app.
What i'm trying to do: Each time a checkbox is clicked, i'd like for a query that includes the selected fields to be generated and inserted into the textarea.
The problem: For some reason, with every click, its showing the query from the previous click event, not the current one.
Here's the markup:
<div class="application container" ng-controller="OQB_Controller">
<!-- top headr -->
<nav class="navbar navbar-default navbar-fixed-top navbar-inverse shadow" role="navigation">
<a class="navbar-brand">
Algebraix Database Client
</a>
<ul class="nav navbar-nav navbar-right">
<!--<li>Clear Queries</li>-->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-import"></span> Load Data <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>Default Data</li>
<li>Custom Import</li>
<!-- <li class="divider"></li> -->
</ul>
</li>
<li>
<a href="" class="queries-clear">
<span class="glyphicon glyphicon-remove"></span> Clear Queries
</a>
</li>
</ul>
</nav>
<!-- left column -->
<div class="col-md-4">
<div class="well form-group">
<ul>
<li ng-repeat="option in options">
<input type="checkbox" class="included-{{option.included}}" value="{{option.value}}" ng-click="buildQuery()" ng-model="option.included"> {{option.text}}
</li>
</ul>
</div>
</div>
<!-- right column -->
<div class="col-md-8">
<form role="form" id="sparqlForm" method="POST" action="" class="form howblock">
<div class="form-group">
<!--<label>Query</label>-->
<textarea type="text" name="query" class="form-control" rows="10" placeholder="Write your SPARQL query here">{{query}}</textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit Query" data-loading-text="Running Query..." />
</div>
</form>
</div>
</div>
And in my controller, i am doing the following:
var OQB_Controller = function($scope) {
console.log('OQB_CONTROLLER');
$scope.query = 0;
$scope.options = [
{ text: "checkbox1", value: "xyz123", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
];
$scope.buildQuery = function() {
console.log('click');
var lines = [];
lines.push("SELECT *");
lines.push("WHERE {");
lines.push(" ?s ?p ?o .");
for(var i = 0; i<$scope.options.length; i++) {
var line = $scope.options[i];
console.log( line.value, line.included, i );
if( line.included ) {
lines.push(" OPTIONAL { ?s "+line.value+" ?o } .");
}
}
lines.push("}");
lines.push("LIMIT 10");
var _query = lines.join("\n");
$scope.query = _query;
};
};
To reiterate, every time the build query method is called, the state of the included booleans is from one click event prior. this has the symptoms of the classic javascript problem of the keyup vs keydown and the state of the event... however, i'm not sure if that is what is happening here.
is there a better way to do build the query (than what i'm currently doing) and populate the textarea based on the checked boxes?
use ng-change instead of ng-click because it is more appropriate for this particular desired behavior. See the ng-change documentation below:
The ngChange expression is only evaluated when a change in the input
value causes a new value to be committed to the model.
It will not be evaluated:
if the value returned from the $parsers transformation pipeline has
not changed if the input has continued to be invalid since the model
will stay null if the model is changed programmatically and not by a
change to the input value

Categories

Resources