If statement with OR condition not working - javascript

I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>

Related

Can't get this javascript (Luhn Algorithm) to work in this perl CGI file

I have a shopping cart that doesn't validate cards and I'm getting a lot of declined orders because people don't catch their typos. Trying to add Luhn validation to it.
I found this script which works fine by itself. It on-the-fly changes invalid to valid when a "good" credit card number is typed in.
<input id="cc" type="text" name="creditcard" size="20"><p id="status">invalid</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#cc').on('input', function(){
if (checkLuhn($('#cc').val())) {
$('#status').html('valid');
} else {
$('#status').html('invalid');
}
});
function checkLuhn(value) {
// remove all non digit characters
var value = value.replace(/\D/g, '');
var sum = 0;
var shouldDouble = false;
// loop through values starting at the rightmost side
for (var i = value.length - 1; i >= 0; i--) {
var digit = parseInt(value.charAt(i));
if (shouldDouble) {
if ((digit *= 2) > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) == 0;
}
</script>
I'm trying to insert it into the HTML portion of the CGI file, below this relevant line and giving the INPUT the id="cc" tag, but the script won't run.
<INPUT TYPE="text" id="cc" NAME="Payment_Card_Number" MAXLENGTH="20" size="20" value="$form_data{'Payment_Card_Number'}">

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

How to find prime numbers in entered number range [duplicate]

This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I'm just trying to find prime numbers of an entered range of numbers. I have no clue how to calculate finding primes. I need to add them to an array and output the array after. I put a placeholder for the calculation... I just can't seem to figure out how find the primes.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = document.numbers.firstNum.value;
var endNum = document.numbers.secondNum.value;
var primeNumbs = new Array();
var ctr = 0;
while (beginNum <= endNum){ //throwaway
if ((beginNum % beginNum == 0) && (beginNum % 1 == 0)){
primeNumbs[ctr] = beginNum;
++ctr;
}
++beginNum;
}
if (primeNumbs == 0){
window.alert("There were no leap years within the range.");
}
else {
outputPrimeNums(primeNumbs);
}
}
function outputPrimeNums(primes){
document.write("<h2>Prime Numbers</h2>");
for (i=0;i<primes.length;i++){
document.write(primes[i] + "<br/>");
}
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
</body>
</html>
try this full page of prime no example
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = parseInt(document.numbers.firstNum.value);
var endNum = parseInt(document.numbers.secondNum.value);
var primeNumbs = new Array();
var ctr = beginNum;
while(ctr<=endNum)
{
if(isPrime(ctr)==true)
{
primeNumbs[primeNumbs.length] = ctr;
}
ctr = ctr+1;
}
if (primeNumbs.length == 0){
document.getElementById('output_content').innerHTML = "There were no prime no within the range.";
}
else {
outputPrimeNums(primeNumbs);
}
}
function isPrime(num)
{
var flag = true;
for(var i=2; i<=Math.ceil(num/2); i++)
{
if((num%i)==0)
{
flag = false;
break;
}
}
return flag;
}
function outputPrimeNums(primes){
var html = "<h2>Prime Numbers</h2>";
for (i=0;i<primes.length;i++){
html += primes[i] + "<br/>";
}
document.getElementById('output_content').innerHTML = html;
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
<div id="output_content">
</div>
</body>
</html>
You should use some algorithm to check whether a given no is prime no or not inside while loop .
http://en.wikipedia.org/wiki/Prime_number
http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_Algorithms
You need two loops here - the first to run between beginNum and endNum and the second to run from 1 to beginNum for each value of beginNum in the outer loop.
Try replacing the main section of your code with the following. (For clarity, I'm going to introduce a new variable - numberBeingTested.)
var ctr = 0;
var numberBeingTested = beginNum;
while (numberBeingTested <= endNum){ //throwaway
var testDivisor = 2;
var isPrime = true;
while (testDivisor < numberBeingTested ){ //throwaway
if (numberBeingTested % testDivisor == 0) {
isPrime = false;
}
++testDivisor;
}
if (isPrime){
primeNumbs[ctr] = numberBeingTested;
++ctr;
}
++numberBeingTested;
}
Note that there are many possible improvements here - for a start, this code as it stands will tell you that 1 is prime, and there are significant possible performance improvements (such as testing possible divisors up to the square root of the number being tested rather than the number itself) - but for your purposes it will probably suffice.
What I try was to edit Sieve of Atkin algorithm from linked question:
function getPrimes(min, max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
if (i >= min) {
primes.push(i);
}
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
console.log(getPrimes(10, 100));
This will give you array with prime numbers from min to max. It still has to go through all number from 2, so maybe there will be more effective way how to achieve this.

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Prototype issue - How do I check for links on an input field and check for the length of that input field?

I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0

Categories