I have a colour picker on my website. Which works great, However i'm wanting to have multiple for multiple elements to be different colour e.g. one text pink and the bg blue.
This is the code i have have at the moment (which works but changes both boxes) i'm missing an id somewhere but im not sure where.
<div class="row">
<script type="text/javascript">
var hexText="123";
var colorList = [ '000000', '993300', '333300', '003300', '003366', '000066', '333399', '333333',
'660000', 'FF6633', '666633', '336633', '336666', '0066FF', '666699', '666666', 'CC3333', 'FF9933',
'99CC33', '669966', '66CCCC', '3366FF', '663366', '999999', 'CC66FF', 'FFCC33', 'FFFF66', '99FF66'];
var picker = $('#color-picker');
for (var i = 0; i < colorList.length; i++ ) {
picker.append('<li class="color-item" data-hex="' + '#' + colorList[i] + '" style="background-color:' + '#' + colorList[i] + ';"></li>');
}
$('body').click(function () {
picker.fadeOut(1);
});
$('.call-picker').click(function(event) {
event.stopPropagation();
picker.fadeIn(1);
picker.children('li').hover(function() {
var codeHex = $(this).data('hex');
$('.color-holder').css('background-color', codeHex);
$('#pickcolor').val(codeHex).trigger('change');
});
});
</script>
<div class="color-wrapper">
<p>Choose color for Header</p>
<!-- ng-model="eventData.header" This is to post the information in the color picker box into the json at the bottom to make it useable by the server. -->
<form name="test">
<input type="text" name="custom_color" ng-model="Data.headerColor" placeholder="#FFFFFF" id="pickcolor" class="call-picker">
</form>
<div class="color-holder call-picker"></div>
<div class="color-picker" id="color-picker" style="display: none"></div>
</div>
</div>
<div class="row">
<script type="text/javascript">
var hexText="123";
var colorList = [ '000000', '993300', '333300', '003300', '003366', '000066', '333399', '333333',
'660000', 'FF6633', '666633', '336633', '336666', '0066FF', '666699', '666666', 'CC3333', 'FF9933',
'99CC33', '669966', '66CCCC', '3366FF', '663366', '999999', 'CC66FF', 'FFCC33', 'FFFF66', '99FF66'];
var picker = $('#color-picker2');
for (var i = 0; i < colorList.length; i++ ) {
picker.append('<li class="color-item" data-hex="' + '#' + colorList[i] + '" style="background-color:' + '#' + colorList[i] + ';"></li>');
}
$('body').click(function () {
picker.fadeOut(1);
});
$('.call-picker2').click(function(event) {
event.stopPropagation();
picker.fadeIn(1);
picker.children('li').hover(function() {
var codeHex = $(this).data('hex');
$('.color-holder2').css('background-color', codeHex);
$('#pickcolor2').val(codeHex).trigger('change');
});
});
</script>
<div class="color-wrapper">
<p>Choose color for Header</p>
<!-- ng-model="eventData.header" This is to post the information in the color picker box into the json at the bottom to make it useable by the server. -->
<form name="test">
<input type="text" name="custom_color2" ng-model="Data.bodytextColor" placeholder="#FFFFFF" id="pickcolor2" class="call-picker2">
</form>
<div class="color-holder2 call-picker2"></div>
<div class="color-picker2" id="color-picker2" style="display: none"></div>
</div>
picker variable must change.
<script type="text/javascript">
var hexText="123";
var colorList = [ '000000', '993300', '333300', '003300', '003366', '000066', '333399', '333333',
'660000', 'FF6633', '666633', '336633', '336666', '0066FF', '666699', '666666', 'CC3333', 'FF9933',
'99CC33', '669966', '66CCCC', '3366FF', '663366', '999999', 'CC66FF', 'FFCC33', 'FFFF66', '99FF66'];
var picker2 = $('#color-picker2');
for (var i = 0; i < colorList.length; i++ ) {
picker2.append('<li class="color-item" data-hex="' + '#' + colorList[i] + '" style="background-color:' + '#' + colorList[i] + ';"></li>');
}
$('body').click(function () {
picker2.fadeOut(1);
});
$('.call-picker2').click(function(event) {
event.stopPropagation();
picker2.fadeIn(1);
picker2.children('li').hover(function() {
var codeHex = $(this).data('hex');
$('.color-holder2').css('background-color', codeHex);
$('#pickcolor2').val(codeHex).trigger('change');
});
});
</script>
Related
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.
I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});
My submit button is finally working. However, it is not counting all of the votes in the results. How do I get my submit button to sort all of the votes?
HTML:
<!DOCTYPE html>
<html>
<link rel="stylesheet" text="text/css" href="movies.css">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<title>
Movie List
</title>
</head>
<body>
<h1>My Favorite Movies</h1>
<div id = "first">
<input type="text" id="movie" placeholder="Movie">
<button id="enter">Enter</button>
</div>
<div id="left">
<div id="list"><u>Chosen Films:</u></div>
<!-- <div>Chosen Films: <span id="list"></span></div> -->
<!-- <div id="films"></div> -->
<div id="best"><u>You're Best Films:</u></div>
<button id="submit">Submit</button>
</div>
<div id= "results"><u>Results</u></div>
<script type="text/javascript" src="movies.js"></script>
</body>
</html>
Javascript:
$(document).ready(function() {
var films = [];
// with working vote button
$("#enter").click(function () {
var movie = $("#movie").val();
var $btn = $('<button />', {
id: "vote",
type: "button",
text: "Vote",
value: movie,
click: function(){
var vote = this.value;
$("#best").append('<p>'+vote+'</p>');
films.push(vote);
}
});
var $p = $('<p />');
$p.append($btn, " ", movie);
$p.appendTo("#list");
});
});
So here is where the trouble is:
This code should allow the submit button to take the listed films under "your best films" and arrange them in a third list under "results" in order of their votes.
$("#submit").click(function () {
var ballot = {};
for (var i = 1; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var i = 0; i < elect.length; i++){
console.log(elect[i].key);
$("#results").append('<p>' + elect[i].key + '</p>');
}
});
Any suggestions or ideas would be appreciated!
$("#submit").click(function () {
var ballot = {};
for ( var i = 0; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var j = 0; j < elect.length; j++){
console.log(elect[j].key);
$("#results").append('<p>' + elect[j].key + '</p>');
}
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.
I have been trying to solve the following problem for the last week or so, and after many searches around the internet, and on here, haven't found an exact solution for what I am trying to achieve.
This is my first post on here, and decided to post here as this forum has saved my bacon several times!
This is what I would like to happen:
User selects the number of scouts and leaders from the dropdowns.
The first tshirts (small) is populated with the number of leaders + scouts total.
if the user selects a lesser amount from the small dropdown, then the remaining amount is used to populate the medium select list, and so on upto XXL.
The following bit of code is how far I have got so far, but it seems a bit buggy, the option values append again and again if the user changes their mind, and the medium box is showing the total options rather that total - amount of small selected.
I don't know if this is the best way or if there are any better solutions?
Here goes
<form method='post' id="wawBooking" action='processWAWBooking.php' >
<div id="groupDetails" >
<fieldset>
<legend>Group Details</legend>
<label for="noScouts">Number of scouts:</label>
<select id='noScouts' name="noScouts"></select><br />
<label for="noLeaders">Number of leaders:</label>
<select id='noLeaders' name="noLeaders"></select><br />
</fieldset>
</div>
<div style="clear: both;"></div>
<div id="tshirts">
<fieldset style="height: auto;">
<legend>T-Shirts</legend>
Total: <span id='totalTshirts'></span><br />
Amount left (Total - current total): <span id='amountLeft'></span><br />
Sum of Selected: <span id='liveTotal'></span><br />
<label for='s'>Small</label>
<select id='s'></select><br />
<label for='m'>Medium</label>
<select id='m'> </select><br />
<label for='l'>Large</label>
<select id='l'></select><br />
<label for='xl'>X-Large</label>
<select id='xl'></select><br />
<label for='xxl'>XX-Large</label>
<select id='xxl'></select><br />
</fieldset>
</div>
<input type="reset" value="Reset Form" id="reset" style="float: left;"/>
<input type="button" value="Order t-shirts" id="tshirtOrder" style="float: right;"/>
<input type="submit" value="Submit Booking" style="float: right;"/>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var scouts = 20;
var leaders = 30;
// ignore this bit - using just to demonstrate
for (a = 0; a <= leaders; a++) {
$('#noScouts').append("<option value='" + a + "'>" + a + "</option>");
}
for (b = 0; b <= scouts; b++) {
$('#noLeaders').append("<option value='" + b + "'>" + b + "</option>");
}
// end of ignore section!
$('#wawBooking').change(function(){
var totalTshirts = parseInt($('#noLeaders').val()) + parseInt($('#noScouts').val());
var liveTotal = parseInt($('#s').val())
+ parseInt($('#m').val())
+ parseInt($('#l').val())
+ parseInt($('#xl').val())
+ parseInt($('#xxl').val());
if ($('#noScouts').val() && $('#noLeaders').val() > 0) {
$('#totalTshirts').empty().append(totalTshirts);
$('#liveTotal').empty().append(liveTotal);
for (i = 0; i <= totalTshirts; i++) {
$('#s').append('<option value="' + i + '">' + i + '</option>')
}
if ($('#s').val() > 0 && $('#s').val() < totalTshirts) {
var subSmallMinusTotal = parseInt(totalTshirts) - parseInt($('#s').val());
for (k = 0; k <= subSmallMinusTotal; k++) {
$('#m').append('<option value="' + k + '">' + k + '</option>')
}
}
}
});
</script>
Any suggestions or tips?
Many thanks in advance
Chris
Here's a possible solution. You might be able to tweak it to be more generic and generate the lists off a collection, but I think it'll get you started.
Example (JsFiddle)
HTML
<label for="noScouts">Number of scouts:</label>
<select id='noScouts' name="noScouts"></select><br />
<label for="noLeaders">Number of leaders:</label>
<select id='noLeaders' name="noLeaders"></select><br />
<label for="noSmall">s:</label>
<select id='noSmall' name="noSmall"></select>
<label for="noMed">m:</label>
<select id='noMed' name="noMed"></select>
<label for="noLarge">l:</label>
<select id='noLarge' name="noLarge"></select>
<label for="noXLarge">xl:</label>
<select id='noXLarge' name="noXLarge"></select>
<label for="noXXLarge">xxl:</label>
<select id='noXXLarge' name="noXXLarge"></select>
JS
var sizes = $('#sizes');
var numScouts = new selectRange('#noScouts', { max: 30 });
var numLeaders = new selectRange('#noLeaders', { max: 20 });
var total = new watchVal(0);
var small = new selectRange('#noSmall', { max: 0 });
var med = new selectRange('#noMed', { max: 0 });
var large = new selectRange('#noLarge', { max: 0 });
var xlarge = new selectRange('#noXLarge', { max: 0 });
var xxlarge = new selectRange('#noXXLarge', { max: 0 });
numScouts.change(zSetTotal);
numLeaders.change(zSetTotal);
total.change(function(e, total){
small.setMax(total);
});
small.change(function(){
med.setMax(total.value() - small.value());
});
med.change(function(){
large.setMax(total.value() - med.value() - small.value());
});
large.change(function(){
xlarge.setMax(total.value() - med.value() - small.value() - large.value());
});
xlarge.change(function(){
xxlarge.setMax(total.value() - med.value() - small.value() - large.value() - xlarge.value());
});
function zSetTotal(){
total.value(numScouts.value() + numLeaders.value());
}
function watchVal(initVal){
var _val = initVal;
var $_ctx = $(this);
$_ctx.value = function(newVal){
if(newVal){
_val = newVal;
$_ctx.trigger('change', _val);
}else{
return _val;
}
}
return $_ctx;
}
function selectRange(selector, options){
var _config = {
max: 10
};
var _select = null;
var _ctx = this;
function zInit(){
$.extend(_config, options);
if($(selector).is('select')){
_select = $(selector);
}else{
_select = $('<select />');
_select.appendTo(selector);
}
_ctx.repaint();
}
this.setMax = function(max){
_config.max = max;
this.repaint();
_select.trigger('change');
};
this.repaint = function(){
var prevPos = _select.find('> option:selected').index();
_select.empty();
for (var i = 0; i <= _config.max; i++) {
var option = $("<option />", {
'value': i,
'text': i
});
_select.append(option);
if(i === prevPos){
option.prop('selected', true);
}
}
};
this.value = function(){
return parseInt(_select.val(), 10);
};
this.change = function(fun){
_select.change(fun);
};
zInit();
}