Classes Not Working in Jquery - javascript

My class pointers will not work once they are clicked.I am trying to create a delete button ,but when I click on the class I need it does not work or do anything.The problem occurs at around line 143 in my code and is label with 'the problem' and right now it just says console.log but not even that will work. The createTable() function is where the class is created in the final td at the bottom of the Javascript if that helps any.Any help is appreciated with this!
var name;
var age;
var sex;
var person;
var flagOne;
var flagTwo;
var flagThree;
var array = [];
var rowIndex;
createTable();
/* Modal Scripts */
$('.left').click(function(){
name = $("#name").val('');
age = $("#age").val('');
sex = $("#sex").val('');
$('.form-row:first-child').css('border','0');
$('.form-row:nth-child(2)').css('border','0');
$('.form-row:nth-child(3)').css('border','0');
if($('td>a.delete').css('opacity') == 1){
$('.modal-wrapper').css('display','none');
}
else {
$('.modal-wrapper').css('display','block');
$('.modal').animate({
opacity:1,
marginTop:'-117px'
},500);
}
});
$('.fa-times').click(function(){
$('.modal-wrapper').css('display','none');
name = $("#name").val('');
age = $("#age").val('');
sex = $("#sex").val('');
$('.modal').animate({
opacity:0,
marginTop:'-250px'
});
});
$('.modal-background').click(function(){
$('.modal-wrapper').css('display','none');
name = $("#name").val('');
age = $("#age").val('');
sex = $("#sex").val('');
$('.modal').animate({
opacity:0,
marginTop:'-250px'
});
});
/* Validation */
$('#button').click(function(){
flagOne = false;
flagTwo = false;
flagThree = false;
name = $("#name").val();
age = $("#age").val();
sex = $("#sex").val();
if(name.match(/^([a-zA-Z]{2,15}\s[a-zA-z]{2,15})/)){
flagOne = true;
}
else {
flagOne = false;
}
if (age < 0 || age > 130 || isNaN(age) || age == '') {
flagTwo = false;
}
else {
flagTwo = true;
}
if (sex == "male" || sex == "Male" || sex == "female" || sex == "Female"){
flagThree = true;
}
else {
flagThree = false;
}
if(flagOne == false || flagTwo == false || flagThree == false){
if(flagOne==false){
$('.form-row:first-child').css('border','3px solid red');
}
else {
$('.form-row:first-child').css('border','0');
$('.form-row:first-child').css('border-bottom','3px solid red');
}
if(flagTwo == false){
$('.form-row:nth-child(2)').css('border-right','3px solid red');
$('.form-row:nth-child(2)').css('border-left','3px solid red');
}
else {
$('.form-row:nth-child(2)').css('border','0');
}
if(flagThree == false){
$('.form-row:nth-child(3)').css('border','3px solid red');
}
else {
$('.form-row:nth-child(3)').css('border','0');
$('.form-row:nth-child(3)').css('border-top','3px solid red');
}
}
else if(flagOne == true && flagTwo == true && flagThree == true) {
$('.modal-wrapper').css('display','none');
$('.modal').animate({
opacity:0,
marginTop:'-250px'
});
storeObject();
}
});
/* Delete Button */
$('.right').click(function(){
if($('td>a.delete').css('opacity') == 1){
$('td>a.delete').css('opacity','0');
}
else if($('td>a.delete').css('opacity') == 0){
$('td>a.delete').css('opacity','1');
}
});
/* THE PROBLEM */
$('.delete').click(function(){
console.log("heelo");
});
/* Array Creation */
function storeObject() {
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
person = new Person(name,age,sex);
array.push(person);
testArray();
}
/* Test Array */
function testArray() {
if(array.length == 8){
createTable();
alert('Table Limit Reached!');
}
else if (array.length > 8){
array.pop();
alert('Too Many Rows!');
}
else {
createTable();
}
}
/* Table Creation */
function createTable() {
var table = "<table><tr><td>Name<span class='special'>▲</span></td><td>Age<span class='special'>▲</span></td><td>Sex</td></tr>";
for(var i=0;i < array.length;i++){
if (array.length > 0){
table += "<tr><td>" + array[i].name + "</td>";
table += "<td>" + array[i].age + "</td>";
table += "<td>" + array[i].sex + "<a class='delete'><i class='fa fa-trash-o' aria-hidden='true'></i></a></td></tr>";
}
}
table += "</table>";
document.getElementById("tablePrint").innerHTML = table;
}

Delegate events like below. This is needed since when the events are registered the HTML is not in DOM yet.
$(document).on("click", ".delete", function(){
console.log("heelo");
});
and similarly for other events as well.

use .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.
$( ".left" ).on( "click", function() {
console.log( $( this ).text() );
});
OR
$(document).on( "click",".left" function() {
console.log( $( this ).text() );
});
more detail :http://api.jquery.com/on/

Related

java script load issue with ng build --prod

my javascript file for multiple email(multiple_emails.js plugin) is working fine with ng serve my code :
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top",
invalid:"Invalid Email Id"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
var to_id = this.id;
var orig_id=to_id;
console.log(to_id);
var arr = to_id.split('_');
to_id = arr[1];
console.log("to_id",to_id);
setTimeout(function(){
console.log($('.licls'+to_id).length);
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
},200);
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" id=ul_'+to_id+' />'); // create html elements - list of email addresses as unordered list
console.log($(this).val());
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email licls'+to_id+'"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" id= input_'+to_id+' />').on('keyup', function(e) { // input
console.log($(this).attr('id'));
$(this).removeClass('multiple_emails-error');
$('#'+orig_id).parent().find("label").remove();
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
$('#'+orig_id).parent().find("label").remove();
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container contnr_'+to_id+'" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
console.log(t.attr('id'));
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
var res_arr=JSON.parse($orig.val().toLowerCase().split(','))
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && res_arr.indexOf(arr[i].toLowerCase()) != -1) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if ( pattern.test(arr[i]) == true && res_arr.indexOf(arr[i].toLowerCase()) == -1) {
if($('#ulcls'+t.attr('id')).length < 4) {
$list.append($('<li class="multiple_emails-email licls'+to_id+'"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0) {
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
t.after('<label for='+orig_id+' style="color:#cc5965;">'+settings.invalid+'</label>');
}else {
$('#'+orig_id).parent().find("label").remove();
t.val("");
}
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
$(document).ready(function(){
$('#input_'+to_id).on("cut copy paste",function(e) {
e.preventDefault();
});
});
return $(this).hide();
});
};
})(jQuery);
But when i compile it with ng build --prod it's gives TypeError: $(...).multiple_emails is not a function , if it's not working correctly any other tool to convert from JavaScript to typescript ?
i had convert js into typesript using online compiler but nothing happened.
solved!!!!
finally i figure out the problem. it is in angular-cli.json.when i place my multiple_email.js after jquery-3.1.1.min.js,jquery.validate.min.js then it works like charm...!!! #rajesh thanks

Replace text in an <li> tag in an ul

I'm new to web programming, and I'm trying to complete a simple guessing game project.
Right now I'm stuck because I'm trying to update an unordered list with the player's past guesses, but the page does not update.
Here is my jQuery code:
$(document).ready(function() {
game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else { //this is the relevant portion
guessNum = (game.pastGuesses.length - 1).toString();
$('#' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
Here is the unordered list's html:
<div id='guesses'>
<!-- unordered list of guesses -->
<ul id='past-guesses' class="list-inline center">
<li id='0' class="guess list-group-item ">-</li>
<li id='1'class="guess list-group-item">-</li>
<li id='2' class="guess list-group-item">-</li>
<li id='3' class="guess list-group-item">-</li>
<li id='4' class="guess list-group-item">-</li>
</ul>
</div>
I have also tried not using the identifiers in the html, and instead selecting the li elements this way:
var idStr = "#past-guesses:eq(" + guessNum + ")"
$(idStr).text(game.playersGuess.toString());
In either case, the page does not update with the new values in the unordered list displayed. What am I doing wrong?
EDIT
In response to the request in comments, here's my entire JS file (now slightly edited because I was experimenting with changing the list id's to not begin with a number):
function generateWinningNumber() {
num = Math.random()
if (num === 0) {
return 1;
} else {
roundNum = Math.floor(num*100);
return roundNum + 1;
}
}
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Game(){
this.winningNumber = generateWinningNumber();
this.playersGuess = null;
this.pastGuesses = [];
}
Game.prototype.difference = function() {
return Math.abs(this.playersGuess - this.winningNumber);
}
Game.prototype.isLower = function() {
if (this.playersGuess < this.winningNumber) {
return true;
} else {
return false;
}
}
Game.prototype.checkGuess = function() {
if (this.playersGuess === this.winningNumber) {
return "You Win!";
}
if (this.pastGuesses.indexOf(this.playersGuess) > -1) {
return "You have already guessed that number.";
}
this.pastGuesses.push(this.playersGuess);
if (this.pastGuesses.length >= 5) {
return "You Lose.";
} else if (this.difference() < 10) {
return "You're burning up!";
} else if (this.difference() < 25) {
return "You're lukewarm.";
} else if (this.difference() < 50) {
return "You're a bit chilly.";
} else {
return "You're ice cold!";
}
}
Game.prototype.playersGuessSubmission = function(num) {
if (num < 1 || num > 100 || typeof num != 'number') {
throw "That is an invalid guess."
} else {
this.playersGuess = num;
return this.checkGuess();
}
}
Game.prototype.provideHint = function() {
return shuffle([generateWinningNumber(), generateWinningNumber(), this.winningNumber]);
}
newGame = function() {
game = new Game;
return game;
}
$(document).ready(function() {
var game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else {
guessNum = (game.pastGuesses.length - 1).toString();
$('#l' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
});
You need to escape the CSS selector.
try to replace this line:
$('#' + guessNum).text(guessNum);
with this:
var selector = "#\\" + guessNum.toString().charCodeAt(0).toString(16) + " " + guessNum.toString().substr(1);
$(selector).text(guessNum);
you can read more at:
https://www.w3.org/International/questions/qa-escapes

Add keydown (keyboard arrow up/down) support for AJAX Live Search PHP

Thanks in advance for your attention,
I'm using the W3 PHP AJAX Live Search Example and it's already integrated on this site. It's just about perfect. I wish to use arrows on keyboard, up (or left) and down (or right), to focus results inside of <div id="livesearch">. Than, on focus press Enter ⏎ key to load.
In HTML head :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#livesearch {
min-height: 155px;
}
#livesearch a:hover {
text-decoration: none;
background-color: rgba(0,0,0,0.05);
}
#livesearch a {
text-transform: capitalize;
font-size: inherit;
padding: 5px 13px;
display: block;
}
#livesearch .selected {
text-decoration: none;
background-color: rgba(0,0,0,0.05);
}
</style>
</head>
HTML Form :
<body>
<form method="post" id="myfrm">
<input type="text" name="search" class="form-control search" placeholder="Just start typing..." autofocus="">
</form>
<div id="livesearch"><div>
</body>
AJAX function :
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
Jquery :
<script>
$(document).ready(function ($) {
$('.search').keyup(function (e) {
var key = e.keyCode;
if (key == 40 || key == 38 || key == 13) {
return false;
}
var str = $('.search').val();
showResult(str);
});
$('#myfrm').on("keydown", ".search", function (e) {
var $listItems = $('#livesearch a');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
if (key != 40 && key != 38 && key != 13)
return;
//$listItems.removeClass('selected');
if (key == 40) // Down key
{
$listItems.removeClass('selected');
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
console.log("Current : "+$current);
}
else if (key == 38) // Up key
{
$listItems.removeClass('selected');
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
else if (key == 13) // Enter key
{
$current = $listItems.filter('.selected');
$current.trigger('click');
return false;
}
$current.addClass('selected');
});
});
</script>
Retrieve data in input search box from livesearch data :
<script>
$(document).ready(function ($) {
$("body").on("click", "#livesearch a", function(e){
e.preventDefault();
var data = $(this).text();
$(".search").val(data);
$('#livesearch').html('');
});
});
</script>
If you want used instead of ajax showResult(str) using ajax+jquery for data retrieve livesearch.php so, you can used bellow code :
<script>
$(document).ready(function ($) {
$('.search').keyup(function (e) {
var key = e.keyCode;
if (key == 40 || key == 38 || key == 13) {
return false;
}
var str = $('.search').val();
$.ajax({
context: this,
url: 'livesearch.php',
type: 'get',
dataType: 'html',
data: {
q: str,
},
beforeSend: function () {
console.log("Loadding...");
}
}).done(function (response) {
$("#livesearch").html(response);
});
});
});
</script>
document.getElementById("yourtextfield").addEventListener("keyup",function(event){
var livesearchelem = document.getElementById("livesearch");
var childrens = livesearchelem.getElementsByTagName("a"); //Get only hyperlinks
var key = event.keyCode;
var selected = this.selectedResultNumber;
if (key == 38){ //Arrow up
if (childrens.length === 0){ return; }
if (!selected){ //If 'selectedResultNumber' is undefined
childrens[childrens.length - 1].style.backgroundColor = 'blue';
childrens[childrens.length - 1].style.color = 'white';
//Store the selected number into this element
this.selectedResultNumber = childrens.length - 1;
}
else if (selected > 1){
//Restore the previous selected element's style
childrens[selected - 1].style.backgroundColor = 'white';
childrens[selected - 1].style.color = 'black';
//Set the new selected element's style
childrens[selected - 2].style.backgroundColor = 'blue';
childrens[selected - 2].style.color = 'white';
//Decrease the selected number by 1
this.selectedResultNumber--;
}
}
else if (key == 40){ //Arrow down
if (childrens.length === 0){ return; }
if (!selected){ //If 'selectedResultNumber' is undefined
childrens[0].style.backgroundColor = 'blue';
childrens[0].style.color = 'white';
//Store the selected number into this element
this.selectedResultNumber = 1;
}
else if (selected < childrens.length){
//Restore the previous selected element's style
childrens[selected - 1].style.backgroundColor = 'white';
childrens[selected - 1].style.color = 'black';
//Set the new selected element's style
childrens[selected].style.backgroundColor = 'blue';
childrens[selected].style.color = 'white';
//Increase the selected number by 1
this.selectedResultNumber++;
}
}
else if (key == 13){ //Enter key
if (childrens.length === 0){ return; }
//Trigger click event on the selected element
childrens[selected - 1].click();
}
else{ //Searching in progress
delete this.selectedResultNumber;
//Your search function goes here
}
});

Autocomplete cities similar to kayak.com from Postgresql with PHP and JS

I would like to have a input where, when the user type in anything all the cities available appear to him. Something like the functionality in kayak.com
So if the user type in the letter M, all the cities starting with M will show like in the picture below.
So I have the following code that works but only for the options provided under var choices:
<form onsubmit="$('#hero-demo').blur();return false;" class="pure-form" style="border-top: 1px solid #eee;border-bottom:1px solid #eee;background:#fafafa;margin:30px 0;padding:20px 10px;text-align:center">
<input id="hero-demo" autofocus type="text" name="q" placeholder="Programming languages ..." style="width:100%;max-width:600px;outline:0">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="jquery.auto-complete.js"></script>
<script>
$(function(){
$('#hero-demo').autoComplete({
minChars: 1,
source: function(term, suggest){
term = term.toLowerCase();
var choices = ['Birmingham', 'Dallas', 'Houston','New York', 'San Francisco'];
var suggestions = [];
for (i=0;i<choices.length;i++)
if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
suggest(suggestions);
}
});
});
</script>
Then I have this PHP code to pull all my cities from my postgresql database:
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT * FROM cities";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
//This is just to print out all the cities I have in my database with their countries
while($myrow = pg_fetch_assoc($result)) {
$city = $myrow[city];
$country = $myrow[country];
echo $city;
echo $country;
echo '<br>';
}
?>
I have 2 questions:
How can I do to substitute the values in var choices for the values retrieve from my postgreqsl database with $query = "SELECT * FROM cities";?
How can I do to have also added the country so if there are two cities named the same in different countries or States all show up: Example:
If I type in Tole --> I'll see:
Toledo, Spain
Toledo, OH
Toledo, OR
Toledo, IA
Toledo, WA
Toledo, IL
Thank you so much
Here is the code from jquery.auto-complete.js:
(function($){
$.fn.autoComplete = function(options){
var o = $.extend({}, $.fn.autoComplete.defaults, options);
// public methods
if (typeof options == 'string') {
this.each(function(){
var that = $(this);
if (options == 'destroy') {
$(window).off('resize.autocomplete', that.updateSC);
that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
if (that.data('autocomplete'))
that.attr('autocomplete', that.data('autocomplete'));
else
that.removeAttr('autocomplete');
$(that.data('sc')).remove();
that.removeData('sc').removeData('autocomplete');
}
});
return this;
}
return this.each(function(){
var that = $(this);
// sc = 'suggestions container'
that.sc = $('<div class="autocomplete-suggestions '+o.menuClass+'"></div>');
that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
that.attr('autocomplete', 'off');
that.cache = {};
that.last_val = '';
that.updateSC = function(resize, next){
that.sc.css({
top: that.offset().top + that.outerHeight(),
left: that.offset().left,
width: that.outerWidth()
});
if (!resize) {
that.sc.show();
if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
if (that.sc.suggestionHeight)
if (!next) that.sc.scrollTop(0);
else {
var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
else if (selTop < 0)
that.sc.scrollTop(selTop + scrTop);
}
}
}
$(window).on('resize.autocomplete', that.updateSC);
that.sc.appendTo('body');
that.sc.on('mouseleave', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
});
that.sc.on('mouseenter', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
$(this).addClass('selected');
});
that.sc.on('mousedown click', '.autocomplete-suggestion', function (e){
var item = $(this), v = item.data('val');
if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
that.val(v);
o.onSelect(e, v, item);
that.sc.hide();
}
return false;
});
that.on('blur.autocomplete', function(){
try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover
if (!over_sb) {
that.last_val = that.val();
that.sc.hide();
setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input
} else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20);
});
if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); });
function suggest(data){
var val = that.val();
that.cache[val] = data;
if (data.length && val.length >= o.minChars) {
var s = '';
for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
that.sc.html(s);
that.updateSC(0);
}
else
that.sc.hide();
}
that.on('keydown.autocomplete', function(e){
// down (40), up (38)
if ((e.which == 40 || e.which == 38) && that.sc.html()) {
var next, sel = $('.autocomplete-suggestion.selected', that.sc);
if (!sel.length) {
next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
that.val(next.addClass('selected').data('val'));
} else {
next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
}
that.updateSC(0, next);
return false;
}
// esc
else if (e.which == 27) that.val(that.last_val).sc.hide();
// enter or tab
else if (e.which == 13 || e.which == 9) {
var sel = $('.autocomplete-suggestion.selected', that.sc);
if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function(){ that.sc.hide(); }, 20); }
}
});
that.on('keyup.autocomplete', function(e){
if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
var val = that.val();
if (val.length >= o.minChars) {
if (val != that.last_val) {
that.last_val = val;
clearTimeout(that.timer);
if (o.cache) {
if (val in that.cache) { suggest(that.cache[val]); return; }
// no requests if previous suggestions were empty
for (var i=1; i<val.length-o.minChars; i++) {
var part = val.slice(0, val.length-i);
if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
}
}
that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
}
} else {
that.last_val = val;
that.sc.hide();
}
}
});
});
}
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
}(jQuery));
I really like this plugin called awesomeplete. Light, easy to use. It is very flexible with how you attach the options.

Checkbox in HTML turns off a function in a .js file

I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.

Categories