how to make a javascript input number positive and negative number - javascript

Hi, I am wondering how I would be able to do this code. I have an idea on how to make the javascript code, but I'm not sure if my code is correct. The question I have been given is:
Design and develop a javascript program that will determine if input
number is positive and negative.Consider zero(0) as
positive(considering that it contains no negative sign).
here is my javascript code, I'm not sure if this is correct based on the question above.
<!DOCTYPE html>
<html>
<head>
<title>activity 1</title>
</head>
<body>
<script type="text/javascript">
var stringNumber = prompt("Enter Number: ", "");
stringNumber = parseInt(stringNumber);
if(stringNumber >=80){
document.write("Positive");
}else{
document.write("Negative");
}
</script>
</body>
</html>
any answers are greatly appreciated.

Just check if the number is greater than or equal to 0
if(stringNumber >= 0)
{
document.write("Positive");
}
else
{
document.write("Negative");
}

var theNumber = prompt("Enter a Number:");
if (theNumber < 0) {
document.write("Negative");
}
else {
document.write("Positive");
}

Why you comparing number with 80? It should be 0
<script type="text/javascript">
var stringNumber = prompt("Enter Number: ", "");
stringNumber = parseInt(stringNumber);
if(stringNumber >=0){
document.write("Positive");
}else{
document.write("Negative");
}
</script>
And it work fine

Positive, negative & NaN:
var stringNumber = prompt("Enter Number: ");
stringNumber = parseInt(stringNumber, 10);
if (isNaN(stringNumber)) {
document.write("Not a Number");
} else if(stringNumber >=0) {
document.write("Positive");
} else {
document.write("Negative");
}

Related

Str.Slice Slicing Spaces

This is my typing game code. Feel free to test it if needed
<!DOCTYPE html>
<html onkeypress="myFunction(event)">
</head>
<body>
<style>
p::first-letter {
background-color: blue;
color: white;
}
</style>
<p id="demo"></p>
<script scr="script.js">
//base value for correct letters typed
var z = 0
//chooses random sentence (changable)
var myArray = [
"Repl.it is the best website in the world",
"Nothing can bet Repl.it in code editors",
"I hope the developers will give me hacker plan for complimenting Repl.it",
"Post your sentence suggestions below because I am horrible at creating sentences",
"I have been on Repl.it for 2 months",
];
var str = myArray[Math.floor(Math.random()*myArray.length)];
//replaces ('demo') with random sentence
document.getElementById("demo").innerHTML = str;
var a = str.length
var n = str.charAt(z)
console.log(a)
var x = null
var y = null
function myFunction(event) {
//find key pressed
x = event.keyCode;
y = String.fromCharCode(x);
myFunction2() //see below
}
function myFunction2() {
if (y == n) { //check if correct key
z = z + 1;
n = str.charAt(z)
console.log(n)
test()
document.getElementById("demo").style.color = "black";
} else { //if not correct key change to red
document.getElementById("demo").style.color = "red";
}
}
function test() {
if (z == a) {
document.write("END")
} else {
document.getElementById("demo").innerHTML = str.slice(z)
}
}
</script>
</body>
</html>
The str.slice is slicing off the spaces.
Is there any way to not slice the space?
or is there any other function which does it?
Which still leaves a space? (I couldn't find one online)
Thanks in advance,
Matthew

Calling a JavaScript function in HTML?

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.

Issue with infinite loop for determining if a word is palindrome

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Programming Task 1</title>
</head>
<body>
<script>
var x, pall, word1;
word1 = prompt("Please enter a word and i will determine if its a palindrome or not")
x = 0
while( x <= word1.length / 2)( pall == true)
if (word1.length(x)!= word1.charAt(word1.length - 1 - x)){
pall == false
}
x=x+1;
if (pall == true) {
confirm("the word you entered "+ word1 + " is a palindrome")
}
else
{
confirm("the word you entered " + word1 + " is not a palindrome")
}
</script>
</body>
</html>
this is what i have currently. this is designed for a website to determine a Palindrome and im unsure why but the loop doesnt stop and im only beginning to code any help is appreciated
Do you have to use a loop? There's an easier way to do this with javascript:
var s1 = 'racecar';
var s2 = 'notracecar';
function isPalindrome(string){
return string.split('').reverse().join('') == string;
}
isPalindrome(s1);
isPalindrome(s2);

Array check with for loop

1.hey guys,how do i separate these?
2.sorry im newb in this,but been cracking my head for a while,how to make this code write sentences separetly without writing them non stop?
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++) {
var y=Number(prompt("enter number from 10 to 30",0));
for(i=0;i<=9;i++) {
if(y==x[i]) {//checking every number in array
document.write("u right.<br>");
e=e+1;
}
else {
document.write("u wrong.<br>");//this writes every time it goes trough the loop,i tried breaking,but it just quits the loop on first number in array,i tried continue,no luck
}
}
}
if(e<5) {//amount of time you guessed right
document.write("u lose ");
}
else {
document.write("u win");
}
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var i=0;
for (c=1;c<=10;c++)
{
var y=Number(prompt("enter number from 10 to 30",0));
var right = false;
for(i=0;i<=9;i++)
{
if(y==x[i]) //checking every number in array
{
right = true;
}
}
if (right)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{document.write("u win");}
</script>
</body>
</html>
Your code can be optimized in many areas:
<html>
<body>
<script type="text/javascript">
var x=[15,22,28,30,25,11,12,29,27,26];//right numbers
var c=1;
var e=0;
var c=0;
while (c < 10)
{
c++;
var y=Number(prompt("enter number from 10 to 30",0));
if (x.indexOf(y) != -1)
{
e++;
document.write("u right.<br>");
}
else {
document.write("u wrong.<br>");
}
}
if(e<5)//amount of time you guessed right
{
document.write("u lose ");
}
else
{
document.write("u win");
}
</script>
</body>
</html>
Use indexOf method of array for checking whether value is available in array or not.
If value is not available then return -1 else return position of that value.
<html>
<body>
<script type="text/javascript">
var x = [15,22,28,30,25,11,12,29,27,26];
var e = 0;
for (var c=1;c<=10;c++) {
var y = Number(prompt("enter number from 10 to 30",0));
x.indexOf(y) > 0?(document.write("u right.<br>"),e++):document.write("u r wrong.<br>");
}
e<5?document.write("u lose "):document.write("u win");
</script>
</body>
</html>

Want to limit korean and chinese

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/

Categories

Resources