In the code below 'len' is the length of text in a tag, the user enters a letter in a textbox, and inside 'result', with the help of .indexof() I am storing the index number of the letter present in the paragraph and then printing that letter in another tag.
But this loop only runs once whereas I want it to run until the statement in the while loop is true.
<!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>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script >
function myFunction(){
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for(var i = 0; i < scen1.length; i++)
{
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while(k <= len){
if(result>=0){
document.getElementById('demo3').innerHTML = scen.substring(result,result+1);
document.getElementById('demo').innerHTML = len;
}
else{
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
break;
}
if(a==0){
window.alert('game over');
}
k++;
}
}
</script>
</body>
</html>
Because of the break condition in Else part of your code is making code to exit from loop.
Please see below code and comments which I have added in your code... and let me know...
function myFunction() {
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for (var i = 0; i < scen1.length; i++) {
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while (k <= len) {
//console.log("Loop iteration ->",k); /*you can uncomment this statement to debug the loop is working or not *?
if (result >= 0) {
document.getElementById('demo3').innerHTML = scen.substring(result, result + 1);
document.getElementById('demo').innerHTML = len;
} else {
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
// break; /* Commented this line so that your loop will run*/
}
if (a == 0) {
window.alert('game over');
}
k++;
}
}
<!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>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
</body>
</html>
Remove the break. It's breaking you out of the loop.
Related
I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output.
Here is my code:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = document.getElementById('userInput').value;
if (input == randomNumber) {
alert.innerHTML = "Your guess is right " + "," + ",it was " + randomNumber;
} else if (number > randomNumber && input < 10) {
alert.innerHTML = "Your guess is to high";
} else if (input < randomNumber && input > 1) {
alert.innerHTML = "Your guess is too low ";
} else if (isNaN(input)) {
alert.innerHTML = "Invalid operator";
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
}
Here it the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<script src="script.js">
</script>
</body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="aginButton">Try again</button>
</div>
</html>
There a couple of issues in your code, first in the html code, you got the id of again button wrong, it should be like this:
<button id="againButton">Try again</button>
Then in the JS code, you should move the two addEventListener() methods out of the checkNumber() function definition. Most importantly, you set the input variable to be the value of the input html element. The value property returns string, and then you compare randomNumber with a string which will not work as expected.
Also, the alert.innerHTML will not work. alert() is a global method which will accepts a string type as its parameter. Please see the JS code corrected below:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = parseInt(document.getElementById('userInput').value);
if (input === randomNumber) {
window.alert("Your guess is right it was " + randomNumber)
} else if (input > randomNumber && input < 10) {
window.alert("Your guess is to high");
} else if (input < randomNumber && input > 1) {
window.alert("Your guess is too low ");
} else if (isNaN(input)) {
window.alert("Invalid operator");
}
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
You should also put your script tag right before the ending </body> tag for it to be able to do its tasks on the DOM elements. Take a look here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="againButton">Try again</button>
</div>
<script src="script.js"></script>
</body>
</html>
There were a few errors in your script. Check out this fixed version.
UPDATE
I now put the <script> element ahead of the <body> element to demonstrate the necessitiy of the window.onload=function(){...}. My whole script is now placed within this function as otherwise, the DOM elements the script refers to, would not yet exist.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
<script>
window.onload=function(){
const [form1,againButton,output,inp]="container,againButton,outputText,userInput".split(",")
.map(id=>document.getElementById(id)), setrndm=_=>randomNumber=Math.ceil(Math.random()*10);
var randomNumber;
setrndm();
form1.addEventListener('submit', checkNumber);
againButton.addEventListener('click', setrndm);
function checkNumber(ev) {
ev.preventDefault(); inp.select();
var input = inp.value;
if (input == randomNumber) {
console.log("Your guess is right, it was " + randomNumber);
} else if (input > randomNumber && input < 11) {
console.log("Your guess is to high");
} else if (input < randomNumber && input > 0) {
console.log("Your guess is too low ");
} else if (isNaN(input)) {
console.log("Invalid operator");
}
}
};
</script>
</head>
<body>
<form id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button type="button" id="againButton">Try again</button>
</form>
</body>
I'm working on a small project about the Collatz conjecture.
In this project i want to apply the formula " times 3 plus one" when the number is odd and devide a number when its even.
i want to keep looping this until the number is 1 and show not only how many steps it took but also display all the numbers it goes through.
i've gotten quite far i think but i have trouble displaying all the steps the loop goes through.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = (num * 3) + 1; /*odd*/
console.log(num) }
i++
document.getElementById('result').innerHTML = "Result is " + num + " found in " + i + " runs";
}
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small><input type="text" id="num" name="num" min="0" /><input type="button" value="submit"
onclick="findOddEven()" name="find" />
<div style="margin-top: 10px;" id="result"></div>
</form>
</body>
</html>
You can store the numbers in the array and display them at the end. You can also move the .innerHTML out of the loop since this only needs to be done when the loop is finished.
I've used join to turn the array into a comma seperated string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let steps = [num]; // Store starting number
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = num * 3 + 1; /*odd*/
}
steps.push(num); // Add changed number to the array
i++;
}
document.getElementById('result').innerHTML =
'Result is ' + num + ' found in ' + i + ' runs. Steps taken: ' + steps.join(', ');
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small
><input type="text" id="num" name="num" min="0" /><input
type="button"
value="submit"
onclick="findOddEven()"
name="find"
/>
<div style="margin-top: 10px" id="result"></div>
</form>
</body>
</html>
Is your problem not seeing all numbers? If so, your console.log is inside the else statement. To see all numbers you shall move it outside the if else statement.
I have a problem with add auto Spaced in Input Tel.
I would like to add a 9-digit number so that every 3 digits take a break (spaces or pauses) like +880 111 222 333. Someone could explain how to achieve it?
function addSpace(){
var inputValue = document.getElementById("telInput").value;
var inputValueLength = inputValue.length;
if(inputValueLength == 3 || inputValueLength == 7){
document.getElementById("telInput").value = inputValue+" ";
}
}
<input type="tel" id="telInput" onkeypress="addSpace()">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<input type="tel" name="phone" id="phone" pattern="[0-9 -+()]{11,11}">
<input type="submit" value="Submit" >
</form>
</body>
</html>
<script>
let itemInput=document.querySelector('input[type=tel]') ;
itemInput.addEventListener('keypress',phone);
function phone()
{
let p=this.value;
if((p.length+1)%4==0 && p.length<9) this.value=p+" ";
}
</script>
XXX XXX XXX only accepts numbers that are 0-9 in this view.try one.
<!DOCTYPE html>
<html>
<head>
<script>
function inNumber(elm){
if (!elm.value) return
elm.value = elm.value.replace(/ /g, '')
}
function withSpaces(elm) {
if (!elm.value|| isNaN(elm.value) || elm.value.length < 3) return
elm.value = elm.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");;
}
</script>
</head>
<body>
<p>Enter any number value and press tab </p>
<input id="0" onblur="withSpaces(this)" onfocus="inNumber(this)">
</body>
</html>
JQuery:
<input type="tel" placeholder="123-456-7890" maxlength="12" id="phone" >
<script>
jQuery(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
var lngth = number.length;
if (lngth == 3 || lngth == 7) {
$("#phone").val(number + "-") ;
} else if (lngth >12 ) {
$("#phone").val(number.slice(0,12));
}
})
});
</script>
Maybe maxlength="12" and else if (lngth >12 ) is redundant but it doesn't hurt either
Am trying to print the values inside the textboxes on the page.
Upon clicking the button, the values appear on the page but only for a split second.
What can I do to make the values remain on the page?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2>Local Storage - JavaScript <h2>
<fieldset>
<legend>Insert Data</legend>
<input id="inpKey" type="text" placeholder="Enter key...">
<input id="inpValue" type="text" placeholder="Enter Value...">
<button type="button" id="btnInsert">Insert Data</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<div id="lsOutPut"></div>
</fieldset>
<script src="action.js">
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutPut = document.getElementById("lsOutPut");
btnInsert.onclick = function(){
const key = inpKey.value;
const value = inpValue.value;
if(key && value) {
localStorage.setItem(key, value);
location.reload();
}
for(let i = 0; i < localStorage.length; i++){
const keyx = localStorage.key(i);
const value = localStorage.getItem(keyx);
lsOutPut.innerHTML += `${keyx}: ${value}</br> `
}
}
</script>
</body>
</html>
In your code you have location.reload(), that's why its reloading the page, not sure why you have there, but its the cause:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2>Local Storage - JavaScript <h2>
<fieldset>
<legend>Insert Data</legend>
<input id="inpKey" type="text" placeholder="Enter key...">
<input id="inpValue" type="text" placeholder="Enter Value...">
<input type="button" id="btnInsert" value="Insert Data"/>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<div id="lsOutPut"></div>
</fieldset>
<script>
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutPut = document.getElementById("lsOutPut");
btnInsert.onclick = function(){
const key = inpKey.value;
const value = inpValue.value;
if(key && value) {
localStorage.setItem(key, value);
}
for(let i = 0; i < localStorage.length; i++){
const keyx = localStorage.key(i);
const value = localStorage.getItem(keyx);
lsOutPut.innerHTML += `${keyx}: ${value}</br> `
}
}
</script>
</body>
</html>
In your code you have location.reload(), I presume to clear the div with previous values. This is reloading the page and causing the split second issue. Switch it for the following to clear the box before printing the new values.
if(key && value) {
localStorage.setItem(key, value);
lsOutPut.innerHTML = '';
}
While unrelated, it's also worth noting you aren't closing your <h2> tag.
<h2>Local Storage - JavaScript</h2>
I am creating a website that allows the user to create a contact, and there is a search box that allows the user to search in the created contacts.
The problem is when the user creates contact and searches, the search box does not work.
The code is running well when I create the contacts manually in the HTML file. It means that the search box only searches in the HTML file, and doesn't search in the newly created contacts by the innerHTML code by JavaScript.
And please answer me with JAVASCRIPT code, not jQuery.
This is my code, only HTML and JAVASCRIPT , no css :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
Javascript code:
//CREATE NEW CONTACT
//CREATE NEW LI I MEAN
document.getElementById('myForm').addEventListener('submit', createContact)
function createContact(e) {
//input
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var demo = document.getElementById('demo');
demo.innerHTML +=
'<li class=menuItem>' + newName + '</li>';
e.preventDefault();
}
//Search Filter
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
function filter() {
var ul = document.getElementById('names');
var li = ul.querySelectorAll('li.menuItem');
var searchBoxValue = document.getElementById('search').value.toUpperCase();
for (var i = 0; i < li.length; i++) {
var newName = document.getElementById('create').value;
var a = li[i].getElementsByTagName('a')[0];
if (a.innerHTML.toUpperCase().indexOf(searchBoxValue) > -1) {
li[i].style.display = '';
}
else {
li[i].style.display = 'none';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
You append new items to <div id="demo"> instead of <ul id="names">. It should be like this:
var names = document.getElementById('names');
names.innerHTML += '<li class="menuItem">' + newName + '</li>';
//CREATE NEW CONTACT
//CREATE NEW LI I MEAN
document.getElementById('myForm').addEventListener('submit', craeteContact)
function craeteContact(e) {
//input
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var names= document.getElementById('names');
names.innerHTML +=
'<li class="menuItem">' + newName + '</li>';
e.preventDefault();
}
//Search Filter
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
function filter() {
var ul = document.getElementById('names');
var li = ul.querySelectorAll('li.menuItem');
var searchBoxValue = document.getElementById('search').value.toUpperCase();
for (var i = 0; i < li.length; i++) {
var newName = document.getElementById('create').value;
var a = li[i].getElementsByTagName('a')[0];
if (a.innerHTML.toUpperCase().indexOf(searchBoxValue) > -1) {
li[i].style.display = '';
}
else {
li[i].style.display = 'none';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
it's because you place li elements in #demo instead of #names
you should use console.log() to debug
Use an array to save names and then search the array. why you get data from UI everytime
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
document.getElementById('myForm').addEventListener('submit', craeteContact)
var names = [];
function craeteContact(e) {
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var demo = document.getElementById('demo');
names.push(newName.toUpperCase()); // add new name to array
demo.innerHTML += '<li class=menuItem>' + newName + '</li>';
e.preventDefault();
}
function filter() {
var searchValue = searchBox.value.toUpperCase();
for (var i = 0; i < names.length; i++) {
if (names[i].indexOf(searchValue) > -1) {
console.log("found");
}
else {
console.log("not found");
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>