JavaScript with jQuery script not loading - javascript

My script with jQuery isn't loading, and when I press the calculate button it doesn't nothing (unsurprisingly.) I KNOW I copied and pasted jQuery in hard code into the file; this is intentional as I want the file to run offline as that's when I normally run it. Also it's intentional that I created the personal console as I normally work on this on a school laptop because that's when I'm bored and they've disabled the developer console.
It's not the jQuery that isn't loading though; I've been able to run it before.
I've tried checking the code, but to me it's just broken. Before the script didn't load, however, I think that somewhere there's an infinite loop because according to task manager, when the script loads and a calculate button is pressed the page freezes but the CPU is running like crazy. I have no idea what could be causing all of this, please help!
I know that other people have probably already done this and that there's probably many other better ways to do what I want to do, so just please remember that I'm doing this for fun, but I've been going at this in my spare time for quite a while an I haven't found anything so either I'm really dumb or the code is broken and it needs a rewrite.
It's supposed to increase the limit of the maximum number a language can understand by pushing the limit from something like 54 billion to 54 billion digits long. However, as stated in the summery, the script doesn't load.
<span id="console"></span>
<form>
<input type="radio" id="add" name="mathtype" checked="checked"> Addition (in devolopment)<br>
<input type="radio" id="sub" name="mathtype"> Subtraction (Unavailible)<br>
<input type="radio" id="multi" name="mathtype"> Multiplication (Unavailible)<br>
<input type="radio" id="div" name="mathtype"> Division (Unavailible)
</form>
<br>
Number: <input type="text" id="input1">
<br>
Number: <input type="text" id="input2">
<br>
<span id="extraInputs"></span>
<button id="addInput">Add another input field</button>
<br>
<button id="calc">Calculate...</button>
<br>
<br>
<p id="output">Press "Calculate..."</p>
<script>/*This is where I load the jQuery*/</script>
<script>
document.getElementById("console").innerHTML("<div class='info'>Script ran</div>");
"use strict";
$(document).ready(function(){
try {
var page = $("#console");
var log = function(message) {
page.append('<div class="log">'+message+'</div>');
};
var info = function(message) {
page.append('<div class="info">'+message+'</div>');
};
var warn = function(message) {
page.append('<div class="warn">'+message+'</div>');
};
var error = function(message) {
page.append('<div class="error">'+message+'</div>');
};
log("Doc and console up");
} catch(err) {
document.getElementById("console").innerHTML("<div class='error'>ERROR WITH LAUNCHING CONSOLE.</div>");
}
try {
var inputBoxes = 2;
var add = function(num1, num2) {
log("Running add");
var neg = [0, false, false];
num1 = num1.split("-");
num2 = num2.split("-");
log(num1);
log(num2);
if(num1.length == 2) {
num1 = num1[1];
neg[1] = true;
} else {
num1 = num1.toString();
}
if (num2.length == 2) {
num2 = num2[1];
neg[2] = true;
} else {
num2 = num2.toString();
}
log(num1);
log(num2);
info(neg);
var isNeg = false;
if(((neg[1] || neg[2]) && (neg[1]!=neg[2])) == true) {
isNeg = true;
}
log(neg);
num1 = num1.split('');
num2 = num2.split('');
log(num1);
log(num2);
var maxChar = Math.max(num1.length, num2.length);
log(maxChar);
if(maxChar > num1.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num1.unshift("0");
}
} else if (maxChar > num2.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num2.unshift("0");
}
}
var final = [];
var time;
var carry = 0;
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
final[i] = (parseInt(num1[i]) + parseInt(num2[i]) + parseInt(carry)).toString();
if(parseInt(final[i]) > 9) {
var temp = final[i].split('');
final[i] = temp[1];
carry = temp[0];
time = i;
}
}
if(isNeg){
final.unshift("-");
}
info(final.join());
return final.join();
};
$("button#addInput").click(function(){
inputBoxes++;
$("#extraInputs").append('Number: <input type="text" id="input'+inputBoxes+'"><br>');
});
$("#calc").click(function(){
info("Checking conditions...");
if ($("#add").is(":checked")) {
info("Running...");
info($("#input1").val());
info($("#input2").val());
var final = add($("#input1").val(), $("#input2").val());
info("Ran");
if (inputBoxes > 2) {
info("inputBoxes: "+inputBoxes.toString());
for (var i=3; i<inputBoxes; i++) {
final = add(final, $("#input"+i.toString()).val());
}
}
info(final);
$("#output").text(final));
}
log("Functions up");
});
} catch(err) {
error(err);
}
});
</script>
It should take any amount of numbers and add them (as well as other things eventually), as long as the result's number of characters is less than or equal to the biggest number the language can understand.

I don't know what your code does, but you definitely have an infinite loop here:
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
At each iteration, the for loop will decrease i by 1, but you are also increasing it by one, so it will keep the same value and the loop never ends. I imagine you actually wanted to check if (time != i+1).

Related

Trying to create a random game but doesn't seem to work

Under my form action, I called the textbox and buttons. It was suppose for the user to key in 2 values one being the highest value and another being the lowest value, it will then generate a random value between the lowest and the highest. The user will than guess the number if its correct it will print out the message correct
<form action="random" method="get" onSubmit="return validate()">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<br/><span id="numbers1"></span>
<br/><input id="rand" type="submit" value="submit" onclick="Random()"><br/>
<input id="guess" type="text" value="Random Number Generator">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</form>
My script consist of the methods and functions to use, I think the problem lies at the RandomNumber() function, im not sure where did I go wrong, but please assist me
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
This is the function to generate a random number in between the lowest number and the highest number.
function Random()
{
var value1 = document.getElementById("digit").value;
var value2 = document.getElementById("digit1").value;
minvalue= Math.ceil(value1);
maxvalue= Math.floor(value2);
var random = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
document.getElementById("guess").value=random;
}
And this is the part where I assume it may have cause the entire program to stop working, its after I wrote down this codes and my web page doesn't perform the way I want it to be.
function RandomNumber()
{
var value3 = document.getElementById("digit").value;
var value4 = document.getElementById("digit1").value;
minvalue= Math.ceil(value3);
maxvalue= Math.floor(value4);
var random1 = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
var maxtries=5;
var counter=0;
var true=document.getElementById("textbox").value;
while(true!=random1)
{
document.getElementById("total").value=total;
counter +=1;
if(counter>maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
if(true==random1)
{
document.getElementById("correct").innerHTML="Correct"
}
}
}
When I look at your code I see a couple of red flags.
E.g. true is a reserved keywoard in JS, you can't assign a value to it:
var true=document.getElementById("textbox").value;
This must throw an error in your development console.
Also in your loop while(true!=random1) neither true or random1 are reassigned, so if true in the beginning, the condition will never become false, hence the loop is never left in this case!
In general you should try to narrow your issue down, look at the errors and rather ask for help on smaller snippets where you ask concrete questions. With a statement like my web page doesn't perform the way I want it to be it is hard to provide help.

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

How do I (1) Create A Randomly Generated Email in Javascript (2) Auto fill a form with it

and thanks for taking time to at least pity my lack of knowledge.
I have a wordpress installation (stay with me..) that has a plugin where you enter some information including an email, in order to add, in this instance a new booking (crm type thing). This is done in the back end by admin. On some occasions, the client doesn't have an email address and as a hacky workaround i'd like the system to just generate a random email address in the box whenever it's left empty.
Much of the plugin is in Javascript and i think i've found the validation function where my snippet might need 'injecting':
(1)
I'm fairly comfortable with PHP, and have written something that generates a random email (which will only be used internally)
//Random email address generator
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$randomString .= "#mysite.co.uk";
return $randomString;
}
(yes I know, there are a million neater ways to accomplish the above)
(2) I think i've found the bit of javascript that validates the email input and was just hoping this may be the chunk of code i'd need to look at in order to generate a random email, if nothing else was entered.
function sln_validateBooking() {
var $ = jQuery;
$('.sln-invalid').removeClass('sln-invalid');
$('.sln-error').remove();
var hasErrors = false;
var toValidate = [
'#_sln_booking_service_select'
];
var fields = $('#salon-step-date').attr('data-required_user_fields').split(',');
$.each(fields, function(k, val) {
toValidate.push('#_sln_booking_' + val);
});
$.each(toValidate, function (k, val) {
if (val == '#_sln_booking_phone' && !$('[name=_sln_booking_createuser]').is(':checked')) {
return;
} else if (val == '#_sln_booking_email') {
if (!$('[name=_sln_booking_createuser]').is(':checked') && !$(val).val()) {
return;
} else if (!sln_validateEmail($(val).val())) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is not a valid email</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
} else if (val == '#_sln_booking_service_select') {
if (!$('[name=_sln_booking\\[services\\]\\[\\]]').size()) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is required</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
} else if (!$(val).val()) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is required</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
});
return !hasErrors;
}
What would be great to know is a) if i should just shoot myself in the face and never go near a line of code again and also b) if there is a neat solution to this that I may forever be in your debt for solving.
UPDATE:
I've decided it would probably be better to pass this randomly generated email address to the empty field via a metabox, and not to hack at the plugin's code (which would only get overwritten)..
However.. I get 'uncaught referenceError : rand is not defined at HTMLinputelement.onclick for both functions if i do something like this:
<input type="text" id="txt_name" placeholder="click to generate" value="" />
<br/>
<input type="button" class="button button-primary button-large" id="btn_Gen"
onclick="rand();" value="Generate" />
<br/>
<input type="button" class="button button-primary button-large" id="btn_Run"
onclick="fn_copy();" value="Autofill" />
<br/>
<script>
function rand() {
document.getElementById("txt_name").value = generateRandStr();
}
function generateRandStr() {
var candidates = "ABCDEFGHIJKLMNOPQRSTUVWXY123456789";
var randomemail = "",
rand;
for (var i = 0; i < 1; i++) {
for (var j = 0; j < 8; j++) {
rand = Math.floor(Math.random() * candidates.length);
randomemail += candidates.charAt(rand);
}
randomemail += "#blahblah.co.uk";
}
return randomemail;
}
//working
function fn_copy() {
var temp = document.getElementById("txt_name").value;
if (temp != "") {
document.getElementById("_sln_booking_email").value = temp;
} else
alert("Text is Empty");
}
</script>
HELP!
After this line
} else if (!sln_validateEmail($(val).val())) {
remove all the code that notifies the user of invalid input and set the value to your random email.
} else if (!sln_validateEmail($(val).val())) {
$(val).val(Math.random().toString(36).substring(5) + "#mysite.co.uk")
}
I'm not sure you want to lean on that Math.random call to make billions of unique emails but it might get you by.

Javascript - simple counting

This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>

Javascript if statement doesn't work as expected

I'm trying to create a small survey with a score. I want to make it so once user reaches score "4", it alerts some message. I wrote if statment for it, but for some reason it never alerts. But if I manually change score variable to 4, everything works as expected.
Where am I going wrong?
Here's the code:
http://jsfiddle.net/uy9kq9mx/
<script>
var score = 0;
function checkQuestionOne (){
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if(jautViens.checked) {
alert(++score)
}else if(jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
}else{
alert("Izvēlies opciju!")
}
}
if (score == 4){
alert(score);
}else{
}
You need to check the condition if the function
var score = 0;
function checkQuestionOne() {
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if (jautViens.checked) {
++score;
//since value of score is changed only in this block you can place the if block here
if (score == 4) {
alert('score is 4');
}
} else if (jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
} else {
alert("Izvēlies opciju!")
}
//keep the if block here, if there are multiple blocks in which the value of score is changed
}
<h1>Pirmais jautājums (1. pareizā)</h1>
<input type="radio" name="jaut1" id="jaut1Pirm" value="pirma" />Šī ir pirmā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Otra" value="otra" />Šī ir otrā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Tres" value="tresa" />Šī ir trešā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Cetu" value="ceturta" />Šī ir ceturtā atbilde
<br/>
<br/>
<button type="submit" onclick="checkQuestionOne();">Spied</button>
When you keep it outside of the function, the if condition is evaluated only once, but you need to check it everytime the value of score is changed.

Categories

Resources