AngularJS --> ng-view not loading js - javascript

The code works when the day1.js script is loaded in the index and if a certain snippet from the HTML template is pasted into the file, but it doesn't work when I switch to the page using ng-view with the same code. There is nothing in my day1controller. I'm pretty lost at this point and would appreciate some insight.
I keep getting the error
day1.js:5 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
Here is my index:
<!-- Takes in an input.txt and counts how many times the numbers increase and decrease -->
<!DOCTYPE html>
<html ng-app="adventOfCode">
<head>
<title>Home</title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular-route.min.js"></script>
<meta name="vieport" content="width=device-width initial scale=1" />
</head>
<body>
<header><h2>Website Header</h2></header>
<div class="column">
<div class="links">
Home<br />
Day 1<br />
Day 2<br />
</div>
</div>
<!-- Where the pages change -->
<div ng-view></div>
<!-- Code only works as intended when this div is pasted here -->
<div>
<input type="file" />
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<!-- End of pasted code -->
<footer><h3>Website footer lalalala</h3></footer>
<script>
var app = angular
.module("adventOfCode", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
//inject $locationProvider service
$locationProvider.hashPrefix(""); // add configuration
$routeProvider
.when("/home", {
template: "About Us",
})
.when("/day1", {
templateUrl: "views/day1.html",
controller: "day1Controller",
})
.when("/day2", {
templateUrl: "views/day2.html",
controller: "day2Controller",
});
});
</script>
<!-- Controllers -->
<script src="js/controllers/day1Controller.js"></script>
<script src="js/controllers/day2Controller.js"></script>
<!-- My scripts -->
<script src="js/day1.js"></script>
</body>
</html>
`
Here is the javascript I am trying to run (day1.js):
//selecting the input and textarea elements and saving them to variables
let input = document.querySelector("input");
let textarea = document.querySelector("textarea");
input.addEventListener("change", () => {
//returns an array of File objects
let files = input.files;
if (files.length == 0) return;
//getting the first File object
const file = files[0];
//creating a FileReader
let reader = new FileReader();
reader.onload = (e) => {
var index = 0;
var lastLine = "";
var currentLine = "";
var increased = 0;
var decreased = 0;
var results = [];
const file = e.target.result;
console.log("inside onload");
/**We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable. */
const lines = file.split(/\r\n|\n/);
console.log("split the lines");
/**-------------- Our Workspace -------------- */
lines.forEach((line) => {
if (index === 0) {
lastLine = line;
console.log(line + "-->" + index);
index++;
} else {
currentLine = line;
if (currentLine > lastLine) {
console.log(line + " --> " + index + " :increased");
increased++;
} else if (currentLine < lastLine) {
console.log(line + " --> " + index + " :decreased");
decreased++;
} else {
console.log(line + " --> " + index);
}
index++;
lastLine = currentLine;
}
});
console.log("Number of inputs: " + index);
console.log("How many times the inputs increased: " + increased); //1582 is too low
console.log("How many times the inputs decreased: " + decreased);
document.getElementById("increase").innerHTML =
"How many times the inputs increased: " + increased;
document.getElementById("decrease").innerHTML =
"How many times the inputs decreased: " + decreased;
results = slidingWindow(lines, 3);
document.getElementById("increase_").innerHTML =
"How many times the inputs increased: " + results[0];
document.getElementById("decrease_").innerHTML =
"How many times the inputs decreased: " + results[1];
document.getElementById("Index").innerHTML = "Number of inputs: " + index;
/**We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element. */
textarea.value = lines.join("\n");
console.log("joined the lines");
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
function slidingWindow(linesArray, windowSize) {
if (windowSize < 0 || windowSize > linesArray.length) return null;
let currentSum = 0;
let lastSum = 0;
let increased = 0;
let decreased = 0;
let results = [];
for (let i = 0; i < linesArray.length; i++) {
currentSum += parseInt(linesArray[i]);
if (i >= windowSize - 1) {
if ((lastSum === 0) && (currentSum > lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
} else if (currentSum > lastSum) {
console.log(currentSum + " --> " + i + " :increased");
increased++;
} else if (currentSum < lastSum) {
console.log(currentSum + " --> " + i + " :decreased");
decreased++;
} else if ((currentSum = lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
}
lastSum = currentSum;
currentSum -= linesArray[i - (windowSize - 1)];
}
}
return (results = [increased, decreased]);
}
Here is day1.html, which is what I'm want to use to run day1.js:
<div>
<input type="file">
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<div>
<h3>Increase or Decrease</h3>
<h2 id="increase"></h2>
<h2 id="decrease"></h2>
<h3>Sliding window</h3>
<h2 id="increase_"></h2>
<h2 id="decrease_"></h2>
<h3 id="Index"></h3>
</div>

You have to use container for place your view.ng- view is a directive that works like a placeholder. It creates a placeholder where a corresponding view can be placed based on the configuration.
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="nav">
Home
About
</div>
</div>
</div>
</div>
<div class="container">
<div ng-view=""></div>
</div>

My problem was that I didn't have the Jquery library in my index.html. Without it the scripts aren't executed when loaded by ng-view.

Related

Show javascript function output in html

My JavaScript contains two functions. One function gets a number from the user and returns a string that shows if the number is a prime or not and then store the number and the result in an array.
results = new Array();
i = 0;
function isPrime(num) {
flag = false;
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = true;
break;
}
}
}
return !flag;
}
function getNumberPrime(number) {
condition = (isPrime(number)) ? ('is') : ('is not');
console.log('' + number + ' ' + condition + ' prime');
dict = {}
dict['number'] = number
dict['isPrime'] = isPrime(number);
results.push(dict);
}
function getAll() {
for (i = 0; i < results.length; i++) {
condition = (results[i]['isPrime']) ? ('is') : ('is not');
number = results[i]['number']
console.log('' + number + ' ' + condition + ' prime');
}
}
My HTML has an input and two buttons. One button returns the output of the first function and the second should show the items of array.
<!DOCTYPE html>
<html lang="fa">
<head>
<title>Prime Number</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.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="prime.js"></script>
</head>
<body>
<div class="container">
<h2>Find Prime Numbers</h2>
<form>
<div class="form-group">
<label class="control-label col-sm-2">Numbers:</label>
<div class="col-sm-10">
<input class="form-control" id="inp" name="nums" style="margin-left: -11%">
</div>
</div>
<button type="submit" class="btn btn-default" style=" margin-top: 2%;" onclick="getNumberPrime()">Check</button>
<button type="submit" class="btn btn-default" style="margin-top: 2%;" onclick="document.getElementById('showprime').innerHTML =getAll()">Show Result</button>
<p id="showprime"></p>
</form>
</div>
</body>
</html>
But the first button doesn't work and I don't know how to implement the second button.
Prime numbers must be blue and none primes must be red.
First: Your buttons need to have type="button" to prevent a reload because of the submit.
Your function getNumberPrime() wants a parameter number which you aren't offering in your inline event handler. Therefor you should get the number in that function by selecting the input and getting its value:
let number = document.querySelector('#inp').value;
Your function getAll() doesn't return anything and therefor the result isn't inserted in #showprime. Instead of loging the values to the console you could add them to an output string and return that string after the for loop:
let output = '';
for (i = 0; i < results.length; i++) {
...
output += number + ' ' + condition + ' prime<br>';
}
return output;
If you want the output to be colored you could wrap each result in a paragraph tag and give it a class dependent on the condition. In this case #showprime should be container element like a div. The class would be styled with CSS.
Inside the for loop:
check = (results[i]['isPrime']) ? true : false;
condition = check ? ('is') : ('is not');
...
output += '<p class=' + check + '>' + number + ' ' + condition + ' prime</p>';
In your CSS-file:
.true {
color: blue;
}
.false {
color: red;
}
Last: It's better to devide Javascript and HTML and not to use inline event handlers. Therefor you should change this:
<button ... onclick="getNumberPrime()">Check</button>
<button ... onclick="document.getElementById('showprime').innerHTML = getAll()">Show Result</button>
to this:
<button id="check" ...>Check</button>
<button id="show" ...>Show Result</button>
document.querySelector('#check').addEventListener('click', getNumberPrime);
document.querySelector('#show').addEventListener('click', function() {
document.getElementById('showprime').innerHTML = getAll();
});
Working example:
results = new Array();
i = 0;
function isPrime(num) {
flag = false;
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = true;
break;
}
}
}
return !flag;
}
function getNumberPrime() {
let number = document.querySelector('#inp').value;
condition = (isPrime(number)) ? ('is') : ('is not');
console.log('' + number + ' ' + condition + ' prime');
dict = {}
dict['number'] = number
dict['isPrime'] = isPrime(number);
results.push(dict);
}
function getAll() {
let output = '';
for (i = 0; i < results.length; i++) {
check = (results[i]['isPrime']) ? true : false;
condition = check ? ('is') : ('is not');
number = results[i]['number'];
output += '<p class=' + check + '>' + number + ' ' + condition + ' prime</p>';
}
return output;
}
document.querySelector('#check').addEventListener('click', getNumberPrime);
document.querySelector('#show').addEventListener('click', function() {
document.getElementById('showprime').innerHTML = getAll();
});
.true {
color: blue;
}
.false {
color: red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<h2>Find Prime Numbers</h2>
<form>
<div class="form-group">
<label class="control-label col-sm-2">Numbers:</label>
<div class="col-sm-10">
<input class="form-control" id="inp" name="nums" style="margin-left: -11%">
</div>
</div>
<button id="check" type="button" class="btn btn-default" style=" margin-top: 2%;">Check</button>
<button id="show" type="button" class="btn btn-default" style="margin-top: 2%;">Show Result</button>
<div id="showprime"></div>
</form>
</div>

I've built and app using javascript /firebase and would like to have it return the last 5 searches and make each of them clickable

I've built an app that is working fine. The only problem is that I'm trying to have it display the last 5 searches in my HTML div with the id of recentSearches. I would like each of them to be clickable and return the result they previously returned. I refered to my HTML div toward the bottom as: let recentSearchesDiv = $('#recentSearches')
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase.js"></script>
var config = {
apiKey: "AIzaSyCzaNmYb94HQPR70d6Omy5kP1d0kw5NLkc",
authDomain: "eventtraveler-69f59.firebaseapp.com",
databaseURL: "https://eventtraveler-69f59.firebaseio.com",
projectId: "eventtraveler-69f59",
storageBucket: "eventtraveler-69f59.appspot.com",
messagingSenderId: "73086206077"
};
firebase.initializeApp(config);
var database = firebase.database();
// slider functionality
$(document).ready(function () {
$('.slider').slider({ full_width: true });
});
var $hotelsContainer = $("#hotel-results");
var $eventsContainer = $("#events-results");
// input fields
var $city = $("#location-input");
var $checkInDate = $("#start-date-input");
var $checkOutDate = $("#end-date-input");
var $submit = $("#add-event");
// make global variable so functions can access
var city = "";
var checkin = "";
var checkout = "";
var pleaseWait = "";
// CORS un-blocker for eventful API
jQuery.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
options.url = "https://cors-anywhere.herokuapp.com/" + options.url;
}
});
function getHotels(city) {
// find location code
$.ajax({
url:
"https://apidojo-kayak-v1.p.rapidapi.com/locations/search?where=" + city,
method: "GET",
headers: {
"X-RapidAPI-Host": "apidojo-kayak-v1.p.rapidapi.com",
"X-RapidAPI-Key": "811b0b509bmshf44ab7ab1214e55p19e182jsnc61a98a0c578"
}
}).then(function(response) {
console.log(response);
console.log(response[0].ctid); // MAKE SURE IT'S A CITY
// make sure it's a city (response returns city and airport codes)
$.each(response, function(i, value) {
if (response[i].loctype === "city") {
console.log("this is a city");
console.log(i + ", " + value);
citycode = response[i].ctid;
console.log(citycode);
return false;
}
});
// now that we have the location code, we can use it to find hotels
$.ajax({
url:
"https://apidojo-kayak-v1.p.rapidapi.com/hotels/create-session?rooms=1&citycode=" +
citycode +
"&checkin=" +
checkin +
"&checkout=" +
checkout +
"&adults=1",
method: "GET",
headers: {
"X-RapidAPI-Host": "apidojo-kayak-v1.p.rapidapi.com",
"X-RapidAPI-Key": "811b0b509bmshf44ab7ab1214e55p19e182jsnc61a98a0c578"
}
}).then(function(response) {
console.log("kajak success");
console.log(response);
console.log(response.hotelset);
// reference for hotel list
var hotelListMain = response.hotelset;
var hotelList = response.hotelset;
// only keep 10 results
if (hotelList.length > 10) {
hotelList.length = 10;
}
console.log(hotelList);
// if no results
if (hotelList.length === 0) {
console.log("no results");
var newP = $("<p>").text("No results.");
$hotelsContainer.append(newP);
}
// go through each hotel and show on page
$.each(hotelList, function(i, value) {
console.log("hotel " + i);
// get relevent info
if (response.hotelset[i].brand !== undefined) {
var hotelName = response.hotelset[i].brand;
} else {
var hotelName = response.hotelset[i].name;
}
var hotelAddress = response.hotelset[i].displayaddress;
var hotelRating = response.hotelset[i].ratinglabel;
var hotelStarCount = response.hotelset[i].stars;
var hotelThumbnail =
"https://kayak.com" + response.hotelset[i].thumburl;
// if cheapest provider object is included
console.log("t/f: " + response.hotelset[i].cheapestProvider !== undefined);
if (response.hotelset[i].cheapestProvider !== undefined) {
var cheapestProviderName = response.hotelset[i].cheapestProvider.name;
var bestPrice =
response.hotelset[i].cheapestProvider.displaybaseprice;
var linkToHotel =
"https://kayak.com" + response.hotelset[i].cheapestProvider.url;
} else {
var cheapestProviderName = response.hotelset[i].brand;
var bestPrice = response.hotelset[i].price;
var linkToHotel = "https://kayak.com" + response.hotelset[i].shareURL;
}
//create elements for html
var newTitle = $("<h5>").text(
hotelName + " (via " + cheapestProviderName + ")"
);
var newAddress = $("<p>").text(hotelAddress);
var newPrice = $("<p>").text(bestPrice);
var newRating = $("<p>").text(
hotelRating + ", " + hotelStarCount + " stars"
);
var newImage = $("<img>").attr("src", hotelThumbnail);
var newLink = $("<a>")
.attr("href", linkToHotel)
.text("see hotel");
// img container
var imgContainer = $("<div>")
.addClass("card-image")
.append(newImage);
var content = $("<div>")
.addClass("card-content")
.append(newTitle, newAddress, newPrice, newRating);
var action = $("<div>")
.addClass("card-action")
.append(newLink);
// content container
var allContentContainer = $("<div>")
.addClass("card-stacked")
.append(content, action);
// make parent div for this hotel
var newHotelDiv = $("<div>")
.append(imgContainer, allContentContainer)
.addClass("card horizontal");
// add this hotel's div to the hotel container
$hotelsContainer.append(newHotelDiv);
// remove wait message
pleaseWait.remove();
});
});
});
}
function displayEvent() {
$("#events-results").empty();
var where = $("#location-input")
.val()
.trim();
var start = moment($("#start-date-input").val()).format("YYYYMMDD00");
var end = moment($("#end-date-input").val()).format("YYYYMMDD00");
// search for button name in omdb and show info underneath
var queryURL =
"https://api.eventful.com/json/events/search?" +
"app_key=n69CWBNZRrGZqdMs" +
"&l=" +
where +
"&t=" +
start +
"-" +
end;
console.log(queryURL);
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
var schema = JSON.parse(response);
console.log(schema.events);
console.log(schema.events.event);
// if no results
if (schema.events.event.length === 0) {
console.log("no event results");
var newP = $("<p>").text("No results.");
$eventsContainer.append(newP);
}
for (var i = 0; i < schema.events.event.length; i++) {
total = parseFloat(i) + 1;
//create elements for html
var eventTitle = $("<h5>").text(schema.events.event[i].title);
var eventAddress = $("<p>").text(
schema.events.event[i].venue_address +
", " +
schema.events.event[i].city_name +
", " +
schema.events.event[i].postal_code
);
var eventLink = $("<a>")
.attr("href", schema.events.event[i].url)
.text("see event");
// img container
if (schema.events.event[i].image !== null) {
var eventimage = schema.events.event[i].image.medium.url;
if (eventimage.includes("http")) {
var neweventImage = $("<div>")
.addClass("card-image")
.append("<img src='" + eventimage + "'/>");
} else {
var neweventImage = $("<div>")
.addClass("card-image")
.append("<img src='https:" + eventimage + "'/>");
}
}
// start time
var begins = schema.events.event[i].start_time;
var days = schema.events.event[i].all_day;
if (begins.includes("00:00:00")) {
var date = begins.slice(0, 10);
var startTime = $("<p>").text("Starts on " + date + ". Happening for " + days + " days");
} else {
var date = begins.slice(0, 16);
var startTime = $("<p>").text(begins);
}
//build container
var eventContent = $("<div>")
.addClass("card-content")
.append(eventTitle, eventAddress, startTime);
var eventAction = $("<div>")
.addClass("card-action")
.append(eventLink);
// content container
var eventContentContainer = $("<div>")
.addClass("card-stacked")
.append(eventContent, eventAction);
// make parent div for this event
var newEventDiv = $("<div>")
.append(neweventImage, eventContentContainer)
.addClass("card horizontal");
// add this event's div to the event container
$("#events-results").append(newEventDiv);
}
})
}
$submit.on("click", function (event) {
event.preventDefault();
// clear out current results
$hotelsContainer.empty();
$eventsContainer.empty();
// save their inputted data
city = $city.val().trim();
checkin = $checkInDate.val();
checkout = $checkOutDate.val();
var citycode = "";
// if user filled out all fields
if (city !== "" && checkin !== "" && checkout !== "") {
// show message that results are being generated - so user knows button did submit
if ($(".please-wait").length === 0) {
console.log("results are generating....please wait");
pleaseWait = $("<p>").text("Searching for results...").addClass("please-wait");
$(document.body).append(pleaseWait);
pleaseWait.insertAfter($submit);
}
// get hotel results and display them
//getHotels();
// get event results and display them
//displayEvent();
// construct object literal for firebase
let travelEvent = {
city,
checkin,
checkout
};
// add event to firebase
database.ref().push(travelEvent)
database.ref().limitToLast(5).on("value", snapshot => {
let keys = Object.keys(snapshot.val())
let recentSearchesDiv = $('#recentSearches');
recentSearchesDiv.empty();
for(let i = 0; i < keys.length; i++) {
let val = snapshot.val()[keys[i]]
let city = val.city
let checkin = val.checkin
let checkout = val.checkout
let search = $(`<div><span>City: ${city} </span><span>Check-in: ${checkin} </span><span>Check-out: ${checkout}</span></div>`);
search.addClass('recentSearch')
search.on('click', function(){
})
recentSearchesDiv.append(search)
}
});
// clear inputs
$city.val("");
$checkInDate.val("");
$checkOutDate.val("");
} else {
// show error message
if ($(".required-error").length === 0) {
var required = $("<p>").text("* All fields are required").addClass("required-error");
$("#event-form").prepend(required);
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>EventTraveler</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" type="text/css "href="assets/css/style.css">
</head>
<body>
<div class="container">
<nav>
<!--Creating NavBar-->
<div class="nav-wrapper">
<img src="assets/images/logo2.png" class="brand-logo">
</div>
</nav>
<!-- Slider Images -->
<div id="slider-container">
<div class="slider">
<ul class="slides">
<li>
<img src="assets/images/beach.png">
</li>
<li>
<img src="assets/images/concert.png">
</li>
<li>
<img src="assets/images/mountain.png">
</li>
<li>
<img src="assets/images/attraction.png">
</li>
</ul>
</div>
</div>
<div>
<h1>Search for hotels and events</h1>
<!-- Create the form -->
<form id="event-form">
<label for="location-input" id="location">Enter city and state</label>
<input type="text" id="location-input" /><br />
<label for="start-date-input" id="checkin">Check In</label>
<input type="date" id="start-date-input" /><br />
<label for="end-date-input" id="checkout">Check Out</label>
<input type="date" id="end-date-input" /><br />
<!-- Button triggers new event to be added -->
<input id="add-event" class="btn btn-info" type="submit" value="Search" />
</form>
</div>
<div>
<h4>Recent Searches</h4>
<div id="recentSearches">
</div>
</div>
<div class="banner-div">
<img src="assets/images/banner.jpg" id= "banner">
</div>
<!-- create cards right -->
<div class="row">
<div class="col s6" id = "right">
<h3 class="header">Hotels</h3>
<div id = "hotel-results">
<div class="card horizontal">
<div class="card-image">
<img src="assets/images/hotels.jpg">
</div>
<div class="card-stacked">
<div class="card-content">
<p>Use the search form above to see results</p>
</div>
</div>
</div>
</div>
</div>
<!-- create cards right -->
<div class="col s6" id = "Left">
<h3 class="header">Events</h3>
<div id="events-results">
<div class="card horizontal">
<div class="card-image">
<img src="assets/images/events.jpg">
</div>
<div class="card-stacked">
<div class="card-content">
<p>Use the search form above to see results</p>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class=“page-footer”>
<div class=“footer-copyright”>
<div class=“container”>
© 2019 Los Cinco
</div>
</div>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/2.12.0/moment.min.js"></script>
<script src="assets/javascript/main.js"></script>
</body>
</html>
If I understand it correctly, your only problem is that there are more then 5 Elements displayed? You can set a limit on the results returned.
https://dinosaur-facts.firebaseio.com/yourJson.json?
orderBy="price"&limitToLast=5;
As you can see, you can also sort it by a Property, e.g. Price and then query only a set number of items. It is also possible to specify if it should be ordered ASC oder DESC.

How to make the what happening box like twitter in our site?

I am doing this by taking the cursor position from the content-editable box. When a new tag is created the cursor comes before the tag but it should be after the tag. Also i am not able to merge/split the tag.
Please give some idea how can i do this.
Visit (https://plnkr.co/edit/DSHKEcOnBXi54KyiMpaT?p=preview) !
What i want here, after pressing the enter key for new tag the cursor should be at the end of tag while it is not and also the merging/spliting functionality like the twitter what's happening box.
Thanks in advance.
Now this code is working fr me
$scope.myIndexValue = "5";
$scope.searchTag = function(term) {
var tagList = [];
angular.forEach($rootScope.tags, function(item) {
if (item.name.toUpperCase().indexOf(term.toUpperCase()) >= 0) {
tagList.push(item);
}
});
$scope.tag = tagList;
return $q.when(tagList);
};
$scope.getTagText = function(item) {
// note item.label is sent when the typedText wasn't found
return '<a>#<i>' + (item.name || item.label) + '</i></a> ';
};
$scope.resetDemo = function() {
// finally enter content that will raise a menu after everything is set up
$timeout(function() {
//var html = "Tell us something about this or add a macro like brb, omw, (smile)";
var htmlContent = $element.find('#htmlContent');
var html = "";
if (htmlContent) {
var ngHtmlContent = angular.element(htmlContent);
ngHtmlContent.html(html);
ngHtmlContent.scope().htmlContent = html;
// select right after the #
mentioUtil.selectElement(null, htmlContent, [0], 8);
ngHtmlContent.scope().$apply();
}
}, 0);
};
HTML :
<div class="share_tags fs-12">
<div class="row margin_row">
<div class="col-md-12 no_padding">
<div class="form-group">
<div contenteditable="true" mentio
mentio-typed-term="typedTerm"
mentio-macros="macros"
mentio-require-leading-space="true"
mentio-select-not-found="true"
class="editor tag" placeholder="Tell Us something about This"
mentio-id="'htmlContent'"
id="htmlContent"
ng-model="htmlContent">
</div>
</div>
<mentio-menu
mentio-for="'htmlContent'"
mentio-trigger-char="'#'"
mentio-items="tag"
mentio-template-url="/people-mentions.tpl"
mentio-search="searchTag(term)"
mentio-select="getTagText(item)"
></mentio-menu>
</div>
</div>
<script type="text/ng-template" id="/people-mentions.tpl">
<ul class="list-group user-search">
<li mentio-menu-item="tag" ng-repeat="tag in items" class="list-group-item">
<span ng-bind-html="tag.name | mentioHighlight:typedTerm:'menu-highlighted' | unsafe"></span>
</li>
</ul>
</script>
</div>
Reference link
http://jeff-collins.github.io/ment.io/?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation#/
is working fine for me.
This is not working perfectly but for the time being i am using this code.
In app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $filter, $element) {
var tags;
$scope.allTags = ['Tag1', 'PrivateTag', 'Xtag', 'PublicTag1', 'newTag', 'socialTag', 'cricketTag'];
var replacedTag = '';
var replacedIndex;
var data;
$scope.log = function (name) {
$scope.tags = [];
$('ul').html(' ');
console.log("here", $('ul'))
var data = $('textarea').val();
replacedIndex = data.indexOf(replacedTag)
console.log('test', name, replacedTag, replacedIndex, data);
var replacedData = data.substring(0, replacedIndex - 1) + ' #' + name + data.substr(replacedIndex + replacedTag.length);
$('textarea').val(replacedData);
$('textarea').keyup();
}
f = $scope.log;
$('textarea').on('keyup', function (e) {
function getIndexOf(arr, val) {
var l = arr.length,
k = 0;
for (k = 0; k < l; k = k + 1) {
if (arr[k] === val) {
return k;
}
}
return false;
}
$('ul').html('');
$scope.tags = [];
tags = $(this).val().match(/#\S+/g);
console.log("---tags-", tags)
var a = data = $(this).val();
if (tags && tags.length) {
tags.forEach(function (tag,index) {
var index1 = getIndexOf(tags, tag);
console.log("index----",index, index1,tag)
replacedTag = tag;
$scope.tags = tag ? $filter('filter')($scope.allTags, tag.substr(1)) : [];
if ($scope.tags && $scope.tags.length && (e.keyCode && e.keCode != 32)) {
$scope.tags.forEach(function (tag1, index) {
$('ul').append('<li>' + '<a href="javascript:;" onclick=f("' + tag1 + '");>'
+ tag1 + '</a>' + '</li>')
})
}
else {
$('ul').html(' ');
}
if(index == index1) {
var b = a.substring(0, a.indexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.indexOf(tag) + tag.length);
}
else {
var b = a.substring(0, a.lastIndexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.lastIndexOf(tag) + tag.length);
}
a = b;
$('p').html(b)
})
}
})
});
HTML
<br>
<br>
<p></p>
<textarea rows="2" cols="80"></textarea>
<div>
<ul>
</ul>
</div>
For live demo Visit
https://plnkr.co/edit/SD9eouQa5yrViwxQD6yN?p=preview
i am also looking for the better answer.
I assume you're talking about gathering hash tags from a string of sorts, the snippet below demonstrates how you can build an array of #hashed tags without modifying the cursor position.
It uses a simple regular expression to match tags found in the textarea and then pushes them to an array.
var tags;
$('textarea').on('keyup', function(){
tags = $(this).val().match(/#\S+/g)
$('ul').html('');
tags.forEach(function(tag){
$('ul').append('<li>' + tag + '</li>')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<ul></ul>

Reset Function for dice rolling game

I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }

Start the function again on click

I've created a quiz which takes answer from user, checks it and shows whether the answer is correct or incorrect. There are 8 questions in it. I want to start the quiz again once all these 8 questions are completed. How do I do it ?
This is my code
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<div class="qscore">
<span id="scr"></span>
</div>
<center>
<div class="qstart">start</div>
</center>
<div class="qarea">
<div class="question">father</div>
<div class="canswer">Vater</div>
<textarea class="abox" placeholder="Translate the text to German"></textarea>
</div>
<div class="qarea">
<div class="question">My father is baba</div>
<div class="canswer">Mein Vater ist baba</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Land</div>
<div class="canswer">Land</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">My Mother</div>
<div class="canswer">Meine Mutter</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Brother</div>
<div class="canswer">Bruder</div>
<textarea class="abox" placeholder="Translate the text to German"></textarea>
</div>
<div class="qarea">
<div class="question">City</div>
<div class="canswer">Stadt</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Woman</div>
<div class="canswer">Frau</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Man</div>
<div class="canswer">Mann</div>
<textarea class="abox"></textarea>
</div>
<div class="qsubmit">submit</div>
<div class="qcontinue">continue</div>
<div class="correct">Correct</div>
<div class="incorrect">Incorrect</div>
<div class="qrating"></div>
<div class="startagain">startagain</div>
Jquery
$(document).ready(function () {
//declare variables
var qarea = $(".qarea");
var totalqarea = qarea.length;
var startagain = $(".startagain");
var canswer = $(".canswer")
var qsubmit = $(".qsubmit");
var qcontinue = $(".qcontinue");
var qscore = $(".qscore");
var counter = 0;
//hide unrequired
qcontinue.hide();
qsubmit.hide();
startagain.hide();
$("startagain")
$(".correct,.incorrect").hide();
qsubmit.hide();
$(".qscore,.qrating").hide();
$(".canswer").hide();
qarea.hide();
var qstart = $(".qstart");
//intiate click on start
qstart.click(function () {
$(".correct,.incorrect").hide();
var counter = 0;
$(".abox").val('');
qsubmit.show();
$(".qrating").hide();
qarea.eq(counter).show();
qstart.hide();
var i = 0;
$(".qscore").text("Score:" + i + "/" + totalqarea).show();
//loop(); function loop()
//initate submit
qsubmit.bind("click", function () {
qstart.hide();
var ma = canswer.eq(counter).text();
var mal = ma.replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace("ü", "u").replace("ä", "ä").replace("ö", "o").replace("ß", "ss").replace("Ä", "A").replace("Ö", "O").replace("Ü", "U").toLowerCase();
var masplt = mal.split(" ");
var ua = $("textarea").eq(counter).val();
var ual = ua.replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace("ü", "u").replace("ä", "a").replace("ö", "o").replace("ß", "ss").replace("Ä", "A").replace("Ö", "O").replace("Ü", "U").toLowerCase();
var uasplt = ual.split(" ");
var n = mal.localeCompare(ual);
counter = counter + 1;
qarea.eq(counter - 1).hide();
// checks correct answer and gives score
if (n == 0) {
var praise = ["Well Done !!..You got it right !! ", "Nice....You got it right!! ", "Perfect....You got it right!! "]
var r = Math.round(Math.random());
$(".correct").text(praise[r] + " : The answer is " + ma).show();
i = i + 1;
$(".qscore").text("Score:" + i + "/" + totalqarea).show();
//gives incorrect
} else {
qarea.hide();
$(".incorrect").text("Oops....the correct answer is....");
for (var j = 0; j < masplt.length; j++) {
if (masplt[j] !== uasplt[j]) {
$(".incorrect").append(" <span style='font-size:32px'>" + masplt[j] + "</span>").show();
} else {
$(".incorrect").append(" " + masplt[j]).show();
}
}
//$(".incorrect").text("Oops....the correct answer is " + ma).show();
}
qsubmit.hide();
qcontinue.show();
qcontinue.click(function () {
qarea.eq(counter).show();
$(".correct,.incorrect").hide();
qsubmit.show();
qcontinue.hide();
})
if (totalqarea == counter) {
qcontinue.show();
qcontinue.click(function () {
qsubmit.hide();
qstart.text("start again").show();
if (i < (totalqarea - 6) && i < (totalqarea - 4)) {
$(".qrating").text("Your scored " + i + "/" + totalqarea + ". ...You need some more practice. Try it again.").show();
} else if (i > (totalqarea - 4) && i < (totalqarea - 2)) {
$(".qrating").text("Your scored " + i + "/" + totalqarea + "....Not bad !!").show();
} else {
$(".qrating").html("Your scored " + i + "/" + totalqarea + "....Wünderbar !! Keep it up !!").show();
}
$("#scr").text('');
})
qstart.click(function () {
})
}
})
})
})
Here is the fiddle
http://jsfiddle.net/qFa39/11/
Thanks.
Currently you're declaring 2 different counter variables. The one declared under the "declare variables" comment and the one declared within qstart.click(). To fix your problem replace the line inside qstart.click() (line 31 in the jsfiddle) with:
counter = 0;
No var preceeding it. This way javascript will understand you are refering to the first counter and not creating a new var called counter. Have a read up on scope in javascript for more info.
Although this does reveal another bug with our code where the 'Start Again' button does then not hide properly.

Categories