Been stuck on this for a while and wanted to get some input as to what I can do differently. I'm essentially taking user input and pushing it into an array, creating a button based on that input, then saving that array to localStorage. When the browser is refreshed, I want to grab that string and re-create those same buttons. Here is what I've got so far:
function generateButton() {
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(response.name)
buttonDiv.prepend(create)
var cityString = response.name
cityButtonArr.push(cityString)
localStorage.setItem("cityStorage", JSON.stringify(cityButtonArr))
console.log(cityButtonArr)
as well as:
function loadData(){
var loadData = localStorage.getItem("cityStorage")
var loadedArr = JSON.parse(loadData)
//
if(loadedArr != null && loadedArr != ""){
cityButtonArr.push(loadedArr)
for(i=0; i<cityButtonArr.length;i++){
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(cityButtonArr[i])
buttonDiv.prepend(create)
}
}
It works almost perfectly, but instead of loading individual parts of the array ("atlanta","las vegas", "salt lake city") it only creates one button with the text of (atlantalasvegassaltlakecity). How can I break up the array when using JSON.parse? Or am I going about this all wrong?
function loadData() {
var loadData = localStorage.getItem("cityStorage")
if (loadData == null || loadData == "") return;
var cityButtonArr = JSON.parse(loadData)
for (i = 0; i < cityButtonArr.length; i++) {
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(cityButtonArr[i])
buttonDiv.prepend(create)
}
}
Full code
Related
I have this keyboard site launcher script, which I copied from some place years ago and it works fine as is. I want to enhance it by adding a cascading keypress launch for some of the keys. Here is my code:
<html><head>
<script language="JavaScript">
<!-- Begin
var key = new Array();
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "https://slashdot.org";
key['y'] = "http://www.yahoo.com";
function getKey(keyStroke) {
isNetscape=(document.layers);
eventChooser = (isNetscape) ? keyStroke.which : event.keyCode;
which = String.fromCharCode(eventChooser).toLowerCase();
// alert('['+which+'] key \n has been stroke');
runUrl(which);
}
function runUrl(which) {
for (var i in key)
if (which == i) {window.location = key[i];}
}
document.onkeypress = getKey;
// End -->
</script></head>
<body>
Make a selection<br>
<br>
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "https://slashdot.org";
key['y'] = "http://www.yahoo.com";
<br>
<br>
<!-- I solemnly swear this page is coded with vi or notepad.exe depending on the OS being used -->
</body>
</html>
Now, I want to modify the action for pressing the letter "s" to launch a submenu of sorts and ask me to select if I want to go to "Slashdot" or Spotify" for instance. like if I press an "s" second time, it goes to slashdot and if I press "f" for instance, it goes to spotify.
My problem is, I have never programmed in Javascript other than copying and pasting code and changing string values in the code, like here, changing the pressed keys and site URLs.
Any pointers, regarding how to start modifying this code, are greatly appreciated.
to be honest, the code provided is a bit outdated but I keep it so you can see the necessary changes that I made for the menu to be added and to implement the feature it's just a sketch but I will do the job I think from here you can expand, hope this puts you in the right direction
let isopenMenu = true;
const menu = document.getElementById("menu");
function toggleMenu() {
isopenMenu = !isopenMenu;
menu.style.display = isopenMenu ? "block" : "none";
}
var key = new Array();
key["a"] = "https://www.arstechnica.com";
key["g"] = "https://www.google.com";
key["s"] = "https://slashdot.org";
key["y"] = "http://www.yahoo.com";
key["b"] = "http://www.stackoverflow.com";
key["c"] = "http://www.test.com";
const menuSite = ["b", "c", "s"];
function getKey(keyStroke) {
isNetscape = document.layers;
eventChooser = isNetscape ? keyStroke.which : event.keyCode;
which = String.fromCharCode(eventChooser).toLowerCase();
runUrl(which);
}
function runUrl(which) {
for (var i in key)
if (which == i) {
if (which === "s") {
return toggleMenu();
}
if (!isopenMenu && menuSite.includes(which)) {
return;
}
window.location = key[i];
}
}
document.onkeypress = getKey;
window.addEventListener("load", toggleMenu);
<html><head>
<script language="JavaScript">
</script></head>
<body>
Make a selection<br>
<br>
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "to toggel menu
key['y'] = "http://www.yahoo.com";
<br>
<br>
<ul id="menu">
<li>key['b'] = "http://www.stackoverflow.com";</li>
<li>key['c'] = "http://www.test.com</li>
</ul>
</body>
</html>
Indeed the code you've provided seems a bit dusted. There's some stuff that isn't done in that way nowadays. Notepad is an editor I still occassionally use though.
Since you've mentioned that you never really used JavaScript it's a bit hard to give you advice. You can do things way more elegant and even improve the look - but I'd say this would just confuse you even more. So let's work on something based on your code.
At the moment the keys and the corresponding targets are stored in an object (yeah, it's an object not an array). We can use a second object - let' say subKey - to store the additional targets upon pressing s.
var key = {};
key.a = "https://www.arstechnica.com";
key.g = "https://www.google.com";
key.s = "subMenu";
key.y = "http://www.yahoo.com";
var subKey = {};
subKey.a = "https://www.stackoverflow.com";
subKey.g = "https://www.startpage.com";
subKey.s = "goBack";
As you can see I've reserved the key s to go to the sub menu and inside the sub menu this button is used to go back to the main menu.
Now instead of hardcoding what the user gets to see on screen, we can iterate over those objects and use the information from there. To do this we need to reserve a html element - I've chosen an empty <div> which acts as some sort of container. As we iterate over the object we construct a string with the keys and it's associated targets and ultimately assign this this to the div's .innerHTML property.
let container = document.getElementById("container");
container.innerHTML = "Make a selection<br><br>";
for (var i in obj) {
container.innerHTML += "key['" + i + "'] = " + obj[i] + "<br>";
}
As the procedure is the same for both objects we just need to wrap it inside a function and pass it a reference to the desired object.
Your runUrl function needs to be modified a bit to take care of the additional options. This is best done with a simple if-else construct. So in pseudo-code:
if choice is subMenu open sub menu
if choice is goBack open main menu
if it's none of the above open a link
If we put everything together, your example looks a little bit like this:
(Just click on 'Run code snippet' and make sure to click somewhere inside the window so it'll have key focus)
<html>
<head>
</head>
<body>
<div id="container">
</div>
</body>
<script type="text/javascript">
var key = {};
key.a = "https://www.arstechnica.com";
key.g = "https://www.google.com";
key.s = "subMenu";
key.y = "http://www.yahoo.com";
var subKey = {};
subKey.a = "https://www.stackoverflow.com";
subKey.g = "https://www.startpage.com";
subKey.s = "goBack";
var currentObj = key;
function getKey(event) {
let which = String.fromCharCode(event.keyCode).toLowerCase();
runUrl(which)
}
function runUrl(which) {
for (var i in currentObj) {
if (which == i) {
if (currentObj[i] != "subMenu") {
if (currentObj[i] != "goBack") {
window.location = currentObj[i];
} else {
populateMenu(key);
}
} else {
populateMenu(subKey);
}
}
}
}
function populateMenu(obj) {
currentObj = obj;
let container = document.getElementById("container");
container.innerHTML = "Make a selection<br><br>";
for (var i in obj) {
container.innerHTML += "key['" + i + "'] = " + obj[i] + "<br>";
}
}
populateMenu(key);
document.onkeypress = getKey;
</script>
</html>
It looks like could achieve this with arbitrary list of sites. If so, you could handle this a little more generically by providing a list of sites and filtering the sites based on keystrokes.
If so, you can achieve it with the following:
const sites = [
'https://www.arstechnica.com',
'https://www.google.com',
'https://mail.google.com',
'https://slashdot.org',
'https://spotify.com',
'http://www.yahoo.com',
];
let matches = sites;
document.getElementById('keys').addEventListener('keyup', event => {
const keys = event.target.value.toLowerCase().split('');
matches = sites
.map(site => ({ site, stripped: site.replace(/^https?:\/\/(www\.)?/i, '')})) // strip out https://wwww. prefix
.filter(site => isMatch(site.stripped, keys))
.map(site => site.site);
if (event.keyCode === 13) {
if (matches.length === 0) {
alert('No matches');
} else if (matches.length === 1) {
alert(`launching ${matches[0]}`);
} else {
alert('More than one match found');
}
matches = sites;
}
document.getElementById('matches').textContent = matches.join(', ');
});
// find sites matching keys
function isMatch(site, keys) {
if (keys.length === 0) return true;
if (site.indexOf(keys[0]) !== 0) return false;
let startIndex = 1;
for (let i = 1; i < keys.length; i++) {
let index = site.indexOf(keys[i], startIndex);
if (index === -1) return false;
startIndex = index + 1;
}
return true;
}
document.getElementById('matches').textContent = matches.join(', ');
<div>Keys: <input type="text" id="keys" autocomplete="off" /> press Enter to launch.</div>
<p>Matches: <span id="matches" /></p>
The key parts to this are:
Define a list of sites you want to handle
Ignore the the https://wwww prefixes which is achieved with site.replace(/^https?:\/\/(www\.)?/i, '')
Implement filter logic (in this case it is the isMatch method) which tries to match multiple keystrokes
For demonstration purposes, I've wired keyup to an input field instead of document so that you can see it in action, and the action is triggered with the enter/return key.
I try to create a generator for lucky numbers. I did it with C# and now with JavaScript and jQuery. You can see this here. When I add new field - JQ do not see it. Just try to click on numbers in "Your field". I have as standard 7 fields and they work fine but when I add new line script do not recognise it like something useful. Could you give me some advice?
change below js code. check this working plunker
Your code:
$('.spielzahlen').on('click', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
Change it with below code , there is only change in initialization other code are same :
$(document).on('click','.spielzahlen', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
In my traveling website I want to filter the search result using multiple check boxes. Currently my code is working as follows.
If I check "Near Airport", it will show only the hotels with the data tag "airport". But when I want to filter the hotels which are near to both the air port and the shopping district at the same time, it will not work. It shows the list of hotels which have the data tag "airport" OR "shopping". I want to change it to list the hotels which have both data tags "airport" AND "shopping".
Screenshot of the web site http://prntscr.com/c49csj
Code in Context
$(document).ready(function(){
$('.category').on('change', function(){
var category_list = [];
$('#filters :input:checked').each(function(){
var category = $(this).val();
category_list.push(category);
});
if(category_list.length == 0)
$('.resultblock').fadeIn();
else {
$('.resultblock').each(function(){
var item = $(this).attr('data-tag');
var itemarr = item.split(',');
$this = $(this);
$.each(itemarr,function(ind,val){
if(jQuery.inArray(val,category_list) > -1){
$this.fadeIn('slow');
return false;
}
else
$this.hide();
});
});
}
});
});
You need to ensure that all elements in category_list array are available in itemarr array. The post How to check whether multiple values exist within an Javascript array should solve your problem e.g in the else block, modify your code as follows:
var item = $(this).attr('data-tag');
var itemarr = item.split(',');
var hideItem = false;
for(var i = 0 , len = itemarr.length; i < len && !hideItem; i++){
hideItem = ($.inArray(itemarr[i], category_list) == -1);
}
if(hideItem) {
$this.hide();
} else {
$this.fadeIn('slow');
}
I am making a registration page that allows you to register an account to a mysql database for my uni project.
In this page you can also 'select' your avatar picture. Here is the code below:
<u>Select your avatar:</u><br>
<?php
// open this directory
$image_dir = opendir("images/avatars");
// get each entry
while( $image = readdir( $image_dir ) )
{
$dirArray[] = $image;
}
// close directory
closedir($image_dir);
// count elements in array
$indexCount = count($dirArray);
// loop through the array of files and print them all in a list
for($index=0; $index < $indexCount; $index++)
{
$extension = substr($dirArray[$index], -3);
if( $extension == "jpg" || $extension == "gif" )
{
//echo("<a href='#'>");
echo("<img id='$index' onClick='SetAvatar($index)' img src='images/avatars/$dirArray[$index]' class='o'> ");
//echo("</a>");
}
}
?>
<script>
function SetAvatar(id) {
var image = document.getElementById(id);
if( CurSelectedImage != null && id != CurSelectedImage )
{
var image_to_unselect = document.getElementById(CurSelectedImage);
image_to_unselect.Selected = false;
image_to_unselect.style.border = null;
}
if( image.Selected != true )
{
image.style.border = 'medium solid blue';
image.Selected = true;
SelectedImage = id;
}
else
{
image.style.border = null;
image.Selected = false;
SelectedImage = null;
}
}
</script>
This selects the avatar picture, makes the border blue and stores the selected image id in a variable but how would I pass the variable with the selected image id back to php so I can save it??
Thanks
can you show your CSS codes too ?
or you can find here jQuery select and unselect image
your answer
You have to think about your application design. Mixing PHP and Javascript isn't the best idea. Use a API instead of mixing code. You can call this API with Ajax. I think this is a good design choice:
Create a getImages API in PHP: You output the data in a json array.
You calling this api with javascript and generating the DOM with the json
You creating a click handler in javascript and calling again a API in PHP
You getting the json data in PHP and saving it in your db
:)
My suggestion would be to use a CSS class. Remove any existing instances of the class then add the class to the selected image.
function SetAvatar(id) {
//remove existing border(s) a while loop is used since elements is a live node list which causes issues with a traditional for loop
var elements = document.getElementsByClassName("selected-avatar");
while (elements.length > 0) {
var element = elements.item(0);
element.className = element.className.replace(/(?:^|\s)selected-avatar(?!\S)/g , '');
}
var image = document.getElementById(id);
image.className += " selected-avatar";
}
To pass the avatar value, I'd suggest using a form to pass all of your registration data to process_register (if you are not already). You can add an input of type hidden to your form and populate the value through javascript on submit.
html:
<form id="registration-form" action="process_register.php" method="put">
<input id="registration-avatar" type="hidden" />
<button id="registration-submit">Submit</button>
</form>
javascript:
document.getElementById("registration-submit").onclick = function(){
var avatarValue; //you'll need to write some code to populate the avatarValue based on the selected avatar image
document.getElementById("registration-avatar").value = avatarValue;
document.getElementById('registration-form').submit();
};
Then in php you can get the values using $_POST
http://php.net/manual/en/reserved.variables.post.php
I am developing a Rails 4 web application. In my Rails application View i have 2 forms . First form contains List of Employees where i can select employees and add to Second Form by clicking on ADD button . Second form also contains a button where i can remove employees from Second Form, all the removed employees will be moved back to first form.
Currently i achieving it like , when i click the add button in First form i will pass the selected employee data to controller through an Ajax call and return the same selected data to second form to display selected employees.
Is it possible to manage this from client side without making any call to Server.
Is there any gems available in Rails to achieve this.
I am using Rails 4 and Ruby 2.
Example : Sample List Manipulation in Javascript
Any help is appreciated.
Yes it's possible to do this on the client-side
Javascript
All I would do is replace your ajax calls with the on-page JS
Have used JQuery in this example (hope that's okay):
http://jsfiddle.net/U443j/3/
$(".move").on("click", "input", function() {
var button = $(this).attr("id");
var from = document.getElementById("FromLB");
var to = document.getElementById("ToLB");
if (button == "left") {
move(to, from);
}else{
move(from, to);
}
});
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
This will allow you to move the items between form elements. The reason this is important is because it allows you to send the data to the controller as one data-set:
Controller
On my JSFiddle, I have a save button
This can be tied to your Rails controller, allowing you to send your form data to your system
This will send your params hash like this:
params { "FromLB": ["value1", "value2"], "ToLB": ["value1", "value2"] }
The hash will be structured differently, but you'll get two sets of data, which you can then put into your db:
#app/controllers/your_controller.rb
def action
#from = params[:FromLB]
#to = params[:ToLB]
#Save the data-sets here
end