Better way to apply javascript scripts - javascript

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?

Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}

It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.

You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong

I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

Related

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

To do list app delete function js

I am trying to make an extremely basic to do list. I have researched and looked at many examples to no avail. All I want to do is have the ability to click an item that has been added to my list and have it deleted. I am not sure how to access the value of what Is entered in my items, or how to manipulate those into a function.
function todoList() {
let item = document.getElementById('todoInput').value //pulling value from input box
let text = document.createTextNode(item) //turning input text into node
let newItem = document.createElement('li') //creates a list
newItem.appendChild(text) //appends task entered from input
document.getElementById('todoList').appendChild(newItem) //appends the entered task to the list
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>To do list</title>
</head>
<body>
<h1>To Do List</h1>
<form id="todoForm">
<input type="text" id="todoInput">
<button type="button" onclick="todoList()">Add Item</button>
</form>
<ul id="todoList"></ul>
<script src="app.js"></script>
</body>
</html>
Here is a likely course of actions. There are many ways you can do it, and here is one that is functional.
I have broken it down for you. I also renamed your add function to be a little more clear what it does:
<!DOCTYPE html>
<html>
<head>
<!-- <link rel="stylesheet" type="text/css" href="style.css"> -->
<title>To do list</title>
<!-- Put this in your style.css -->
<style>
.item {
color: blue;
}
</style>
</head>
<body>
<h1>To Do List</h1>
<form id="todoForm">
<input type="text" id="todoInput">
<button type="button" onclick="addItem()">Add Item</button>
</form>
<ul id="todoList"></ul>
<!-- <script src="app.js"></script> -->
</body>
</html>
<script>
function addItem(){
//get current number of todo Items (for creating the ID)
const currentNumberOfItems = document.querySelectorAll('.item').length
console.log(currentNumberOfItems)
console.log('Research:', document.querySelectorAll('.item'))
const item = document.getElementById('todoInput').value //pulling value from input box
const text = document.createTextNode(item) //turning input text into node
const newItem = document.createElement('li') //creates a list
newItem.id = currentNumberOfItems //give the new <li> an auto-incrementing id property
newItem.classList.add('item') //add the item class so we can search for it by class
//we didn't end up searching by class, but you can find every <li> on the page
//using console.log(document.querySelectorAll('.item'))
newItem.appendChild(text) //appends task entered from input
document.getElementById('todoList').appendChild(newItem) //appends the entered task to the list
const btn = document.createElement('button') // Create a <button> element
const t = document.createTextNode('Delete') // Create a text node
btn.appendChild(t) // Append the text to <button>
newItem.appendChild(btn) // Append <button> into the new <li>
//we are going to create an event listener on the button
//this takes 2 parameters
//first = event type (on click)
//second = callback function to run when the event is detected
btn.addEventListener('click', function(event) {
console.log(event.target.parentNode) //we want the element in which the button exists
console.log('Research:', event) //look at all the stuff in here!
deleteItem(event.target.parentNode) //run our delete function
})
}
//now that we have an event listener and know the parent
//we just have to find a way to delete the parent
//we can call the input anything, and it will be a DOM element (event.target.parentNode)
function deleteItem(parent) {
console.log(parent.id) //lets check the parent's id
//we can use element.removeChild() to ditch the todo item
//first, we have to get the <ul> somehow
const todoList = document.getElementById('todoList') //let's get the <ul> by ID
todoList.removeChild(parent) //cya later "parent that the button was inside of"
}
</script>
I tried to make this a snippet, but it seems the code editor crashes when you delete, so I will leave it like this.
Bonus
You will see I used const instead of let, because it does not allow re-assignment, which tells JavaScript and other coders that you do not plan to change that variable once it is set.
You can sample that by putting this in your JS file:
app.js
'use strict'
const test = 'cool'
test = 'not cool'
console.log(test)
Notice the behaviour now with let (swap the code for this):
'use strict'
let test = 'cool'
test = 'not cool'
console.log(test)
This some basics with "immutability" that you should research a bit when you want to do some reading. It means you dont have to worry quite as much with strange bugs when you accidently mutate some variable. const will get mad if you try.
More advanced, you can still re-assign properties on objects when using const:
const object = {
name: 'Bob Alice'
}
object.name = 'Not Bob Anymore'
When you use let, it tells yourself and other coders that you expect the value of the variable will likely change somewhere nearby in the code.
I recommend you try this out and if you ever encounter any issues, just Google it and you will quickly discover. Don't worry, nothing will blow up on you if you always use const "unless you cant". Issues will only occur in highly advanced code, with const vs. let vs. var.

Trouble Getting HTML Input Into JS

So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

Dynamically Update Element Content after multiplying an integer input with a variable

I request some help with updating the result element content with the product of integer input in the text field with a pre-defined variable.
What i wanted to achieve is the content of the element with id="result" to be updated automatically, i want to achieve this using jquery:
Below is my code, thanks in advance.
<script>
function updateresult(){
var operand1 = parseFloat($('slide').val()) || 1;
var operand2 = 25;
var produt;
produt = operand1 * operand2;
$('#result').html(product);
}
</script>
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()" />
</div>
<div >Total is: <span id="result"></span></div>
<br/>
</body>
</html>
You can use keyup event of textbox in jquery.
$("#slide").keyup(function(e){
var operand1 = parseFloat($(this).val()) || 1;
var operand2 = 25;
var result = operand1 * operand2;
$("#result").html(result);
});
Working Sample
There are a couple of things:
your function is named updateresult() but you call a different function: onchange="updateText()"
Instead of $('slide') you need to use an id-selector $('#slide')
you have a typo in product, you sometimes refer to it as poduct
The code below fixes all of that
function updateText(){
var operand1 = parseFloat($('#slide').val()) || 1;
var operand2 = 25;
var product;
product = operand1 * operand2;
$('#result').text(product);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()">
</div>
<div >Total is: <span id="result"></span></div>
There is one more thing: The change event gets fired only when the element loses focus, you may want to add paste and keyup events by removing the onchange attribute and add the following to your javascript
$('#slide').on('change keyup paste',updateText);
And yet another thing: you're using <!DOCTYPE HTML> so this is html5. But there are no self-closing tags in html5, so instead of <tag /> you should just write <tag>

Categories

Resources