Need help for a getInput function - javascript

I've been having trouble with my javascript code.
<!DOCTYPE html>
<html>
<head>
<title>js-game</title>
<script src="script.js" type="text/javascript"></script>
<script src="story.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="game">
<ul id="output">
<li onclick="main()">Click here to start!</li>
</ul>
<input autofocus id="inputLine" type="text">
<p onclick="" id="enterInput">ENTER</p>
</div>
</body>
</html>
// Variables
var log="<li>Hello</li>";
var lastVar="";
// Functions
function getInput() {
document.getElementById("enterInput").addEventListener("click", function() {
return document.getElementById("inputLine").value;
document.getElementById("inputline").value="";
});
}
function output(output) {
log=log + "<li>" + output + "</li>";
document.getElementById("output").innerHTML=log;
}
function main() {
output("What's your name?");
alert(getInput());
}
As you can probably see I want to get input from a <input type="text"> with the id of inputLine. And a button with the id of enterInput.
But all I get back is undefined, and I've been working on this for a long time, so I'm getting frustrated.
Sorry for bad english.

Try doing it like so:
document.getElementById("enterInput").addEventListener("click", getInput );
function getInput() {
var val = document.getElementById("inputLine").value;
//do something with val
document.getElementById("inputLine").value="";
return val;
}
See this demo
Or to fetch it as a variable with getInput():
document.getElementById("enterInput").addEventListener("click", function(event){
var val = getInput();
alert(val);
});
function getInput() {
var val = document.getElementById("inputLine").value;
document.getElementById("inputLine").value="";
return val;
}
See this demo

Related

How to reuse a function without refreshing the page

When i use the function to check if number is positive or negative it works fine but when i try to do it again nothing happens i have to refresh the whole page to make it work again. Any help is welcome!
const userNum = document.querySelector(".user-input").value;
const checkBtn = document.querySelector(".check-input");
const result = document.querySelector(".result");
function checkNum() {
if (userNum > 0) {
result.innerHTML = "Positive!!"
}
else if (userNum < 0) {
result.innerHTML = "Negativeee!!"
}
else if (userNum < 0) {
result.innerHTML = "Number is NULL"
}
else {
result.innerHTML = "Enter a Number!!"
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<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>
</head>
<body>
<div class="container">
<div class="intro">
<h1>A Program to Check if number is <br></h1>
<h2>Positive, Negative or Null</h2>
</div>
<div class="check-number-type">
<input type="text" class="user-input">
<button onclick="checkNum()" class="check-input">Check</button>
</div>
<div class="show-result">
<p class="result"></p>
</div>
</div>
</body>
<script src="/script.js"></script>
</html>
The reason why you say you have to "reload" the page everytime is because your code that extracts the input value was placed outside of your checkNum function that determines if it's positive or negative.
You only retrieve the input once, when the script starts, instead of getting a fresh copy everytime you enter the checkNum function.
Just move this:
const userNum = document.querySelector(".user-input").value;
Inside the checkNum() function.

Display javascript array in div

I am trying to make a basic to do application.
Here is what I have done so far;
When the user clicks a button a prompt appears asking the user to enter a task.
The task will then be stored in an array
I have displayed the array in the console. However, I am having trouble displaying the array on the web page:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
console.log(toDoItems);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
</html>
The first thing is you need to use Array.push() and not Array.push = someVal. Then you can loop over to the values and create a list of elements in the HTML:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var nHTML = '';
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
toDoItems.forEach(function(item) {
nHTML += '<li>' + item + '</li>';
});
document.getElementById("item-list").innerHTML = '<ul>' + nHTML + '</ul>'
}
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
You can use map() to map over the toDoItems and convert each items to html code and then use join() to combine the array into one string of HTML code.
Like this:
const HTML = toDoItems.map( item => `<li>${item}</li> ` ).join('');
document.getElementById("item-list").innerHTML = '<ul>' + HTML + '</ul>'
Edit: Fixed typo (should be join, not joint)
Loop over toDoItems, create a <p> tag and append it to #item-list:
toDoItems.forEach((item) => {
let p = document.createElement('p');
p.innerText = item;
document.querySelector('#item-list').appendChild(p);
});
You can use innerHTML for this
document.getElementById("item-list").innerHTML += "<p>" +userInput+"</p>";
demo : plunker
Check below I think this may help you
I removed style from your code for my convenience
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
<script>
function myFunction(){
var toDoItems = [];
var parsed ="";
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
document.getElementById("item-list").innerHTML=userInput;
console.log(toDoItems);
}
</script>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem" onclick="myFunction()">Add item</button>
<div id="item-list">
</div>
</body>
</html>
The Code above has an drawback: It erases the old value of userInput when you enter a new value in prompt().
I propose:
document.getElementById("item-list").innerHTML +=userInput+"";
Vu

Click function executed on page load

I am trying to bind my html button to a function using knockout. The function is only supposed to pop up the alert message when the button is clicked but instead, the function is executed on page load.
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
<script type='text/javascript' src='studentapp.js'></script>
</head>
<body>
<div class="container">
<div class="new_student">
<input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus()">
<input type="text" class="age" placeholder="age" data-bind="value: person_age">
<button data-bind="click: createPerson">Create</button>
</div>
</body>
</html>
Here's my js:
function createPerson(){
alert("Name ");
};
ko.applyBindings(new createPerson());
The console is displaying the following:
Uncaught TypeError: Cannot read property 'nodeType' of null
Any ideas ?
view model should look like this
var createPerson = function(){
var self = this;
self.name = "Mike";
self.sendAlert = function(){
alert(self.name);
};
};
ko.applyBindings(new createPerson());
then your button can use
<button type="button" data-bind="click:sendAlert"></button>
Please have a look on this tutorial
Your code should looks like
var viewModel = function () {
var self = this;
self.name = "Name";
self.age = 22;
self.buttonClicked = function () {
alert(self.name + " is " + self.age + " old");
};
};
ko.applyBindings(new viewModel());
Here is working fiddle sample.
EDIT:
Fiddle was fixed, and link updated
try put defer tag in your script, and put all javascript code after </html> tag, it`s a good practice.
<script type='text/javascript' src='studentapp.js' defer="defer"></script>

ng-click does nothing, DOM notices a click

Trying to set up a simple ng-click event, and reading through other pages about it. It seems like as long as it is added to $scope it should work, but of the two examples I have put in the below page nothing works (except the preventDefault()).
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>ng-click test</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="js/DBFScube.js"></script>
</head>
<body ng-app="DBFScube" ng-controller="AppCtrl as app">
<div style="width: 100%;">
<div id="zoom-controll"><li class="full">Full-screen</li></div>
<button ng-click="$scope.alert('I am a little thing that needs to do somethign');">Click Me</button>
</div>
</body>
</html>
And the controller
var DBFScube = angular.module("DBFScube", ['ngSanitize']);
DBFScube.controller("AppCtrl", function ($sce, $scope, $http, $filter){
var app = this;
//
//$http.get("http://localhost:3000").success(function(CubeSides){
// app.CubeSides = CubeSides;
//})
$http.get("http://localhost:3000").success(function(CubeSides){
$scope.sides=CubeSides;
console.log("Loading data");
})
app.getmenuname = function(side) {
if($scope.sides === undefined) {
console.log("Not loaded fside " + side );
} else {
console.log("Got menu pane " + $scope.sides);
var fside = $filter('filter')($scope.sides, function (d) {return d.side === side;})[0];
console.log("Sending: " + fside.menuname);
return fside.menuname;
}
}
$scope.alert = function(message) { alert(message); }
$scope.growpane = function (side) {
console.log("You pressed the button, like " + side);
}
app.showpane = function (side) {
console.log("Loading side: " + side);
if($scope.sides === undefined) {
console.log("Not loaded yet");
} else {
console.log("Got page " + $scope.sides);
var fside = $filter('filter')($scope.sides, function (d) {return d.side === side;})[0];
var culine = '<iframe src="' + fside.surl + '" height="700" width="700"></iframe>';
console.log(culine);
return $sce.trustAsHtml(culine);
}
}
})
The problem is that you should not write $scope in the view. This holds true to everything you need from the controller, you never need to write $scope since you are in the scope of your defined controller.
Your issue is here:
<button ng-click="$scope.alert('I am a little thing that needs to do somethign');">Click Me</button>
Change to:
<button ng-click="alert('I am a little thing that needs to do somethign');">Click Me</button>
$scope is not necessary inside 'ng-' attribute. Try
<button ng-click="alert('I am a little thing that needs to do somethign');">Click Me</button>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>ng-click test</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="js/DBFScube.js"></script
<script>
module.angular("DBFScube").controller("AppCtrl",['$scope', function($scope){
$scope.someFun = function(){
alert('I am a little thing that needs to do somethign');
}
}]);
</script>
</head>
<body ng-app="DBFScube" ng-controller="AppCtrl">
<div style="width: 100%;">
<div id="zoom-controll"><li class="full">Full-screen</li></div>
<button ng-click="someFun()">Click Me</button>
</div>
</body>
</html>

How to prevent empty input in text input form?

Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?
You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.
Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}

Categories