I'm extremely new to JavaScript and HTML so go easy on me. I'm attempting to call a function from my external JavaScript file in my HTML file, but nothing I seem to do allows it to work.
JavaScript Code
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength = false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x <= passlength;){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<script type="text/javascript" src="PassGen.js"></script>
<script>
var x = prompt("Enter password length: ")
function generatePassword(x);
</script>
</body>
</html>
The goal is for the user to be prompted to input a password length, then generate a random password which will be alerted to the user and written on screen. However, only the header at the top of the screen is printed.
(I realize that I could just take the function out of the JavaScript file and run it normally, but I kinda wanna leave it like this so I know what to do in the future if I ever run into this situation again.)
Following is the code with Javascript inside <script> tag within HTML document. One thing you should be careful of while writing your javascript code in the HTML file is, to include your javascript code just before the ending tag of body </body>. so it get executed only when your html file is loaded. But if you add your javascript code in the starting ot html file, your JS code will be executed before the file is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
<script>
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
</script>
</body>
</html>
And if you want to have your Javascript code in a separate file, which can be helpful in big programs, then you need to reference that file using <script> tag and this is the way you write it down.
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
<script src=""></script>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
</body>
</html>
In your code there are the following problems :
1) Change function generatePassword(x); to generatePassword(x.length);
2) Change trueLength = false to trueLength === false
3) Change for(var x = 0; x <= passlength;){ to for(var x = 0; x < passLength; x++){
passlength => passLength , x<= to x< , insert x++
4) Change Math.floor(Math.random()*things.length+1); to Math.floor(Math.random()*(things.length)+1)
5) insert passLength = passLength.length; to else
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
var x = prompt("Enter password length: ")
generatePassword(x.length);
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
passLength = passLength.length;
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x < passLength; x++){
var randomNum=Math.floor(Math.random()*(things.length)+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
You can use this code with less complexity :
var trueLength = false, password = "" ;
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var x = prompt("Enter password length: ")
generatePassword(x);
var input = document.getElementById("len");
function generatePassword(passLength){
while ( passLength.length < 9 )
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
for ( var x = 0; x < passLength.length ; x++ ) {
var randomNum = Math.floor ( Math.random() * (things.length)+1 );
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
Few things. In order to have something show up in HTML, you will need to select an HTML element in JavaScript. Next, you used 'passlength' instead of 'passLength' in the for loop. Third, when you write function generatepassword it is invalid syntax as Lux said. Lastly, your for loop doesn't go anywhere because you don't have a third expression. Which should be changed to
for(var x = 0; x <= passLength;x++)
Edit: Another thing I forgot was trueLength = false should be changed to trueLength == false or trueLength === false.
With all that said, here's my solution:
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<p align="center"></p>
<!--script type="text/javascript" src="PassGen.js"></script-->
<script>
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
//var input = document.getElementById("len");
var ppass = document.querySelector("p");
function generatePassword(passLength){
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
for(var x = 0; x <= passLength;x++){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
//alert("Your password is: " + password);
//document.write("<h1>Your Password</h1><p>" + password + "</p>");
ppass.textContent = password;}
var x = prompt("Enter password length: ")
generatePassword(x);
</script>
</body>
</html>
What I added was a <p> tag to display the password once it's generated. I use textContent to display it once the password is done generating. And i use document.querySelector to access it.
Related
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="assets\css\style.css" />
</head>
<body>
<div class="wrapper">
<!-- || HEADER || -->
<header>
<h1>Password Generator</h1>
</header>
<!-- || CONTENT || -->
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
<button id="copy" class="btn-copy">Copy to Clipboard</button>
</div>
</div>
</div>
<!-- || JAVASCRIPT STYLE SHEET || -->
<script src="assets\js\script.js"></script>
</body>
</html>
---- || JavaScript || ----
// GenerateBtn
var generateBtn = document.querySelector("#generate");
// Define variables
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Set variables
var plength = 0;
var lowerCase = "abcdefghijklmnopqrstuvwxyz";
// Uppercase conversion
var upperCase = lowerCase.toUpperCase();
var numbers = "1234567890";
var specialCharacter = "!#$%&'()*+,-./:;?#][^_`{|}~'<=>";
var userPassword = "";
var passwordGroup = "";
// Function writes password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Clicking btn runs funtion
generateBtn.addEventListener("click", writePassword);
// Request length of the password
var plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.",""));
// Require number
while (isNaN(plength)) {
var plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.",""));
}
// Require length
while (plength < 8 || plength > 128) {
var plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters",""));
}
// Confirm lower case letters
var selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
var selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
var selectNumber = confirm("Use numbers?");
//Confirm special characters
var selectSpecial = confirm("Use special characters?");
// Call function to generate password
generatePassword();
// Write generated password on page
document.getElementById("password").innerHTML = userPassword;
// From selected options randomly generate password.
function generatePassword() {
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
/* || COPY FUNCTION || */
// https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
var copy = document.querySelector("#copy");
copy.addEventListener("click", function () {
copyPassword();
});
function copyPassword() {
document.getElementById("password").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
}
What I want it to do is wait to run the prompts till after the page loads and you click the generate button. Then when clicking the generate button again I want it to clear the text area and repeat the prompts. Currently, it's asking the prompts when the page loads then running the function again with the same prompts originally chosen and adding them to the text previously in the text area.
In order to display the pop-up only when the button "Generate Password" is clicked, you should insert all the pop-ups in the writePassword function:
function writePassword() {
// Request length of the password
plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.", ""));
// Require number
while (isNaN(plength)) {
plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.", ""));
}
// Require length
while (plength < 8 || plength > 128) {
plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters", ""));
}
// Confirm lower case letters
selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
selectNumber = confirm("Use numbers?");
//Confirm special characters
selectSpecial = confirm("Use special characters?");
var password = generatePassword();
document.querySelector("#password").value = password;
}
Then, in order to clear the password area you should simply set the userPassword variable to a null string before you start generating a new password (since you append the random generated characters):
function generatePassword() {
userPassword = "";
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
This is the complete JavaScript code:
// GenerateBtn
var generateBtn = document.querySelector("#generate");
// Define variables
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Set variables
var plength = 0;
var lowerCase = "abcdefghijklmnopqrstuvwxyz";
// Uppercase conversion
var upperCase = lowerCase.toUpperCase();
var numbers = "1234567890";
var specialCharacter = "!#$%&'()*+,-./:;?#][^_`{|}~'<=>";
var userPassword = "";
var passwordGroup = "";
var plength;
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Function writes password to the #password input
function writePassword() {
// Request length of the password
plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.", ""));
// Require number
while (isNaN(plength)) {
plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.", ""));
}
// Require length
while (plength < 8 || plength > 128) {
plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters", ""));
}
// Confirm lower case letters
selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
selectNumber = confirm("Use numbers?");
//Confirm special characters
selectSpecial = confirm("Use special characters?");
var password = generatePassword();
document.querySelector("#password").value = password;
}
// Clicking btn runs funtion
generate.addEventListener("click", writePassword);
// Call function to generate password
generatePassword();
// Write generated password on page
document.getElementById("password").innerHTML = userPassword;
// From selected options randomly generate password.
function generatePassword() {
userPassword = "";
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
/* || COPY FUNCTION || */
// https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
var copy = document.querySelector("#copy");
copy.addEventListener("click", function() {
copyPassword();
});
function copyPassword() {
document.getElementById("password").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
}
Try refactoring your code
Make a separate function for all your prompts.
Call the function when the DOM is completely loaded.
And at the starting of the function always set the value of your password textarea to empty.
I'm new to coding and I can't figure out why my JS isn't generating a random password. Click ok through the prompts and you will see the issue I am having. It appears to just be pulling one of my functions in //Generator Functions. I coded the prompts to be very simple since I still don't quite know what I'm doing. I just need it to generate the password for this particular exercise. Any help is appreciated!
// Assignment Code
var generateBtn = document.querySelector("#generate");
// Special characters for the function created
const specialCharacters = "!##$%^&*()";
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
// Prompts that come up after you click generate password
function generatePassword() {
var passwordLength = prompt("Please enter the number of characters you want for you new password. It must be more than 12 but less than 128.");
var numbers = confirm("Do you want numbers in your password?");
var lowerCases = confirm("Do you want lowercases in your password?");
var upperCases = confirm("Do you want uppercases in your password?");
var special = confirm("Do you want special characters in your password?");
// this is a minimum count for numbers, lowerCases, upperCases & specialCharacters
var minimumCount = 0;
// Empty minimums for numbers, lowerCases, upperCases & specialCharacters
var minimumNumbers = "";
var minimumLowerCases = "";
var minimumUpperCases = "";
var minimumSpecialCharacters = "";
**// Generator functions**
var functionArray = [
function getNumbers() {
return String.fromCharCode(Math.floor(Math.random() * 10 + 48));
},
function getLowerCases() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 97));
},
function getUpperCases() {
return +String.fromCharCode(Math.floor(Math.random() * 26 + 65));
},
function getSpecialCharacters() {
return specialCharacters(Math.floor(Math.random() * specialCharacters.length));
}
];
// Checks to make sure user selected ok for all and uses empty minimums from above
if (numbers === true) {
minimumNumbers = functionArray[0];
minimumCount++;
}
if (lowerCases === true) {
minimumLowerCases = functionArray[1];
minimumCount++;
}
if (upperCases === true) {
minimumUpperCases = functionArray[2];
minimumCount++;
}
if (special === true) {
minimumSpecialCharacters = functionArray[3];
minimumCount++;
}
// empty string variable for the for loop below
var randomPasswordGenerated = "";
// loop getting random characters
for (let i = 0; i < (parseInt(passwordLength) - minimumCount); i++) {
var randomNumberPicked = Math.floor(Math.random() * 4);
randomPasswordGenerated += functionArray[randomNumberPicked]();
}
// to make sure characters are added to the password
randomPasswordGenerated += minimumNumbers;
randomPasswordGenerated += minimumLowerCases;
randomPasswordGenerated += minimumUpperCases;
randomPasswordGenerated += minimumSpecialCharacters;
return randomPasswordGenerated;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Firstly, I should say you have syntax error with **// Generator functions**. I have modified your codes a little bit, compare with mine...
// Special characters for the function created
const specialCharacters = "!##$%^&*()";
const generateButton = document.getElementById('generateBtn')
generateButton.addEventListener('click', writePassword)
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Prompts that come up after you click generate password
function generatePassword() {
var passwordLength = prompt("Please enter the number of characters you want for you new password. It must be more than 12 but less than 128.");
var numbers = confirm("Do you want numbers in your password?");
var lowerCases = confirm("Do you want lowercases in your password?");
var upperCases = confirm("Do you want uppercases in your password?");
var special = confirm("Do you want special characters in your password?");
// this is a minimum count for numbers, lowerCases, upperCases & specialCharacters
var minimumCount = 0;
// Empty minimums for numbers, lowerCases, upperCases & specialCharacters
var minimumNumbers = "";
var minimumLowerCases = "";
var minimumUpperCases = "";
var minimumSpecialCharacters = "";
// Generator functions**
var functionArray = {
getNumbers: function() {
return String.fromCharCode(Math.floor(Math.random() * 10 + 48));
},
getLowerCases: function() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 97));
},
getUpperCases: function() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 65));
},
getSpecialCharacters: function() {
return specialCharacters[Math.floor(Math.random() * specialCharacters.length)]
}
};
// Checks to make sure user selected ok for all and uses empty minimums from above
if (numbers === true) {
minimumNumbers = functionArray.getNumbers();
minimumCount++;
}
if (lowerCases === true) {
minimumLowerCases = functionArray.getLowerCases();
minimumCount++;
}
if (upperCases === true) {
minimumUpperCases = functionArray.getUpperCases();
minimumCount++;
}
if (special === true) {
minimumSpecialCharacters = functionArray.getSpecialCharacters();
minimumCount++;
}
// empty string variable for the for loop below
var randomPasswordGenerated = "";
// loop getting random characters
for (let i = 0; i < (parseInt(passwordLength) - minimumCount); i++) {
var randomNumberPicked = Math.floor(Math.random() * 4);
randomPasswordGenerated += randomNumberPicked;
}
// to make sure characters are added to the password
randomPasswordGenerated += minimumNumbers;
randomPasswordGenerated += minimumLowerCases;
randomPasswordGenerated += minimumUpperCases;
randomPasswordGenerated += minimumSpecialCharacters;
return randomPasswordGenerated;
}
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generateBtn" class="btn">Generate Password</button>
</div>
</div>
</div>
What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);
I need to limit input box content based on lang. enter.
For example:-
If a string with Korean characters is input, then the number of permitted characters is 8.
If a string with Chinese characters is input, the number of permitted characters is 5.
If that with English, then 12 characters are permitted.
My code is working well for English characters in IE, Firefox and Chrome. However, this code is not working as expected for Korean and Chinese characters. My code always cuts the length of string to 2 even if i increase the valid length. Please suggest some solution as soon as possible.
I am pasting my code for checking.
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
document.onkeydown=function() {
var text = $('#lang').val();
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
// alert(hangul.test(text));
if(hangul.test(text))
{
limit = 8;
//console.log("korean");
limitCharacters('lang', limit , text);
}else if(china.test(text))
{
limit = 5;
//console.log("china");
limitCharacters('lang', limit , text);
}else {
limit = 11;
limitCharacters('lang', limit , text);
}
};
function limitCharacters(textid, limit, text)
{
//alert('here in limit funt.');
var textlength = text.length;
//alert(textlength);
if(textlength > limit )
{
$('#'+textid).val(text.substr(0,limit));
return false;
}else {
$('#'+textid).val(text);
$('#txt').html(text);
return true;
}
}
</script>
<body>
<input type="text" id="lang" />
</body>
</html>
I solved this issue and now it is working fine for me. As per my understanding substring is not supported by IE.
<html>
<title> test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://css-browser-selector.googlecode.com/git/css_browser_selector.js"></script>
<script src="./beta.fix.js"></script>
<script>
var keyFix = new beta.fix('lang');
jQuery(document).ready( function($) {
jQuery('#lang').bind('keyup', checklang);
});
function checklang() {
var textid = jQuery(this).attr("id");
var text = jQuery(this).val();
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
// alert(hangul.test(text));
if(china.test(text))
{
limit = 5;
console.log("chiness");
}else if(hangul.test(text))
{
limit = 8;
console.log("korean");
}else {
limit = 11;
console.log("english");
}
jQuery('#'+textid).attr("maxlength", limit);
};
</script>
<body>
<input type="text" id="lang" size="100" />
</body>
</html>
Can you try this:
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
$("#lang").on("keypress keyup", function () {
var that = $(this);
var text = that.val();
if (china.test(text)) {
limit = 5;
} else if (hangul.test(text)) {
limit = 8;
} else {
limit = 11;
}
that.attr("maxlength", limit);
if (text.length > limit) that.val(text.substring(0, limit))
});
also on http://jsfiddle.net/sWPeN/1/