why my h1 title hides behind input box when slideUp executes - javascript

I have the following page, which is a wikisearch page that queries multiple wikipidia pages for the search term. The page has the title and input box somewhere around the middle; however, when I click on the botton, the title slides up, and so the input box. But the input box slides all way up covering the title. I think!... how can I prevent the inputbox from covering the title? or make the title stays at the top of page? Thanks
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
console.log(searchStr);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
console.log(response.query);
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary" onclick="#">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>

Insted of using $('#title').slideUp(3000) try use $('#title').animate({'margin-top': '0'}, 3000);
Then the title will remain.
Also, you might want to remove onclick="#" from <button id="search" class="btn btn-primary" onclick="#">Search</button>
Example below.
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$('#title').animate({'margin-top': '0'}, 3000);
//$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>

Add this to the h1 class
h1 {
z-index: 1000;
}
Now let's say you needed something to then go on top of the header, you'd give that element's class a z-index of something higher than 1,000, so maybe 1,001! If you needed something to go behind, simply make it 999 or lower. Using 1,000 gives you a lot of free range in either direction (+/-) to work with.

Related

Why is my text output from next() and prev() toggle incorrect?

When clicking the arrows to change the displayed option, the incorrect options is shown.
The user should be able click on the option menu to toggle it open/cosed and be able to click on a option to select it. Alternatively, the arrows could be used to toggle through the options instead.
This is the problematic code:
<script>
$("#arrow_left_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $("#left_menu__variant_physics").children();
divs.eq((divs.index($selected) - 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
$("#arrow_right_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $selected.parent().children();
divs.eq((divs.index($selected) + 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
</script>
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
-It seems that the first click of the arrows isn't working and that the index function is incorrect somewhere.
The problem is this line:
$("#menu_open .button_text").text($($selected).text());
$($selected) is the option that was previously selected, so you're showing the text of the previous option, not the current option. (BTW, there's no need to wrap $selected in $(), since it's already a jQuery object.)
You should use $(".menu_option_selected").text() instead of $($selected).text() to get the current option.
You should also make the initial text of the button option1, so it matches the selected option.
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
Just another version, refactoring your javascript code with some Arrow functions.
const setButtonText = () => {
$("#menu_open .button_text").text(
$(".menu_option_selected").text()
);
}
const moveSelection = direction => {
var selected = $(".menu_option_selected")
var options = $("#menu").children()
var newIndex;
if (direction == 'right') {
newIndex = (options.index(selected) + 1) % options.length
} else {
newIndex = (options.index(selected) - 1) % options.length
}
selected.removeClass("menu_option_selected")
options.eq(newIndex).addClass("menu_option_selected")
setButtonText()
}
// inizilize menu button_text
setButtonText()
$("#arrow_left").click(() => moveSelection('left'));
$("#arrow_right").click( () => moveSelection('right'));
$("#menu_open").click( () => $("#menu").toggle());
$(".menu_option").click( function() {
$(".menu_option_selected").removeClass("menu_option_selected")
$(this).addClass("menu_option_selected")
setButtonText()
});

Form to fill excel spreadsheet

I've been trying to build an application to submit form selections to an existing spreadsheet on a local machine. This is intended for a windows machine, but I am working on ubuntu, and don't have access to a windows development environment. With this, I'm trying to parse an excel document, find the bottom row, capture the 'ingredients' list, or other form values, then insert the value of the hash into the excel column and save the changes to the document. Any suggestions on where I should start would be great.
-- Thanks a million
//Script
$(document).ready(doInput);
function doInput(){
var ingreds = $('.ingredients');
var count = $('.count');
var runs = $('#runs');
var cb = $('.cb');
var bb = $('.bb');
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
var bbDate = fullDate.getMonth() + 8;
cb.html("C&B:<br />" + currentDate);
if (bbDate > 12){
bb.html("BB:<br />" + "0" + (bbDate - 12) + "/" + fullDate.getDate() + "/" + (fullDate.getFullYear() + 1));
}else{
bb.html("Best By:<br />" + bbDate + "/" + fullDate.getDate() + "/" + fullDate.getFullYear());
}
var recipes = {
'Volvo': {
'Torq': 1231,
'Leather': 131,
'Blue': 22
},
'Jet': {
'HP': 1233,
'Leather': 121,
'Candy': 1313,
'Gas': 1313,
'Billiard': 223
},
'Mac': {
'Torq': 12111,
'Cheddar': 123
},
'Hog': {
'Torq': 475,
'Sugar': 12,
'Sheer': 11,
'Water': 2323,
'Wheels': 3
}
}
var recipe;
ingreds.html("Ingredients:<br />");
count.html("The Yield is:" + $('#yield').val() + "?<br />");
if ($("option:selected").val() == 'volv') {
recipe = recipes['Volvo'];
}else if($("option:selected").val() == 'jet') {
recipe = recipes['Jet'];
}else if($("option:selected").val() == 'mac') {
recipe = recipes['Mac'];
}else if($("option:selected").val() == 'hog') {
recipe = recipes['Hog'];
}
for (key in recipe){
if(key == 'Sugar'){
ingreds.append(key + ": " + recipe[key] * runs.val() + 'Lbs<br />');
}else{
ingreds.append(key + ": " + recipe[key] * runs.val() + 'g<br />');
}
}
return true;
}
body {
background: rgba(150,150,150,.5);
}
.container {
width: 80%;
margin: auto;
padding: 10px;
}
.ingredients {
padding: 10px;
padding-left: 20px;
}
.count {
margin-top: 25px;
font-weight: Bold;
color: #700;
}
.submit,
.ingredients,
.flavor,
.runs,
.yieldShell,
.bestBy,
.cb,
.bb {
min-width: 215px;
}
.count {
min-width: 190px;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.row:before,
.row:after {
display: table;
content: " ";
}
.row:after {
clear: both;
}
.col-sm-4{
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
#media (min-width: 540px) {
.container {
width: 750px;
}
.col-sm-4 {
float: left;
width: 33.33333333333333%;
}
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="container">
<form oninput="doInput()">
<div class="row">
<div class="flavor col-sm-4">
Flavor:<br />
<select name="flavors">
<option value="volv" selected="selected">Volvo</option>
<option value="jet">Jet</option>
<option value="mac">Mac</option>
<option value="hog">Hog</option>
</select>
</div>
<div class="runs col-sm-4">
Number of runs:<br />
<input type="number" id="runs" name="runs" value="1">
</div>
</div>
<div class="row">
<div class="ingredients col-sm-4"></div>
<div class="yieldShell col-sm-4">
<div class="yield">Yield:<br />
<input type="number" id="yield" name="yield" value="450">
</div>
<div class="count col-sm-4"></div>
</div>
</div>
<div class="row">
<div class="submit col-sm-4">
<input type="submit" value="Save to Production Log?">
</div>
<div class="bestBy col-sm-4">
<div class="row">
<div class="col-sm-4 cb"></div>
</div>
<div class="row">
<div class="col-sm-4 bb"></div>
</div>
</div>
</div>
</form>
</div>
Are you not looking at this from the wrong angle?
Rarely would you try to access an Excel document directly, since the quantity of 'irrelevant' data is huge (data needed by Excel to reconstruct the page itself, but not directly related to the data the user is storing - meta-data if you will; i.e. font used, size of font, etc.).
Usually you would output the data to a CSV and allow the user to import the data into any spreadsheet program, which gives you greater flexibility and is simpler to code.
In terms of adding the data, you could easily open the existing CSV and append new data, or search the file and insert the data where required. However, if others are to use the CSV then I'd save the data in a single-table database as well as in the CSV. Then you simply construct a new CSV each time, overwriting any existing file if necessary.
No code help here at present, and I might be wrong, but this is the approach I have used and seen used.

How to pause and start gif using jQuery AJAX

I am a student and I am trying to start, pause and start a gif when a user clicks the gif, however I am stuck on how to add in this click function. I know that the the gif version of the object is .images.fixed_height.url and the still image is .images.fixed_height_still.url . If I try to append like below $(this) I get that images is undefined. How would I go by doing this? Currently 10 gifs show when you click the category. Thank you for any help in advance.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Giphy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
body {
background-image: url('http://www.efoza.com/postpic/2011/04/elegant-blue-wallpaper-designs_154158.jpg');
width: 100%;
}
button {
padding: 0 2%;
margin: 0 2%;
}
h4 {
font-size: 165%;
font-weight: bold;
color: white;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
max-width: 1000px;
width: 100%;
}
.btn {
margin-top: 2%;
margin-bottom: 2%;
font-size: 125%;
font-weight: bold;
}
.guide {
padding: 3% 0 0 0;
}
.tag-row {
padding: 3% 0 0 0;
}
.category-row {
padding: 3% 0 ;
}
#photo {
padding-bottom: 3%;
}
</style>
</head>
<body>
<div class="container">
<div class="row text-center guide"><h4>Click a category and see the current top 10 most popular giphy's of that category!</h4></div>
<div class="row text-center tag-row" id="tags"></div>
<div class="row text-center category-row">
<input type="" name="" id="category"><button class="btn btn-secondary" id="addTag">Add Category</button>
</div>
</div>
<div class="container">
<div id="photo"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var tags = ["dog", "dolphin", "whale", "cat", "elephant", "otter"];
// Function for displaying movie data
function renderButtons() {
$("#tags").empty();
for (var i = 0; i < tags.length; i++) {
$("#tags").append('<button class="tag-buttons btn btn-primary">' + tags[i] + '</button>');
}
}
// Add tags function //
$(document).on('click', '#addTag', function(event) {
event.preventDefault();
var newTag = $("#category").val().trim();
tags.push(newTag);
$("#tags").append('<button class="tag-buttons btn btn-primary">' + newTag + '</button>');
});
// Tag button function //
$(document).on('click', '.tag-buttons', function(event) {
// Keeps page from reloading //
event.preventDefault();
var type = this.innerText;
console.log(this.innerText);
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + window.encodeURI(type) + "&limit=10&api_key=dc6zaTOxFJmzC";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
for (var i = 0; i < response.data.length; i++) {
$("#photo").append('<img src="' + response.data[i].images.fixed_height_still.url + '" class="animate">');
$('.animate').on('click', function() {
$(this).remove().append('<img src="' + response.data[i].images.fixed_height.url + '" class="animate">');
console.log($(this));
});
}
});
$("#photo").empty();
});
renderButtons();
</script>
</body>
</html>
The difference between fixed_height and fixed_height_still will solve the problem. if you look closely the urls differ only by name_s.gif and name.gif.
So you can simply swap the two images to create a player. This will act like a play and stop. Not play and pause. But in a small gif I don't think pause really matter, stop and pause will look similar.
adding class name to the #photo
$("#photo").append('<img class="gif" src="' + response.data[i].images.fixed_height_still.url + '">');
event handler which will control play and stop
$('body').on('click', '.gif', function() {
var src = $(this).attr("src");
if($(this).hasClass('playing')){
//stop
$(this).attr('src', src.replace(/\.gif/i, "_s.gif"))
$(this).removeClass('playing');
} else {
//play
$(this).addClass('playing');
$(this).attr('src', src.replace(/\_s.gif/i, ".gif"))
}
});
jsfiddle demo
https://jsfiddle.net/karthick6891/L9t0t1r2/
you can use this jquery plugin http://rubentd.com/gifplayer/
<img class="gifplayer" src="media/banana.png" />
<script>
$('.gifplayer').gifplayer();
</script>
you can control like this
Use these methods to play and stop the player programatically
$('#banana').gifplayer('play');
$('#banana').gifplayer('stop');
youll find more details here https://github.com/rubentd/gifplayer

if statement not evaluating condition as expected

I am using a $.getJSON function to return JSON from an API of employee salaries. For each entry, I have a counter that goes up for each employee returned. I added a list that allows the user to choose the department the employee works in as a variable to check when the function is wrong. When the check function runs for all employees, it works as expected returning 1000 employees. However, when I add in the if statement, it does add any employees to the employee counter.
I am logging the selected department to the console and can see the department is correctly selected. I think put in a string of "Department of Police" to use in the function and it return 186 employees. If I use the variable checkedValue which shows in the console the same value I would expect the same function to return 186 employees but it does not. The value is held in the JSON object as a string so I'm not sure if the wrong data would be the problem.
What am I doing wrong?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<div id="page">
<div id="content">
<div id="button-area">
<button id="check">Check the radio button</button>
<button id="action">Do Action</button>
</div>
<div id="checks">
</div>
<div>
<ul id="list"></ul>
</div>
</div>
</div>
</body>
CSS:
body {
font-family: 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;
height: 100%;
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
#page {
width: 80%;
margin: 0 auto;
border: 1px solid black;
box-shadow: 3px 3px 5px 2px black;
}
#content {
margin: 10px;
}
#button-area {
padding-top: 50px;
width: 100%;
height: 100px;
margin: 0 auto;
text-align: center;
}
JavaScript:
var url;
var myNewObject;
var myObject;
var departmentArray;
var cleanedDepartmentArray;
var checkedValue;
var budget = 0;
var employees = 0;
function setTheList() {
$.getJSON(url, function(data) {
myObject = data;
for (var i = 0; i < myObject.length; i++) {
departmentArray.push(myObject[i].department_name);
};
$.each(departmentArray, function(i, el) {
if ($.inArray(el, cleanedDepartmentArray) === -1) {
cleanedDepartmentArray.push(el);
}
});
for (var i = 0; i < cleanedDepartmentArray.length; i++) {
$('#list').html("");
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
};
});
};
$(document).ready(function() {
console.log("Initialized with " + employees + " employees and " + budget +
" budget.");
url = 'https://data.montgomerycountymd.gov/resource/54rh-89p8.json';
myObject;
myNewObject;
departmentArray = [];
cleanedDepartmentArray = [];
//set the list
setTheList();
//get checked radio button value
function getCheckedValue() {
checkedValue = "";
checkedValue = $("input[name=department]:checked").val();
console.log(checkedValue);
};
//call geojson
function getData(checkedValue) {
getCheckedValue();
$.getJSON(url, function(data) {
myNewObject = data;
console.log("my new object: ", myNewObject)
for (i = 0; i < data.length; i++) {
if (data[i].department_name === checkedValue) {
employees++;
};
};
console.log(checkedValue);
console.log(employees)
});
};
$('#check').on('click', function() {
getCheckedValue();
});
$('#action').on('click', function() {
getData(checkedValue);
});
});
There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Seeing if I can highlight this any clearer for you:
There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Just to see if I can highlight it any better:
cleanedDepartmentArray[i] + " ' <<< this bit

jQuery search bar only working one time per page

I am working on a page for pre-registration to events on my website. On this page, people need the ability to add names into as many slots as the event creator would like (so it needs to handle 3 person basketball teams and 50 person banquets). I have had a high quality facebook-like search bar made so that I can neatly search through the database and select the desired people. Sadly I have this search bar being created by a for loop that creates many different ID filled search bars but every one of them is left empty and the first search bar is the only one that is filled.
I found that it deals with the jQuery code at the top of my page. My question/issue is that I need this jQuery to work on multiple search bars on a single page. If anyone can help me accomplish this I'd be greatly appreciative.
The "top code" or JQuery code that pulls from the db successfully is:
$(function(){
$(".search").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
<style type="text/css">
body{
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.contentArea{
width:600px;
margin:0 auto;
}
/*
#inputSearch
{
width:350px;
border:solid 1px #000;
padding:3px;
}
*/
#divResult
{
position:absolute;
width:545px;
display:none;
margin-top:-1px;
border:solid 1px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 3px 1px 1px;
border-style: solid;
border-color: #333 #DEDEDE #DEDEDE;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px;
}
.display_box:hover
{
background:#0088cc;
//background:#3bb998;
color:#FFFFFF;
cursor:pointer;
}
The for-loop code that prints the search bars is as follows:
for($i = 0; $i < $looper; $i++)
{
echo'
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div id="divResult" style="z-index:999; margin-top: 35px;" ></div>
</div>
</div>
</div>';
}
EDIT: Working JSFiddle
The first issue is that with each iteration of the for loop an element is created with id="divResult". An ID should be used once in the whole document. I have changed the for loop to produce an element with class="divResult" instead. If you use this change, remember that your CSS will need to be changed accordingly.
for ($i = 0; $i < $looper; $i++) {
echo '
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div class="divResult" style="z-index:999; margin-top: 35px;"></div>
</div>
</div>
</div>';
}
Next we iterate over each .search element. Within each iteration we can find the corresponding 'result' element by using jQuery's next() function, which retrieves the immediately following sibling of an element. If the code is ever changed such that the 'results' element does not appear straight after the `.search' element, this will need changing.
$(function () {
$('.search').each(function(index) {
var $searchElement = $(this);
var $resultElement = $searchElement.next();
console.log(index, $searchElement, $resultElement);
$searchElement.on('keyup', function() {
var inputSearch = $searchElement.val();
var dataString = 'searchword=' + inputSearch;
if (inputSearch != '') {
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function (html) {
$resultElement.html(html).show();
}
});
}
return false;
});
$resultElement.on("click", function (e) {
var $clicked = $(this);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$searchElement.val(decoded);
});
$(document).on("click", function (e) {
var $clicked = $(e.target);
if (!$clicked.hasClass("search")) {
$resultElement.fadeOut();
}
});
$searchElement.on('click', function () {
console.log(index + ' clicked');
$resultElement.fadeIn();
});
});
});

Categories