I have gotten the code for all permutations of a string from another user on stackoverflow and i am trying to make it work in my webpage. Are there any problems with this code? I get an error in the javascript console when i try to submit a word. The error flashes for a short time so i cannot read it.
$(document).ready(function() {
$('form#anagram').submit(function(event) {
function findAllPermutations(str, index, buffer) {
if (typeof str == "string") {
str = str.split("") };
if (typeof index == "undefined") {
index = 0 };
if (typeof buffer == "undefined") {
buffer = [] };
if (index >= str.length) {
return buffer };
for (var i = index; i < str.length; i++) {
buffer.push(ToggleLetters(str, index, i));
}
return FindAllPermutations(str, index + 1, buffer);
}
function ToggleLetters(str, index1, index2) {
if (index1 != index2) {
var temp = str[index1]
str[index1] = str[index2]
str[index2] = temp
};
return str.join("");
}
list = $('input#word').val();
$('#resulttext').append("<p>" + findAllPermutations(list) + "</p>")
event.preventDefault();
});
});
here is the HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.1.js"></script>
<script src="js/scripts3.js"></script>
<title>Anagram finder</title>
</head>
<body>
<div class="container">
<div class="band">
<h1>Anagram Finder</h1>
</div>
<form id="anagram">
<div class="form-group">
<label for="word">Your Word</label>
<input id="word" type="text">
</div>
<button type="submit" class="btn">Find!</button>
</form>
<div id="resulttext">
</div>
</div>
</body>
</html>
There was a mistake in the function name and as event.preventDefault() was at the end of the function, you wan not being able to see the error as the page was being refreshed.
Try it:-
<!DOCTYPE html>
<script src="jquery.js"></script>
<title>Anagram finder</title>
</head>
<body>
<script>
$(document).ready(function() {
$('form#anagram').submit(function(event) {
event.preventDefault();
function findAllPermutations(str, index, buffer) {
if (typeof str == "string") {
str = str.split("") };
if (typeof index == "undefined") {
index = 0 };
if (typeof buffer == "undefined") {
buffer = [] };
if (index >= str.length) {
return buffer };
for (var i = index; i < str.length; i++) {
buffer.push(ToggleLetters(str, index, i));
}
return findAllPermutations(str, index + 1, buffer);
}
function ToggleLetters(str, index1, index2) {
if (index1 != index2) {
var temp = str[index1]
str[index1] = str[index2]
str[index2] = temp
};
return str.join("");
}
list = $('input#word').val();
$('#resulttext').append("<p>" + findAllPermutations(list) + "</p>")
});
});
</script>
<div class="container">
<div class="band">
<h1>Anagram Finder</h1>
</div>
<form id="anagram">
<div class="form-group">
<label for="word">Your Word</label>
<input id="word" type="text">
</div>
<button type="submit" class="btn">Find!</button>
</form>
<div id="resulttext">
</div>
</div>
</body>
</html>
Related
I am trying to create a program that takes a user's input from the html and runs it through a for loop, and then displays the translated input. The problem is that the output just displays undefined. The function that translates the user's input in the inputbox is supposed to be called with the button in the html, but clicking it changes nothing, and the output just stays "undefined"
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
console.log(resultArray.join('').toUpperCase());
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = resultArray.join('').toUpperCase();
console.log(resultArray);
}
function translateInput() {
let userInput = document.getElementById('input').value
let translateResult = whaleTalk(userInput);
updateOutput(translateResult);
}
function updateOutput(input) {
document.getElementById('output').innerHTML = input;
}
whaleTalk();
updateOutput();
<!DOCTYPE html>
<head>
<title>Whale Talk Translator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="whaletranslator.css" rel="stylesheet" type="text/css" />
<style>
</style>
</head>
<body>
<header style="color: white;">Whale Talk Translator </header>
<h2>Input anything you want into the box below and hit the button to translate it.</h1>
<div class="translatorBox">
<input value="" id="input" type="text" class="inputBox" placeholder="Text to translate">
<br>
<div class="container">
<div class="center">
<button class="translateButton" onclick="updateOutput()">Translate</button>
</div>
</div>
<div class="container">
<div class="center">
<button class="reloadButton" onClick="window.location.reload();">Reload</button>
</div>
</div>
</div>
<p style="padding: 2em">Translated input:</p>
<div class="output">
<p id="output"></p>
</body>
<script src="whaletranslator.js" type="text/javascript"></script>
</html>
Your function returns undefined because you are not returning anything from it. Try this:
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
return resultsArray.join('').toUpperCase()
}
Now when your translationResult variable will be the string that your updateOutput method will set to the innerHtml of the element with id 'output'. Instead of calling the two methods at the bottom you can now just call translateInput()
You haven't satisfied the argument for the method updateOutput, the "undefined" message is caused because the argument is not defined in your call
I am trying to do an assignment where it makes random lotto numbers. I have it all built out, but when I put the first value in and it runs it will post to the HTML. Then doing a second value will concatenate to the first instead of clearing. I've tried .reset and value = "" but I must be doing something wrong. I tried searching the old posts, but couldn't find anything as I wasn't sure exactly what the problem was.
var buttons = document.getElementById("create");
var numbers = [];
var shownSelection = ""
function makeIt() {
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
You should initialize your 'shownSelection' variable inside the function so it will be empty each time you press the button:
var buttons = document.getElementById("create");
var numbers = [];
function makeIt() {
var shownSelection = ""
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
This is the Javascript that turns on Georgian keyboard in every input and textarea field
But I have one input field with ID user_login which type is text and of course, this javascript takes effect on this field too
I simply want to disable the effect of this javascript only for this field which ID is user_login
Please help me
thank you in advance
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
<script type="text/javascript" src="/js/jquery_min.js"></script>
<script type="text/javascript" src="jquery.geokbd.js"></script>
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
<script>
$('#kbd-switcher').geokbd();
</script>
</body>
</html>
and code
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
this.each(function() {
var $this = $(this);
if ($this.is(':text, textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find(':text, textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $(':text, textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
}(jQuery));
If you call your plugin on the form element, instead of the checkbox and then search the document for all desired element types except the one with the id of user_login, your inputs JQuery wrapper will only contain the elements you want.
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
// Using the standard DOM API, search the document for all `input` and
// 'textarea' elements, except for the one with an id of: "user_login"
document.querySelectorAll("input:not(#user_login), textarea").forEach(function(item) {
var $this = $(item);
// You had the selector for an input incorrect
if ($this.is('input[type="text"], textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find('input[type="text"], textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $('input[type="text"], textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
$('form').geokbd();
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
</body>
</html>
I'm probably being very stupid here...
I have two JavaScript functions that are practically identical except each one refers to a different element.
The idea is to show and hide a toast/notification when the document loads.
For one element (errorexplanationcontainer), it works... For the other (alert), it doesn't...
CODE FOR errorexplanationcontainer (WORKS)
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
^^ This is copied and pasted from the inspect window within Google Chrome. As you can see, the script ran successfully. We know this because class="" is absent in the source document and has been added by the script (after showing class="show" for 3 seconds).
CODE FOR alert (DOESN'T WORK)
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
^^ No class="" here! The script has not worked...
FULL HTML DOC
<html class="mdl-js"><head>
<title>Dennis' Coffee Hut | CuppaDesk</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="/assets/favicon-16x16-347e46971826b54de74f354ae410242483f471bb3051a5f948d83af70770dadc.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicon-32x32-ac516884b2aa2ea870ddfbd0ae383c0dd66ec1a640181174ac7adaba8e7ccd7d.png" sizes="32x32">
<link rel="apple-touch-icon" type="image/x-icon" href="/assets/apple-touch-icon-af3f73bee131a689a15fede0d2d6f7cf9698786524670279ac74cd128ec5dc40.png" sizes="180x180">
<link rel="mask-icon" type="image/x-icon" href="/assets/safari-pinned-tab-4f97411db829aebf4a4796a8f216e788ba4eeddf4d062a0a1efe473ee10fce3b.svg" color="#99cc33">
<link rel="icon" type="image/png" href="/assets/android-chrome-192x192-cb0ced957daf2743c293b898f5e595fcf07fc0842b9d0aeef37c08b8c5f74d42.png" sizes="192x192">
<link rel="manifest" href="/manifest.json">
<meta name="apple-mobile-web-app-title" content="CuppaDesk">
<meta name="application-name" content="CuppaDesk">
<meta name="msapplication-TileColor" content="#99cc33">
<meta name="msapplication-TileImage" content="/assets/mstile-144x144-5de954b6d137b31283af01b9a7645c90440392de2b44ec88949fdba65cca75e7.png">
<meta name="theme-color" content="#99cc33">
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<link rel="stylesheet" media="all" href="/assets/main.self-b06bcba5344c9fc9a5c6491a38f0780f4594d723339bc0543a25138d83fe3de3.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/places.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-f0d704deea029cf000697e2c0181ec173a1b474645466ed843eb5ee7bb215794.css?body=1" data-turbolinks-track="reload">
<script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/places.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-eba3cb53a585a0960ade5a8cb94253892706bb20e3f12097a13463b1f12a4528.js?body=1" data-turbolinks-track="reload"></script>
<!-- BEGIN MATERIAL DESIGN LITE -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- <link rel="stylesheet" href="/material.min.css"> -->
<script defer="" src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<!-- END MATERIAL DESIGN LITE -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
<div id="login-container">
<div id="cuppadesk-logo-large"></div>
<div id="card-white">
<h1>Log in</h1>
<div class="dropdown-dots">
<button onclick="dotsDropdown()" class="dropbtn-dots"></button>
<div id="dotsDropdown" class="dropdown-content">
<a href="/users/sign_up">
<div class="dropdown-content-item">Sign up</div>
</a>
<a href="/users/password/new">
<div class="dropdown-content-item">Forgot password</div>
</a>
<a href="/users/confirmation/new">
<div class="dropdown-content-item">Didn't recieve email confirmation</div>
</a>
<a href="/users/unlock/new">
<div class="dropdown-content-item">Didn't receive unlock instructions</div>
</a>
<a href="/users/auth/facebook">
<div class="dropdown-content-item">Log in with
Facebook
</div>
</a>
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dotsDropdown() {
document.getElementById("dotsDropdown").classList.toggle("show-dots");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn-dots')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show-dots')) {
openDropdown.classList.remove('show-dots');
}
}
}
}
</script>
<form class="new_user" id="new_user" action="/users/sign_in" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
<div class="field-white">
<input autofocus="autofocus" placeholder="Email" type="email" value="" name="user[email]" id="user_email">
</div>
<div class="field-white">
<input autocomplete="off" placeholder="Password" type="password" name="user[password]" id="user_password">
</div>
<div class="checkbox">
<input name="user[remember_me]" type="hidden" value="0"><input class="css-checkbox" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me">
<label class="css-label clr" for="user_remember_me">Remember me</label>
</div>
<script>
// generic tools to help with the custom checkbox
function UTIL() { }
UTIL.prototype.bind_onclick = function(o, f) { // chain object onclick event to preserve prior statements (like jquery bind)
var prev = o.onclick;
if (typeof o.onclick != 'function') o.onclick = f;
else o.onclick = function() { if (prev) { prev(); } f(); };
};
UTIL.prototype.bind_onload = function(f) { // chain window onload event to preserve prior statements (like jquery bind)
var prev = window.onload;
if (typeof window.onload != 'function') window.onload = f;
else window.onload = function() { if (prev) { prev(); } f(); };
};
// generic css class style match functions similar to jquery
UTIL.prototype.trim = function(h) {
return h.replace(/^\s+|\s+$/g,'');
};
UTIL.prototype.sregex = function(n) {
return new RegExp('(?:^|\\s+)' + n + '(?:\\s+|$)');
};
UTIL.prototype.hasClass = function(o, n) {
var r = this.sregex(n);
return r.test(o.className);
};
UTIL.prototype.addClass = function(o, n) {
if (!this.hasClass(o, n))
o.className = this.trim(o.className + ' ' + n);
};
UTIL.prototype.removeClass = function(o, n) {
var r = this.sregex(n);
o.className = o.className.replace(r, '');
o.className = this.trim(o.className);
};
var U = new UTIL();
function getElementsByClassSpecial(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
// specific to customized checkbox
function chk_labels(obj, init) {
var objs = document.getElementsByTagName('LABEL');
for (var i = 0; i < objs.length; i++) {
if (objs[i].htmlFor == obj.id) {
if (!init) { // cycle through each label belonging to checkbox
if (!U.hasClass(objs[i], 'chk')) { // adjust class of label to checked style, set checked
if (obj.type.toLowerCase() == 'radio') {
var radGroup = objs[i].className;
var res = radGroup.split(" ");
var newRes = res[0] + " " + res[1];
var relLabels = getElementsByClassSpecial(document.body,newRes);
for (var r = 0; r < relLabels.length; r++) {
U.removeClass(relLabels[r], 'chk');
U.addClass(relLabels[r], 'clr');
}
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
else {
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
} else { // adjust class of label to unchecked style, clear checked
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr');
obj.checked = false;
}
return true;
} else { // initialize on page load
if (obj.checked) { // adjust class of label to checked style
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
} else { // adjust class of label to unchecked style
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr')
}
}
}
}
}
function chk_events(init) {
var objs = document.getElementsByTagName('INPUT');
if (typeof init == 'undefined') init = false;
else init = init ? true : false;
for(var i = 0; i < objs.length; i++) {
if (objs[i].type.toLowerCase() == 'checkbox' || objs[i].type.toLowerCase() == 'radio' ) {
if (!init) {
U.bind_onclick(objs[i], function() {
chk_labels(this, init); // bind checkbox click event handler
});
}
else chk_labels(objs[i], init); // initialize state of checkbox onload
}
}
}
U.bind_onload(function() { // bind window onload event
chk_events(false); // bind click event handler to all checkboxes
chk_events(true); // initialize
});
</script>
<div class="green-submit">
<input type="submit" name="commit" value="Log in" data-disable-with="Log in">
</div>
</form>
</div>
</div>
</body></html>
Again, I'm probably missing something obvious here... I'm completely new to developing and JavaScript is something I particularly struggle with. I've read through many resources but in my mind, the code still looks correct...
Obviously, I'm wrong... So any help will be greatly appreciated!
Use window.addEventListener instead of overwriting window.onload.
For errorexplanationcontainer,
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.addEventListener("load", function() {
var z = document.getElementById("errorexplanationcontainer");
z.className = "show";
setTimeout(function() {
z.className = z.className.replace("show", "");
}, 3000);
}, false);
</script>
For alert,
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.addEventListener("load", function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function() {
y.className = y.className.replace("show", "");
}, 3000);
}, false);
</script>
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>');
}