function is not working in my code - javascript

my problem is that text3 is undefined in my codes in here:
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
but it is here:
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
here is all of my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
</script>
</body>
</html>
what is the problem?
please help

Looks like $('#x').keyup() is being called before $('#pass').keyup()

Your call $('#x').keyup(function (e) { is creating the first event listener so on keyup you will always endup with text3 is undefined because the $('#pass').keyup(function (e) { will be triggered always later.
EDIT:
Your second keyup handler will never work because it will grab the #pass element only once (during document parse). You need to create some defered listener to fix it.
// Anyway this won't fix your text3 is undefined problem.
What you need to do is define it first before the two .keyup handlers.
NOTE:
But please avoid setting global variables anyway ;)
Put everything into a closure or something.
Last but not least DO NOT create many elements with the same ID this is a major bug.

Look, even after fixing the code to get it to work it makes very little sense. Using roryok's jsFiddle, it'll only work if the value you're entering is a number and doing so just spawns the paragraph elements for the number you entered. You can enter as many numbers as you'd like (before your browser crashes), it'll always return as "weak".
If it's a simple password strength meter you're after, unless you can explain the logic you're trying to achieve more by forcing it to stick to numbers, I'd dump most of the JavaScript code and reduce it to
$('#x').keyup(function (e) {
document.getElementById("passdiv").innerHTML = strength($(this).val());
return true;
});
function strength(val) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test(val)) {
t = "strong";
} else if (normal.test(val)) {
t = "normal";
} else {
t = "weak";
}
return t;
}
This will then validate the whole input each time you enter a character, which the user can then submit once it's "strong".
Here's my jsFiddle: http://jsfiddle.net/xqooj482/

text3 is not set as a variable in your code, therefore it's always going to be undefined. You need to set it before your two functions.
Note: I also put things inside a jQuery ready function.
For some reason I'm being downvoted, but I tested this and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// set text3 in here first
var text3 = "";
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
});
</script>
</body>
</html>
Also here's a fiddle of it working
http://jsfiddle.net/gsuy4t27/

Related

How do i remove a calculator from a bot? (its connected to the enter button)

I need to remove the calculator, without removing the function of allowing it to print, I have tried switching things around, and removing things, but still when I type in a number, such as 67, it comes out as 67=67, or more complicated math equations, it dosent except things like PI, this is because it thinks it's some symbol, not a character. The only things that do work are: / = + - /, it dosent accept cubed or squared, or to the power of X
Bot code:
<html>
<body>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<div id="stretchbox" style = "position:fixed; left:80px;">
<input type="text" placeholder="Coin ID #"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false">
</input>
</div>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
var trigger = [
["25184"],
["27123"],
["26124"],
["17453"]
];
var reply = [
["Coin Bot - "],
["Tokyn Blast - "],
["Iron Wolf - "],
["Foxyville - "],
];
var alternative = ["I cant find that Coin ID # right now, make sure that the Coin ID # exist!"];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'You';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/!/g, "!").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
</script>
</body>

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

Loop for issue javascript won't run

So this exercice is about outputing a word by the number typed in the input section simple but i find this problem the loop for won't work if there is any help i will be greatfull
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script defer>
function Verifer() {
var ch = document.querySelector("input").value
var nbr = document.getElementById("nb").value
if ((nbr > 0) && (ch != "")) {
for (let i = 1; i >= nbr; i++) {
var txt = ""
txt += "<h1>" + ch + "</h1> <br>"
document.getElementById("d2").innerHTML = txt
}
} else {
alert("Retype plz")
}
}
</script>
</head>
<body>
// the first input is to type a String //the seconde input to type the number of repetition of this String
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
//This part is dedicated to the output of the function
</div>
</body>
change
var nbr = document.getElementById("nb").value
to
var nbr = parseInt(document.getElementById("nb").value)
Is this what you want to do? Your question is a bit vague.
function Verifer() {
var ch = document.querySelector("input").value;
var nbr = document.getElementById("nb").value;
nbr = parseInt(nbr); //Parse to int
console.log(nbr);
if (nbr === NaN || !ch) { //Validate
document.getElementById("nb").value = "invalid";
return;
}
var txt = ""; //Set var in scope around for loop
for (var i = 1; i <= nbr; i++) { //repeat when i is less or equal to nbr
txt += "<h1>" + ch + "</h1> <br>" //Append txt
}
document.getElementById("d2").innerHTML = txt; //Add txt to element html
}
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
</div>

JavaScript: Function that accepts message and replaces specific characters to line of code?

I have a chat application on Node.js, I just made smileys for it.
How can I scan/replace all sets of characters in messages to line of code? (image)
here is the message being added to chat window.
$("#chatEntries").append('<div class="messagesOLD">' +
"<span class='msg_date'>"+dateFormat(time)+"</span><span class='msg_seperator'> | </span><span class='msg_name'>"+ pseudo + '</span> : ' + replaceEmoticons(msg) + '</div>');
msg is actual message, and replaceEmoticons is function name but it's blank for now as I don't know how to implement it.
Here are my smileys:
var smileys = [];
smileys[":/"] = "derp.png";
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";
The array/object names are the actual char sets I want to be replaced in message.
All smileys are located like: http://example.com/public/images/smileys/
In the end I want all messages to look like:
Hello how are you all doing today? :D
would become:
Hello how are you all doing today? <img src='http://example.com/public/images/smileys/laugh.png' id='chat_smls'/>
Update:
It needs to replace only character sets when there is space before and after them.
So:
Hello:D = Not valid. Hello:DHow = Not Valid Hello :DHow = Not Valid Hello :D How = Valid.
Simply call replace :
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "(?=$|\\s)", 'g');
str = str.replace(re, "<img src='http://example.com/public/images/smileys/" + smileys[key] + "' id='chat_smls'/>");
}
return (str);
}
Here is a demo :
var smileys = [];
smileys[":/"] = "derp.png";
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";
function RegExpEscape(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
str = str.replace(re, "<img src='http://example.com/public/images/smileys/" + smileys[key] + "' id='chat_smls'/>");
}
return (str);
}
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
update();
function update() {
$('#result').text(replaceEmoticons($('#input').val()));
}
$('#input').keyup(function () {
delay(update, 250);
});
textarea
{
width: 100%;
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Input :</h4>
<textarea id="input">
Hello how are you all doing today? :D
</textarea>
<hr>
<h4>Result :</h4>
<textarea id="result">
</textarea>
Edited to fulfill requirements

Javascript 2 clicks onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Use javascripts' setTimeout( function() {})
You could do something like this (sudo code below. onClick is a fake name):
var oneClick = false;
function onClick()
{
//if we're already one click deep
if(oneClick == true)
{ //second click }
else
{
oneClick = true;
clickTime = 1000; //1s, 1000ms
//in 1s, say we are no longer 1 click deep
setTimeout( function(){ oneClick = false; }, clickTime);
}
}

Categories

Resources