The code not working. I cannot identify the issue - javascript

I was writing some code and for some reason that I am unaware of, whenever I click on the button, the function that it is assigned does not run. Does anybody know why? Thanks in advance.
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p").innerHTML;
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text = "Your number, "+number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text = "Your number, "+number+", is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input");
prime(number);
}
</script>
<p id="p"></p><br>
<form id="input">
Your Number: <input type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>

Try this
<button onclick="funcito()" value = "Got my number">Got my number</button>

There are a couple of other issues with that code, so you won't get the result you are looking for. Try this code:
<html>
<head>
</head>
<body>
<script>
function prime(number) {
var text = document.getElementById("p");
var n = 0;
for(var i = 2; i<number; i++){
if(number%i==0){
text.innerHTML = "Your number, "+ number+", is divisible by "+i+"! It's composite!";
n = 1;
}
}
if(n==0){
text.innerHTML = "Your number" + number + " is prime!";
}
}
function funcito(){
console.log("Functions!");
var number = document.getElementById("input").value;
prime(number);
}
</script>
<p id="p"></p><br>
<form>
Your Number: <input id = "input" type="number" name="uInput"><br>
</form>
<p>Click "Got my number" to find out!.</p>
<button onclick="funcito()" value = "Got my number">Got my number</button>
</body>
</html>

Because you write onclick="funcito" which is wrong write onclick="funcito()". instead.

Related

How to fix the show/hide button on input change based on if/else condition

I am learning jquery. I have an HTML & jquery code. I want to show the button only if my answer is true on input value otherwise it should stay hidden. Also, I want to show the questions on my screen. See, if anyone can help. thanks
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var ans = 5;
$(document).ready(function() {
$("#bot").keyup(function() {
if (ans == floor) {
$("#pete").css("display", "block");
} else {
$("#pete").css("display", "none");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;">
use show() and hide() functions and i dont know when your floor and ans will be equal.
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ans = 5;
floor=6; //for testing i gave
$("#bot").keyup(function() {
if (ans == $('#bot').val())
$("#pete").show();
else
$("#pete").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What number comes after 4?</label>
<input type="number" id="bot" required="required"/>
<input type="submit" id="pete" style="display:none;" >
Here is the complete code for your requirement .
Use innerHTML to priint the question in the screen and .value to obtain the value entered by user ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="question"></p>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;" >
</body>
</html>
<script type="text/javascript">
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
document.getElementById('question').innerHTML = ques1;
var ans = 5;
$("#bot").keyup(function() {
var ansFromInput = document.getElementById('bot').value;
console.log("ans , floor" , ans , ansFromInput);
if (ans == ansFromInput) {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
</script>
You can do something like that ,
Here using class to hide the button, we can add and remove class to achieve that.
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var floor = 5;
$('#ques').text(ques1);
$(document).ready(function() {
$('#bot').on('input',function(e){
if ($('#bot').val() == floor) {
$("#pete").removeClass('hide');
} else {
$("#pete").addClass('hide');
}
});
});
.hide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <p id="ques"> </p> </label>
<p><input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" class="hide">

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

How to store inputs from a textbox in array in Javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!
Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.
i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Dynamically array input with Javascript

I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here

Dynamically changing a value in a function with Javascript using input text fields

I'm not sure if the title makes sense, but I'm trying to dynamically change the value of a variable in a loop through a text input.
Take a look at my code so far
<script type="text/javascript">
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
for(count = 0; count < 5; count++, str += plus){
document.write("<br />");
document.write(str);
}
};
</script>
<input type="text" id="inputter" name="inputter"></form>
<button id="sub" type="button" onclick="test()">Try It Out</button>
so if you hit the button with whatever you put in as a value in the text field, say for example... You put "X" the result would be...
X
XX
XXX
XXXX
XXXXX
but then the form field disappears and I would have to refresh the page to do it again? Is there a way I can do this dynamically? So without refreshing, I would like to be able to type in a new string, and it would change.
Thanks in advance!
document.write() is overwriting your page. Don't use it, use DOM modification functions to put the string in a DIV.
<input type="text" id="inputter" name="inputter"></form>
<button id="sub" type="button" onclick="test()">Try It Out</button>
<div id="output"></div>
<script>
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
var output = '';
for(count = 0; count < 5; count++, str += plus) {
output += "<br />" + str;
}
document.getElementById('output').innerHTML = output;
};
</script>
DEMO
use a div and fill with data:
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form>
<input type="text" id="inputter" name="inputter">
<button id="sub" type="button" onclick="test()">Try It Out</button>
</form>
<div id="theText"></div>
<script type="text/javascript">
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
var theText = document.getElementById('theText');
for (count = 0; count < 5; count++) {
str += plus;
theText.innerHTML = theText.innerHTML + str + '<br/>';
}
};
</script>
</body>
</html>
Do you mean something like this?:
var str;
function test() {
var str += document.getElementById('inputter').value;
document.write("<br />");
document.write(str);
}

Categories

Resources