Incredibly novice coder here. Like, complete beginner aside from Tumblr and Neopets teaching me how to read and do basic tinkering.
I've maybe bitten off more than I can chew on this project, anybody willing to help?
Needing 5 buttons in a single column where "on click" the text changes. I got it to work for 1, but adding 5 on the same page all the buttons go random and I think they need individual IDs, but I have no idea how to do that.
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="return change(this);" />
<script type="text/javascript">
function change( bf3 )
{
if (bf3.value === "BF₃" )
bf3.value = "boron trifluoride";
else
bf3.value = "BF₃";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="return change(this);" />
<script type="text/javascript">
function change( sf6 )
{
if ( sf6.value === "SF₆" )
sf6.value = "sulfur hexafluoride";
else
sf6.value = "SF₆";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="return change(this);" />
<script type="text/javascript">
function change( h2o )
{
if ( h2o.value === "H₂O" )
h2o.value = "dihydrogen monoxide (aka water)";
else
h2o.value = "H₂O";
}
</script>
</center>
</body>
<body>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="return change(this);" />
<script type="text/javascript">
function change( pcl5 )
{
if ( pcl5.value === "PCl₅" )
pcl5.value = "phosphorus pentachloride";
else
pcl5.value = "PCl₅;
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="return change(this);" />
<script type="text/javascript">
function change( n2h4 )
{
if ( n2h4.value === "N₂H₄" )
n2h4.value = "dinitrogen tetrahydride";
else
n2h4.value = "N₂H₄;
}
</script>
</center>
</body>
</html>
I would do it like this for more maintainability:
var container = document.getElementById('container');
var molecules = [
{ formula: "BF₃", name: "boron trifluoride" },
{ formula: "SF₆", name: "sulfur hexafluoride" },
{ formula: "H₂O", name: "dihydrogen monoxide (aka water)" },
{ formula: "PCl₅", name: "phosphorus pentachloride" },
{ formula: "N₂H₄", name: "dinitrogen tetrahydride" }
];
molecules.forEach(function(m) {
var showName = false;
var btn = document.createElement('input');
btn.type = 'button';
btn.className = 'button';
btn.value = m.formula;
btn.addEventListener('click', function() {
showName = !showName;
btn.value = showName ? m.name : m.formula;
});
container.appendChild(btn);
container.appendChild(document.createElement('br'));
});
#container { text-align: center; }
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<div id="container"></div>
You do not need multiple functions to achieve that. Simply check the value of the currently clicked button and set the value accordingly.
Try the following way:
function change(currBtn){
if(currBtn.value == 'BF₃' || currBtn.value == 'boron trifluoride'){
if(currBtn.value == 'BF₃')
currBtn.value = 'boron trifluoride';
else
currBtn.value = 'BF₃';
}
else if(currBtn.value == 'SF₆' || currBtn.value == 'sulfur hexafluoride'){
if(currBtn.value == 'SF₆')
currBtn.value = 'sulfur hexafluoride';
else
currBtn.value = 'SF₆';
}
else if(currBtn.value == 'H₂O' || currBtn.value == 'dihydrogen monoxide (aka water)'){
if(currBtn.value == 'H₂O')
currBtn.value = 'dihydrogen monoxide (aka water)';
else
currBtn.value = 'H₂O';
}
else if(currBtn.value == 'PCl₅' || currBtn.value == 'phosphorus pentachloride'){
if(currBtn.value == 'PCl₅')
currBtn.value = 'phosphorus pentachloride';
else
currBtn.value = 'PCl₅';
}
else if(currBtn.value == 'N₂H₄' || currBtn.value == 'dinitrogen tetrahydride'){
if(currBtn.value == 'N₂H₄')
currBtn.value = 'dinitrogen tetrahydride';
else
currBtn.value = 'N₂H₄'
}
}
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="change(this);" />
</center>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="change(this);" />
</center>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="change(this);" />
</center>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="change(this);" />
</center>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="change(this);" />
</center>
My way...
const buttonList =
[ [ 'BF₃', 'boron trifluoride' ]
, [ 'SF₆', 'sulfur hexafluoride' ]
, [ 'H₂O', 'dihydrogen monoxide (aka water)' ]
, [ 'PCl₅', 'phosphorus pentachloride' ]
, [ 'N₂H₄', 'dinitrogen tetrahydride' ]
];
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, timOut = null;
newbt.className = 'button'
newbt.textContent = bt[0]
document.documentElement.appendChild( newbt )
newbt.onclick=()=>{
newbt.textContent = bt[1]
clearTimeout(timOut)
timOut = setTimeout(()=>{ newbt.textContent = bt[0] }, 1500)
}
})
/* or
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, LibNum = 0
newbt.className = 'button'
newbt.textContent = bt[0]
newbt.onclick=()=>{ LibNum = ++LibNum %2; newbt.textContent = bt[LibNum] }
document.documentElement.appendChild( newbt )
})
*/
.button {
font-family: 'Quattrocento Sans', sans-serif;
font-size: 18px;
display: block;
margin: .2em auto;
padding: 1em;
color: #08365F;
background-color: #f0c640;
border: none;
cursor: pointer;
text-align: center;
min-width: 5em;
}
Did I still take the time to correct your code to help you?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title> sample code </title>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px;
display: block; /* must be block to be centered */
font-size: 18px;
margin: 4px auto; /* this one replace <center> tag (obsolete) */
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<input type="button" id="bf3" class="button" value="BF₃" onclick="xchange(this);" />
<input type="button" id="sf6" class="button" value="SF₆" onclick="xchange(this);" />
<input type="button" id="h2o" class="button" value="H₂O" onclick="xchange(this);" />
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="xchange(this);" />
<input type="button" id="n2h4" class="button" value="N₂H₄" onclick="xchange(this);" />
<script>
function xchange( btn )
{
switch (btn.id) {
case 'bf3': btn.value = (btn.value==='BF₃') ? 'boron trifluoride' : 'BF₃'; break;
case 'sf6': btn.value = (btn.value==='SF₆') ? 'sulfur hexafluoride' : 'SF₆'; break;
case 'h2o': btn.value = (btn.value==='H₂O') ? 'dihydrogen monoxide (aka water)' : 'H₂O'; break;
case 'pcl5': btn.value = (btn.value==='PCl₅') ? 'phosphorus pentachloride' : 'PCl₅'; break;
case 'n2h4': btn.value = (btn.value==='N₂H₄') ? 'dinitrogen tetrahydride' : 'N₂H₄'; break;
} }
</script>
</body>
</html>
Related
I want to create a to do list that will add elements typed in <input type="text"> and delete when clicked on button with class .delete. When ever I push elements in an array. And innerHTML it in html page, the delete button stops working. The delete button works for elements that are written into Html code. If someone can help me I will be very thankful.
`
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
addText.addEventListener('click', addItem);
<style>
body {
width: 100%;
height: 100vh;
background-color: rgb(115, 115, 197);
margin: 0;
padding: 0;
position: relative;
}
.container {
width:50%;
height:70%;
position: absolute;
background-color: rgb(241, 241, 241);
font-family: Arial, Helvetica, sans-serif;
border-bottom-left-radius: 25px;
border-bottom-right-radius: 25px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow-y: scroll;
}
.heading {
width: 100%;
height: 122px;
background-color: #5B45B9;
display: flex;
align-items: center;
justify-content: center;
}
.heading h1 {
color: white;
font-size: 40px;
}
.item-list {
width: 100%;
padding: 0 0 30px 0;
}
.item-list div {
width: auto;
height: 60px;
}
p {
width: 60%;
float: left;
font-size: 25px;
padding-left: 30px;
margin-top: 12px ;
}
.item-list button {
width: 60px;
height: 60px;
font-size: 18px;
float: right;
}
.delete {
font-size: 30px;
color: red;
}
.input_form {
width: 100%;
padding: 30px 0 30px 0;
position: absolute;
bottom: 0;
text-align: center;
}
.input_form .input_bar {
width: 80%;
height: 50px;
font-size: 18px;
border: none;
}
.input_form button {
width: 10%;
height: 50px;
float: right;
margin-right: 30px;
}
</style>
<html>
<head>
</head>
<body>
<div class="container">
<div class="heading">
<h1>TO-DO LIST</h1>
</div>
<div class="item-list">
<div>
<p>TEEXT2</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
</div>
</body>
</html>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
<script src="script.js"></script>
</div>
</body>
</html>`
You actually only trigger DOM "original" delete button (button loaded with your HTML code) with the line :
let deleteText = document.querySelectorAll('.delete'); // delete button
Your others .delete are loaded after the first DOM loading and are not even listed in "deleteText" array !
You have to refresh deleteText every time you add a new item. Something like :
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
function triggerDeleteButton(){
deleteText = document.querySelectorAll('.delete'); // delete button
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
}
addText.addEventListener('click', function(){
addItem() ;
triggerDeleteButton() ;
}
);
Without refreshing, you can add and edit data by using local storage
For example, like below, you can try once!
<script>
let customerData = [];
// Inserting new customer record into local storage
function insert() {
let company = document.getElementById("company").value;
let obj = {company};
customerData.push(obj);
synData(customerData);
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
clearFileds();
displayelements(customerDetails);
}
function displayelements(customerDetails) {
let html = "<table id='customer_data' border='1'><tr><th>Sl No</th><th>Company</th><th>Delete</th></tr>";
if(customerDetails == '') {
html+="<tr>No record found!</tr>";
} else {
customerDetails.map((values, index) => {
html+="<tr id='row_data'>";
html+="<td>"+index+"</td>";
html+="<td>"+values.company+"</td>";
html+="<td onclick='deleteRow(" + index + ")'>Delete</td>";
html+="</tr>";
} )
}
html+="</table>";
document.getElementById("display").innerHTML = html;
clearFileds();
}
// Delete the specific customer record from local storage
function deleteRow(deleteKey) {
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
customerDetails.map((values, index) => {
if (index == deleteKey) {
customerDetails.splice(index, 1);
}
})
customerData = customerDetails;
synData(customerDetails);
displayelements(customerDetails);
}
// Clearing the form input field data
function clearFileds() {
document.getElementById("company").value = '';
}
// Updating local storage data
function synData(customerDetails) {
localStorage.setItem('customerString', JSON.stringify(customerDetails));
}
</script>
<html>
<head>
<title>Save</title>
</head>
<script ></script>
<body id="format_background">
<div id="customerAction" >
<h1>Customer data</h1>
<label>Company Name </label>
<input id="company" type="text" />
<button type="button" value="Save&Show" onclick="insert()" id="insert">Save</button>
</div>
<div id="display"></div>
</body>
</html>
I am trying to create a text font colour drop down button where it gives you an option of multiple colour to pick from and then it would change the colour of the text. I am not sure on how to approach this and I am not meant to use jQuery. Any help would be appreciated. In the code below it shows other examples of other button where they change the user input entered into the contenteditable. I want the font colour button to do the same but just change the colour of the text
const TAB_KEY = 9;
const ENTER_KEY = 13;
const SHIFT_KEY = 16
const editor = document.querySelector('.editor');
editor.appendChild(document.createElement('li'));
editor.addEventListener('keydown', (e) => {
let code = e.keyCode || e.which;
if (code == TAB_KEY) {
e.preventDefault();
let parent = e.target;
let ul = document.createElement('ul');
let li = document.createElement('li');
ul.appendChild(li);
parent.appendChild(ul);
moveCursorToEnd(li);
} else if (code == ENTER_KEY) {
e.preventDefault();
let parent = e.target;
let li = document.createElement('li');
parent.appendChild(li);
moveCursorToEnd(li);
} else if (code == TAB_KEY * TAB_KEY){
e.preventDefault();
let parent = e.target;
let ol = document.createElement('ol');
let li = document.createElement('li');
ol.appendChild(li);
parent.appendChild(ol);
moveCursorToEnd(li);
}
});
function moveCursorToEnd(el) {
el.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
/*editor.addEventListener('click', (x) => {
x = document.getElementById("b");
if(x.style.fontWeight == "bolder"){
x.style.fontWeight = "normal";
} else {
x.style.fontWeight = "bolder";
}
});*/
function bold(){
if(document.execCommand("bold")){
document.execCommand("normal");
}else{
document.execCommand("bold");
}
}
/*function underline(){
let x = document.getElementById("text");
if(x.style.textDecoration == "underline"){
x.style.textDecoration = "none";
}else{
x.style.textDecoration = "underline";
}
}*/
function underline(){
if(document.execCommand("underline")){
document.execCommand("none");
}else{
document.execCommand("underline");
}
}
/*Turns the font of the text to Italic*/
function italic(){
if(document.execCommand("italic")){
document.execCommand("normal");
}else{
document.execCommand("italic");
}
}
function highlighSelectedText(){
let sel = window.getSelection().getRangeAt(0);
let selText = sel.extractContents();
let span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selText);
sel.insertNode(span);
}
/*function printPage(){
let printButton = document.getElementById("ul");
printButton.style.visibility = 'hidden';
window.print();
printButton.style.visibility = 'visible';
}*/
body{
margin-top:1em;
margin-bottom: 10em;
margin-right: 1em;
margin-left: 1em;
border: solid;
border-color: #0033cc;
background-color: #f6f6f6;
}
div button{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div input{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div{
list-style-type:square;
list-style-position: inside;
margin-left: 0.25em;
margin-bottom: 5em;
}
section {
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
.editor {
font-weight: normal;
}
div contenteditable{
margin-bottom: 10em;
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<div>
<button id="b" onclick="bold()"> B </button>
<button onclick="underline()"> U </button>
<button onclick="italic()"> I </button>
<input type="button" onclick="highlighSelectedText()" value="Highlight"/>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
</div>
<section>
<input id="saveAs"></input>
<button onclick="saveTextFile()">Download</button>
<input type="file" id="load"/>
<button onclick="loadFile()">Load</button>
</section>
<section>
<button class="btn btn-primary" onclick="saveChanges()">Save Text</button>
<button class="btn btn-warning" onclick="clearStorage()">Reset</button>
</section>
</head>
<script type= "text/javascript" src='setting.js'></script>
</body>
First off we will use a CSS variable. Lets declare a value at :root
:root {
--font-color: #000;
}
Now we will use that value to style the font color of our P tags.
p {
color: var(--font-color);
}
Now when somebody clicks one of the color names, we want to change the value of --font-color. (Notice we are using the data- attribute model to store the color we want to change too).
document.documentElement.style.setProperty('--font-color', target.dataset.color);
And presto we can now change color easily. This works for other values also.
Here is a great article
document.addEventListener('click', ({ target }) => {
if(target.matches('p')) {
document.documentElement.style.setProperty('--font-color', target.dataset.color);
}
});
:root {
--font-color: #000;
}
p {
width: 30%;
border: 2px solid #00000030;
border-radius: 7px;
margin: 0.25rem;
padding: 0.25rem;
color: var(--font-color);
}
<h2>Click a color</h2>
<p data-color="#f00">Red</p>
<p data-color="#0f0">Green</p>
<p data-color="#00f">Blue</p>
<p data-color="#000">Reset</p>
You can manipulate the style variable:
<div id="text">
Choose a color
</div>
<input id="color" type="color">
<button onclick="document.getElementById('text').style.color = document.getElementById('color').value;">Change Color</button>
I want to display a table on click submit only if text box is not null
Demo: https://jsfiddle.net/21bbc4wm/
When i click submit button it returns no table, pls can someone help me out of this
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required />
<div id= "container1" style="display:none;">
<p style="text-align:center; font-size:160%;">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
<td><button style="background-color: #4CAF50;" id = "buttonSubmit"
type="submit" value="Submit" onclick ='check(); return
false'>Submit</button></td>
Javascript:
function check()
{
if(document.getElementById("note").value == null ||
document.getElementById("note").value == "")
{
alert("You must mention User ID for the result!!!");
document.getElementById("note").focus();
return false
var x = document.getElementById("container1");
if (x.style.display = "none") {
x.style.display = "block";
} else {
x.style.display = "true";
}
}
document.addEventListener("click", function(e){
var table = document.getElementById("demo");
var content = document.getElementById("container1");
var val = document.getElementById("note");
if(e.target.id === "buttonSubmit") {
if(val.value === null || val.value === "") {
alert("You must mention User ID for the result!!!");
content.classList.remove("active");
val.focus();
}
else {
var date = new Date();
/* remove this line for stacking */ table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
table.innerHTML += '<tr><td>' + val.value + '</th><td>'+ date.toDateString() +'</th><tr>';
val.value = "";
content.classList.remove("active");
content.classList.add("active");
}
}
if(e.target.id === "buttonReset") {
table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
val.value = "";
content.classList.remove("active");
}
});
input {
font-size: 1em;
}
#container1 {
display: none;
}
#container1.active {
display: block;
}
#result {
text-align: center;
font-size: 160%;
}
#buttonSubmit {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
#buttonReset {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required>
<div id="container1">
<p id="result">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
</div>
<a id="buttonSubmit">Submit</a>
<a id="buttonReset">Reset</a>
Today I started building a dummy client-side web app project in order to improve my basic JavaScript skills. Basically, it's a scientific calculator imitation that runs on line. As you'll see in the code, there are buttons in my HTML file each of which calls to one of the JavaScript functions in my JavaScript file. The calculator doesn't work, I mean, at all, and as I tried debugging, every function in my JavaScript file works by them-self as intended, but seemingly they don't work together.
Here's my code:
var currentMode = 'deg';
var screen = document.getElementById("screen");
var lastChar = screen.value.slice(-1);
/**
* Auxiliary functions
*/
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function sine(val) {
if (currentMode === 'deg') {
return Math.sin(Math.PI * val / 180);
}
return Math.sin(val);
}
function cos(val) {
if (currentMode === 'deg') {
return Math.cos(Math.PI * val / 180);
}
return Math.cos(val);
}
function tan(val) {
if (currentMode === 'deg') {
return Math.tan(Math.PI * val / 180);
}
return Math.tan(val);
}
function ln(val) {
return Math.log(val);
}
/**
* Calculator functions
*/
function addSpecial(val) {
var nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var operations = ['+', '-', '*', '/', '^'];
if (screen.value === '0') {
if (nums.indexOf(val) >= 0)
screen.value = val;
else if (val === '.' || operations.indexOf(val) >= 0)
screen.value += val;
else
screen.value = '0';
} else if (lastChar === '.' || operations.indexOf(lastChar) >= 0) {
if (val !== '.' && val !== '=' && operations.indexOf(val) < 0)
screen.value += val;
} else {
if (val !== '=')
screen.value += val;
else {
if (lastChar === '.' || operations.indexOf(lastChar) >= 0)
screen.value = 'SYNTAX ERROR!';
else if (screen.value.split('(') !== screen.value.split(')'))
screen.value = 'ERROR! Open or close parantheses!';
else {
try {
screen.value = eval(screen.value);
} catch(err) {
screen.value = err.message;
}
}
}
}
}
function setAngleMode(newMode) {
if (newMode === 'rad') {
if (currentMode === 'deg') {
currentMode = 'rad';
screen.value *= Math.PI / 180;
}
} else {
if (currentMode === 'rad') {
currentMode = 'deg';
screen.value *= 180 / Math.PI;
}
}
}
function addSymbol(val) {
switch (val) {
case 'pi':
screen.value = Math.PI;
break;
case 'e':
screen.value = Math.E;
break;
case 'phi':
screen.value = 1.61803398875;
break;
case 'gamma':
screen.value = 0.5772156649;
}
}
function clearScreen() {
screen.value = '';
}
function clearLast() {
screen.value.slice(0, -1);
}
function inverseVal() {
var len = screen.value.length;
var subs;
for (var i = 0; i < len; ++i) {
for (var j = len; j > i; --j) {
subs = screen.value.slice(i, j);
if (isNumeric(subs)) {
screen.value = 1 / parseFloat(subs);
break;
}
}
}
}
function addSquare() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^2';
}
}
function addPower() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^';
}
}
function addSquareroot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/2)';
}
}
function addRoot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/';
}
}
function addExp() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'Math.E^';
}
}
function addSin() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'sine(';
}
}
function addCos() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'cos(';
}
}
function addTan() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'tan(';
}
}
function addLn() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'ln(';
}
}
h5 {
text-align: right;
color: #333333;
font-family: Arial;
font-size: 12px;
font-weight: bold;
margin: 3px;
}
input[type=text] {
text-align: right;
height: 50px;
width: 176px;
padding: 6px;
border: 10px groove #888888;
background-color: #E5DFA0;
font-family: Luicida, monospace;
}
.scientific {
position: relative;
top:0px;
left: 33px;
}
.scientific input[type=button] {
width: 28px;
height: 28px;
background-color: #444444;
color: #BBBBBB;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=button].cardinal {
width: 28px;
height: 28px;
background-color: red;
color: white;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=image] {
width: 24px;
height: 24px;
background-color: #444444;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.simple input[type=button] {
width: 32px;
height: 32px;
background-color: #EEEEEE;
color: #222222;
font-family: Verdana;
font-size: 11px;
}
.simple input[type=button].roman {
font-family: "Times New Roman", serif;
font-size: 13px;
}
#calc-contain {
width: 180px;
margin: 0px auto;
}
<html>
<head>
<title>::Scientific Calculator::</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="engine.js"></script>
</head><body>
<div id="calc-contain">
<img src="EnData.png" alt="EnData" width="180px" />
<h5>SCIENTIFIC CALCULATOR</h5>
<form id="calculator">
<input type="text" id="screen" value="0" readonly />
<div class="scientific">
<div class="line">
<input type="button" value="RAD" onclick="setAngleMode('rad')" />
<input type="button" value="DEG" onclick="setAngleMode('deg')" />
<input type="button" class="cardinal" value="C" onclick="clearScreen()" />
<input type="button" class="cardinal" value="CE" onclick="clearLast()" />
</div><div class="line">
<input type="button" value="sin" onclick="addSin()" />
<input type="button" value="cos" onclick="addCos()" />
<input type="button" value="tan" onclick="addTan()" />
<input type="button" value="ln" onclick="addLn()" />
</div><div class="line">
<input type="image" src="sqr.png" alt="square" onclick="addSquare()" />
<input type="image" src="nthp.png" alt="nth power" onclick="addPower()" />
<input type="image" src="sqrt.png" alt="square root" onclick="addSquareroot()" />
<input type="image" src="nthr.png" alt="nth root" onclick="addRoot()" />
</div><div class="line">
<input type="button" value="1/x" onclick="inverseVal()" />
<input type="button" value="(" onclick="addSpecial('(')" />
<input type="button" value=")" onclick="addSpecial(')')" />
<input type="button" value="exp" onclick="addExp()" />
</div>
</div>
<div class="simple">
<div class="line">
<input type="button" class="roman" value="π" onclick="addSymbol('pi')" />
<input type="button" value="7" onclick="addSpecial('7')" />
<input type="button" value="8" onclick="addSpecial('8')" />
<input type="button" value="9" onclick="addSpecial('9')" />
<input type="button" value=":" onclick="addSpecial('/')" />
</div><div class="line">
<input type="button" class="roman" value="e" onclick="addSymbol('e')" />
<input type="button" value="4" onclick="addSpecial('4')" />
<input type="button" value="5" onclick="addSpecial('5')" />
<input type="button" value="6" onclick="addSpecial('6')" />
<input type="button" value="x" onclick="addSpecial('*')" />
</div><div class="line">
<input type="button" class="roman" value="φ" onclick="addSymbol('phi')" />
<input type="button" value="1" onclick="addSpecial('1')" />
<input type="button" value="2" onclick="addSpecial('2')" />
<input type="button" value="3" onclick="addSpecial('3')" />
<input type="button" value="-" onclick="addSpecial('-')" />
</div><div class="line">
<input type="button" class="roman" value="γ" onclick="addSymbol('gamma')" />
<input type="button" value="0" onclick="addSpecial('0')" />
<input type="button" value="." onclick="addSpecial('.')" />
<input type="button" value="=" onclick="addSpecial('=')" />
<input type="button" value="+" onclick="addSpecial('+')" />
</div>
</div>
</form>
</div>
</body>
</html>
Any help is appreciated.
I am able to get some functionality, (with some parenthesis errors). If it's not working AT ALL, I suspect you are loading the javascript before the DOM is ready which will cause errors with you getElementById. Try either loading in a window.onload handler or put the script before the closing body tag.
I am a beginner and trying to write a simple Calculator in Javascript but something is wrong.
When the user enters numbers, "Number 1" and "Number 2", then the following should occur for addition, subtraction, multiply and division (for example):
Number1 = 5, Number2 = 3
then => 5 + 3 = 8,
5 - 3 = 2,
5 * 3 = 15,
5 / 3 = 1.6
When the user gives numbers to specific equation, then displays the result of these operations.
<html>
<head>
<title>Function Calculator</title>
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
/*function formValidator(){
var number = document.getElementById('number');
if(isNumeric(number, "Only Numbers pls")){
return true;
}return false;
}
function notEmpty(elem, helperMsg){ //gia keno
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show_clear(){
document.form1.display.value=null;
num1= null;
num2 = null;
lastaction= null;
action = null;
} */
}
</script>
</head>
<body>
<table width="400" align="center" bgcolor="#C0C0C0">
<form name="form1" action="">
<tr align="center">
<td width="600" height="112" align="center" border="1">
<h1 align="center"> Calculator </h1>
Number 1: <input name="num1" type="text" size=10/>
Number 2: <input name="num2" type="text" size=10/>
</td>
</tr>
<tr align="center">
<td width="500">
<input name="num3" type="text" size=10/> +
<input name="num4" type="text" size=10/> =
<input name="result1" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num5" type="text" size=10/> -
<input name="num6" type="text" size=10/> =
<input name="result2" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num7" type="text" size=10/> *
<input name="num8" type="text" size=10/> =
<input name="result3" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num9" type="text" size=10/> /
<input name="num10" type="text"size=10/> =
<input name="result4" type="text" size=10/>
</td>
</tr>
<br/>
<td height="13"></tr>
<tr align="center" width="100">
<td>
<input name="result" type="button" onClick="show_cal()" value="Result" />
<input type="button" onClick="show_clear()" value="Clear"/>
</td>
</tr>
</form>
</table>
</body>
</html>
the problem is you have a function sum within a function show_calc and you don't call this function.
You need call the function num when finish the showcalc function.
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
num();
}
But I better ways to make this correctly.
Your code could be cleaner and violates DRY (Don't Repeat Yourself) repeatedly.
Try this:
<form action="javascript:void(null);" method="post" onSubmit="calculate(this);">
<p><label>Number 1: <input type="number" /></label></p>
<p><label>Number 2: <input type="number" /></label></p>
<p><input type="submit" value="Calculate" /></p>
<p>N1 + N2 = <span>-</span></p>
<p>N1 - N2 = <span>-</span></p>
<p>N1 * N2 = <span>-</span></p>
<p>N1 / N2 = <span>-</span></p>
</form>
<script type="text/javascript">
function calculate(form) {
var fc = form.children,
n1 = parseInt(fc[0].children[0].children[0].value || 0,10),
n2 = parseInt(fc[1].children[0].children[0].value || 0,10);
fc[3].children[0].firstChild.nodeValue = n1+n2;
fc[4].children[0].firstChild.nodeValue = n1-n2;
fc[5].children[0].firstChild.nodeValue = n1*n2;
fc[6].children[0].firstChild.nodeValue = n1/n2;
}
</script>
JSFiddle demonstration
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" href="cal.css">
<script src="./calc.js"></script>
</head>
<body>
<div class="calculator">
<div id="textBox1">
<input type="text"id="textBox" placeholder="0"/>
</div>
<div class="buttons">
<button class="calc-buttons" onclick="disPlay('1')" value="1">1</button>
<button class="calc-buttons" onclick="disPlay('2')" value="2">2</button>
<button class="calc-buttons" onclick="disPlay('3')" value="3">3</button>
<button class="calc-buttons" onclick="disPlay('4')" value="4">4</button>
<button class="calc-buttons" onclick="disPlay('5')" value="5">5</button>
<button class="calc-buttons" onclick="disPlay('6')" value="6">6</button>
<button class="calc-buttons" onclick="disPlay('7')" value="7">7</button>
<button class="calc-buttons" onclick="disPlay('8')" value="8">8</button>
<button class="calc-buttons" onclick="disPlay('9')" value="9">9</button>
<button class="calc-buttons" onclick="disPlay('0')" value="0">0</button>
<button class="calc-buttons" onclick="disPlay('+')" value="+">+</button>
<button class="calc-buttons" onclick="disPlay('-')" value="-">-</button>
<button class="calc-buttons" onclick="disPlay('*')" value="*">*</button>
<button class="calc-buttons" onclick="disPlay('/')" value="/">/</button>
<button class="calc-buttons" onclick="disPlay('%')" value="%">%</button>
<button class="calc-buttons" onclick="clr()" value="clear">C</button>
<button class="calc-buttons" onclick="disPlay('.')" value=".">.</button>
<button class="calc-buttons" onclick="backSpace()" value="B">B</button>
<button class="calc-buttons-equal" onclick="result()" value="=">=</button>
</div>
</div>
</body>
</html>
calc.js:---
var res = "";
function disPlay(x) {
nan = document.getElementById("textBox").value;
if (nan === "NaN" || nan === "Infinity" || nan === "undefined" || nan === "-Infinity") { // delete Nan,infinity,undefined after entering the numbers.
document.getElementById("textBox").value = "";
}
if (res && (x >= 0 || x <= 0)) {
res = false;
document.getElementById("textBox").value = "";
document.getElementById("textBox").value += x;
} else {
document.getElementById("textBox").value += x;
res = false;
var y = [];
y = document.getElementById("textBox").value;
p = y.length;
if ((y[p - 2] === "*" || y[p - 2] === "/" || y[p - 2] === "%" || y[p - 2] === "+" || y[p - 2] === "-" || y[p - 2] === ".") && (x === "*" || x === "/" || x === "%" || x === "+" || x === "-" || x === ".")) {
document.getElementById("textBox").value = y.slice(0, p - 1);
}
}
}
function clr() {
document.getElementById("textBox").value = "";
}
function backSpace() {
bakSpa = document.getElementById("textBox").value;
if (bakSpa === "NaN" || bakSpa === "Infinity" || bakSpa === "undefined" || bakSpa === "-Infinity") {
document.getElementById("textBox").value = "";
} else {
var value = document.getElementById("textBox").value;`enter code here`
document.getElementById("textBox").value = value.substr(0, value.length - 1);
}
}
function result() {
exp = "";
exp = document.getElementById("textBox").value;
l = exp.length;
if (exp[0] == '*' || exp[0] == '/' || exp[0] == '%' || exp[0] == '+' || exp[l - 1] == '+' || exp[l - 1] == '%' || exp[l - 1] == '/' || exp[l - 1] == '*' || exp[l - 1] == '-') {
document.getElementById("textBox").value = 'NaN';
} else {
exp = document.getElementById("textBox").value;
res = eval(exp);
console.log(res);
document.getElementById("textBox").value = res;
if(res===undefined){
document.getElementById("textBox").value = "";
}
}
}
cal.css:-
*{
box-sizing: border-box;
text-align: center;
padding: 0;
margin: 0;
}
::placeholder {
color: red;
opacity: 1;
}
body {
background: #F6F6F6;
}
.calculator {
max-width: 400px;
margin: 0 auto;
border: 2px solid #111;
border-radius: 5px;
display:flex;
flex-wrap: wrap;
flex: 0 1 60%;
min-width:400px;
color: #F6F6F6;
}
#calc-buttons ,.calc-buttons {
background-color: gray;
border: none;
color: white;
padding-left: 60px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:125px;
height: 50px;
border-radius: 6px;
}
.calc-buttons-equal{
background-color:orange;
border: none;
color: white;
padding-left: 190px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:388px;
height: 50px;
border-radius: 6px;
}
#textBox1 input {
background: none;
border: none;
box-shadow: none;
padding: 10px;
width: 100%;
border-bottom: 2px solid #111;
color: #333;
text-align: right;
font-size: 40px;
border-radius: 0;
}
I created an api to make a calculator automatically, just put the api inside script tag (<script src="https://calculatorapi.netlify.app/api.js>"). I created this api to help more people build their own web apps. If you want to style my api calculator just do:
<style>
<!--To result input-->
input[type="text"] {
<!--Your style-->
}
<!-- To Calculator buttons e.g: 1,2,3 -->
input[type="buttons"] {
<!-- Your style -->
}
</style>
<!DOCTYPE html>
<html>
<head>
<script>
z="";
fun =""
ans="";
function dis(val)
{
ans = document.getElementById("result").value;
if (ans === "Infinity" ||ans === "-Infinity" || ans === "undefined") {
document.getElementById("result").value = "";
}
if(z&& (val >= 0 || val <= 0)){
z = false;
document.getElementById("result").value="";
document.getElementById("result").value+=val;
}
else{
ans = document.getElementById("result").value+=val;
z = false;
var y = [];
y = document.getElementById("result").value;
p = y.length;
if ((y[p - 2] ==="*" ||y[p - 2] ==="/" ||y[p - 2] ==="%" ||y[p - 2] ==="+" ||y[p - 2] ==="-" ||y[p - 2] ===".") && (val ==="*" ||val ==="/" ||val ==="%" ||val ==="+" ||val ==="-" ||val ===".")) {
document.getElementById("result").value = y.slice(0, p - 2)+y[p-1];
}
}
}
function solve()
{
let i,j;
i= ans;
j=i[i.length-1];
if(i[0]==="*"||i[0]=="/"||i[0]==="%"||i[0]==="+"){
document.getElementById("result").value = undefined;
}
else if(j==="*"||j==="/"||j==="%"||j==="."||j==="+"||j==="-"){
document.getElementById("result").value = undefined;
}
else {
z="";
let x = document.getElementById("result").value;
z = eval(x);
if(z===undefined)
{
document.getElementById("result").value = "";
}
else{
document.getElementById("result").value = z;
}
}
}
function clr()
{
document.getElementById("result").value =""
}
function back()
{
var i = document.getElementById("result").value;
if(i==="undefined"||i==="infinity"||i==="-infinity"){
document.getElementById("result").value ="";
}
else{
document.getElementById("result").value = i.substr(0, i.length - 1);
}
}
</script>
<style>
* {
background-color: black;
height: 100%;
width: 100%;
margin: 0px;
text-align: center;
box-sizing: border-box;
}
.disply{
height: 30%;
width: 100%;
box-sizing: border-box;
}
.functions{
height: 68%;
width: 100%;
box-sizing: border-box;
}
input{
background-color:black;
border:whitesmoke;
color: white;
text-align: center;
font-size: 45px;
cursor: pointer;
height: 20%;
width: 24.2%;
}
button{
background-color:lightslategray;
color: white;
text-align: center;
font-size: 90px;
cursor: pointer;
height: 18%;
width: 24%;
border: none;
border-radius: 50%;
}
button[type=button4]{
width: 48.4%;
padding-right: 24.2%;
border-radius: 40%;
}
button[type=button2]{
background-color: orange;
font-size: 60px;
}
button[type=button1]{
background-color: whitesmoke;
color: black;
font-size: 60px;
}
input[type=text]{
height: 100%;
width: 100%;
background-color:black;
text-align: right;
color: white;
font-size: 100px;
}
::placeholder{
color: bisque;
}
</style>
</head>
<body>
<div class="disply">
<input type="text" id="result" placeholder="0"/>
</div>
<div class="functions">
<button type="button1" value="AC" onclick="clr()">AC</button>
<button type="button1"value="/" onclick="dis('/')">/</button>
<button type="button1"value="%" onclick="dis('%')">%</button>
<button type="button2"value="back" onclick="back()">back</button>
<button type="button3"value="7" onclick="dis('7')">7</button>
<button type="button3"value="8" onclick="dis('8')">8</button>
<button type="button3"value="9" onclick="dis('9')">9</button>
<button type="button2"value="*" onclick="dis('*')">*</button>
<button type="button3"value="4" onclick="dis('4')">4</button>
<button type="button3"value="5" onclick="dis('5')">5</button>
<button type="button3"value="6" onclick="dis('6')">6</button>
<button type="button2"value="-" onclick="dis('-')">-</button>
<button type="button3"value="1" onclick="dis('1')">1</button>
<button type="button3"value="2" onclick="dis('2')">2</button>
<button type="button3"value="3" onclick="dis('3')">3</button>
<button type="button2"value="+" onclick="dis('+')">+</button>
<button type="button4"value="0" onclick="dis('0')">0</button>
<button type="button3"value="." onclick="dis('.')">.</button>
<button type="button2"value="=" onclick="solve()">=</button>
</div>
</body>
</html>