I have a form that calculates price per square meters of ceiling.
And ion range slider as input, then it calculates price and outputs data to inputs. But I need to change inputs with span or div. Any suggestions?
Here is the html:
<form id="calc">
<div id="1">
<p>
<input id="rel" oninput="
var v = this.value;
this.form.new.value = isNaN(v) ? '' : (v * 450).toFixed (0);
var v = this.value; this.form.new2.value = isNaN(v) ? '' : (v * 650).toFixed (0)"
style="display: none;">
</p>
<p><p>
<span class="small">from </span>
<span class="new"></span>
<input type="text" disabled="disabled" name="new" size="2" maxlength="4" value="0" >
<span class="small">to </span><input type="text" disabled="disabled" name="new2" size="2" maxlength="4" value="0">
<div class="result" id="result">
</div>
</p>
</div>
</form>
and here you can find how it works http://jsfiddle.net/khvoroffski/50apyyr5/
Please make a good look at this example , I made you func you make design (css) .
/*Chrome*/
#media screen and (-webkit-min-device-pixel-ratio:0) {
input[type='range'] {
overflow: hidden;
width: 10px;
-webkit-appearance: none;
background-color: #9a905d;
}
input[type='range']::-webkit-slider-runnable-track {
height: 10px;
-webkit-appearance: none;
color: #13bba4;
margin-top: -1px;
}
input[type='range']::-webkit-slider-thumb {
width: 10px;
-webkit-appearance: none;
height: 10px;
cursor: ew-resize;
background: #434343;
box-shadow: -10px 0 0 0px #43e5f7;
}
}
/** FF*/
input[type="range"]::-moz-range-progress {
background-color: #43e5f7;
}
input[type="range"]::-moz-range-track {
background-color: #9a905d;
}
/* IE*/
input[type="range"]::-ms-fill-lower {
background-color: #43e5f7;
}
input[type="range"]::-ms-fill-upper {
background-color: #9a905d;
}
<script>
function E (ele) {return document.getElementById(ele)}
function CALC ( value_ ) {
var SPAN = E("SliderValue")
var FROM = E("FROM")
var TO = E("TO")
var currentValue = E("SliderValue")
var WIDTH_OF_SLIDER = E("rel")
var positionInfo = WIDTH_OF_SLIDER.getBoundingClientRect();
var width_IN_PIX = positionInfo.width;
FROM.value = isNaN(value_) ? '' : (value_ * 450).toFixed (0);
TO.value = isNaN(value_) ? '' : (value_ * 650).toFixed (0);
currentValue.innerHTML = value_ + ""
var COEFICIJENT = width_IN_PIX / 100
currentValue.style.left = ( value_ * COEFICIJENT ) + "px"
}
</script>
<form id="calc"
>
<div id="1">
<p>
<input id="rel"
oninput="CALC(this.value)"
type="range"
maxValue="50"
minValue="5"
value="0"
step="1"
style="width:100%;background-color:red;" >
</p>
<span class="small" >from </span>
<span id="SliderValue" style="position:absolute;left:0;" > </span>
<input type="text" id="FROM" value="0" />
<span class="small">to </span>
<input type="text" id="TO" value="0" />
<div class="result" id="result" > </div>
</div>
</form>
Related
I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
function appearafter2() {
document.getElementById("buttonappear2").style.display = "block";
document.getElementById("button2").style.display = "block";
document.getElementById("hinzufuegen2").style.display = "none";
}
function myFunction2() {
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList3").appendChild(cln);
}
function deleteFunction2() {
var list3 = document.getElementById("myList3");
var divs = Array.from(list3.getElementsByTagName("div"));
// If the number of divs is 4, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 4) {
document.getElementById("button2").style.display = "none";
}
var lastDivToDelete2 = divs[divs.length - 1];
list3.removeChild(lastDivToDelete2);
}
function allFunction2() {
myFunction2();
appearafter2();
}
#button2 {
display: none;
}
#buttonappear2 {
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#myList3 {
display: none;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="allFunction2()">
+ Loc de munca
</div>
<div id="myList3">
<div id="button2" onclick="deleteFunction2()">Șterge</div>
<div id="myList4">
<div id="addingNewJob">
<label class="label-job-input" for="job-input-1">Numele firmei</label>
<select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
<option value="scoala">școală profesională</option>
<option value="lic">liceu</option>
<option value="fac">facultate</option></select>
<label class="label-job-input" for="job-input-2">Postul ocupat
</label>
<input size="1" type="text" id="job-input-3" /><br />
<label class="label-data2" for="job-input-3">din data</label><label class="label-data2" for="job-input-4">până la data</label><br />
<input type="number" style="width: 48%" />
<input type="number" style="width: 50%; margin-left: 6px" />
</div>
</div>
</div>
<div onclick="allFunction2()" id="buttonappear2">
+ Loc de munca
</div>
Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
Updated the answer, check if this is what you are trying to achieve.
function myFunction2() {
var cln = '<div class="list-item">'+
'<div id="addingNewJob">'+
'<label class="label-job-input" for="job-input-1">Numele firmei</label>'+
'<select size="1" type="text" id="job-input-1" /></div>';
document.getElementById("myList3").innerHTML+=cln;
document.getElementById("buttonappear2").classList.remove('hide');
document.getElementById("button2").classList.remove('hide');
document.getElementById("hinzufuegen2").classList.add('hide');
}
function deleteFunction2() {
var divs = Array.from(document.querySelectorAll(".list-item"));
if(divs.length>0){
var lastDivToDelete2 = divs[divs.length - 1];
document.getElementById("myList3").removeChild(lastDivToDelete2);
}
if(divs.length==1){
document.getElementById("buttonappear2").classList.add('hide');
document.getElementById("button2").classList.add('hide');
document.getElementById("hinzufuegen2").classList.remove('hide');
}
}
.hide{
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="myFunction2()">+ Loc de munca</div>
<div id="myList3">
<div id="button2" class="hide" onclick="deleteFunction2()">Șterge</div>
</div>
școala generală școală profesională liceu facultate
<label class="label-job-input" for="job-input-2">Postul ocupat</label>
<form>
<input size="1" type="text" id="job-input-3" />
<br />
<label class="label-data2" for="job-input-3">din data</label>
<label class="label-data2" for="job-input-4">până la data</label>
<br />
<input type="number" style="width: 48%;" />
<input type="number" style="width: 50%; margin-left: 6px;" />
</form>
<div onclick="myFunction2()" class="hide" id="buttonappear2">+ Loc de munca</div>
in my class we are using firstChild.nodeValue to display text if a user enters in an incorrect value. However, I can't get my two other fields to display the error message and only the first one. What am I doing wrong? When I run it in the code snipped is says that the nodeValue is null. I have the error messages display through a span and they are being used by the firstChild.nodeValue.
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseInt( $("investment").value);
var rate = parseFloat( $("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment==="" || investment < 100 || investment > 100000){
$("investment_error").firstChild.nodeValue="Must be an integer from 100 - 100,000";
}
else if (rate ==="" || rate <0.1 || rate >12){
$("rate_error").firstChild.nodeValue="Must be a value from .1 - 12";
}
else if (years ==="" || years <1 || years > 50){
$("years_error").firstChild.nodeValue="Must be an integer from 1 - 50";
}
var nt = 4*years;
var amount = investment * (1 + (rate/4)) ** nt;
$("future_value").value=amount.toFixed(2);
}
var clear_fields = function (){
$("investment").value="";
$("rate").value="";
$("years").value="";
$("future_value").value="";
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick=clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48%;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
Its working on the first span becouse you have space between the span tags as:
with space
<span id="investment_error"> </span>
without
<span id="rate_error"></span>
In any case you should use innerHTML instead.
first child is good in case you already have a child in the html tags like this
<div>
<p id="i_am_div_first_child"> first child</p>
</div>
please hit correct answer if that was helpfull.
So what is the difference? A simple test will show you why.
console.log("1:", document.querySelector("#s1").firstChild)
console.log("2:", document.querySelector("#s2").firstChild)
<span id="s1"> </span>
<span id="s2"></span>
The one has a whitespace in it, the others do not the one with the whitespace has a firstChild, the others do not.
What should you do?
I would just set the textContent or innerHTML of the span and not set the nodeValue.
And another issue with your code, is you have
var rate = parseFloat( $("rate").value);
and
if ( rate==="")
That empty string check is not going to happen to be true ever since parseFloat is going to return NaN.
$("rate_error").firstChild returns null because it has no childrne (not even whit space), and so does not have a nodeValue property.
You could just use innerHTML instead of firstChild.nodeValue.
Also you don't need the else, just tell the user immediately all they have to fix.
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var investment = parseInt($("investment").value);
var rate = parseFloat($("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment === "" || investment < 100 || investment > 100000) {
$("investment_error").innerHTML = "Must be an integer from 100 - 100,000";
}
if (rate === "" || rate < 0.1 || rate > 12) {
$("rate_error").innerHTML = "Must be a value from .1 - 12";
}
if (years === "" || years < 1 || years > 50) {
$("years_error").innerHTML = "Must be an integer from 1 - 50";
}
var nt = 4 * years;
var amount = investment * (1 + (rate / 4)) ** nt;
$("future_value").value = amount.toFixed(2);
}
var clear_fields = function() {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("future_value").value = "";
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick = clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48 %;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
On giving inputs to my temperature,Humidity,Number of people fields, i want my speed n Temperature fields to be automatically get coloured. Like when i give input as temperature=1,Humidity=1,Number Of people=1, on click on sumbit button i want Speed n Temperature field -1st box should be get coloured. Similarly on giving different inputs,i want my speed n temperature box should get coloured. how should i do dat???? Any kind of help will useful!!
<html>
<frameset rows="50%,50%">
<frame name="top" src="k7.php"/>
<frame name="bottom" src="n3.html"/>
</frameset>
</html>
This is my k7.php code
<?php
session_start();
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['bttn'] ) && !empty( $_POST['type'] ) ){
$type=$_POST['type'];
$bttn=$_POST['bttn'];
$_SESSION['buttonClicked'][ $type ]=$bttn;
exit( json_encode( $_SESSION['buttonClicked'] ) );
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Set Colours of Buttons</title>
<style>
.green{
background-color: green;
border: 1px solid black;
color: white;
padding: 8px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
.blue{
background-color: blue;
border: 1px solid black;
color: white;
padding: 8px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
.yellow{
background-color: yellow;
border: 1px solid black;
color: black;
padding: 8px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
.red{
background-color: red;
border: 1px solid black;
color: white;
padding: 8px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
input[type='button']{
border: 1px solid black;
padding: 8px 30px;
margin:0 0.25rem;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
</style>
<script>
(function(){
var colours={
1:'red',
2:'blue',
3:'green',
4:'yellow'
};
var flags={
passive:true,
capture:false
};
function setcolours(e){
var _class=this.dataset.class;
var col=this.parentNode.querySelectorAll('input[type="button"][data-class="'+_class+'"]');
/* Clear previous colour classes assigned */
col.forEach(function(e,i,a){
Object.values( colours ).forEach(function( c ){
e.classList.remove( c );
});
});
/* Add colour class to any element with a value equal to or less that selected button value */
for( var i=this.value; i > 0; i-- ){
try{
if( col[ i - 1 ].nodeType==1 )col[ i - 1 ].classList.add( colours[ col[ i - 1 ].value ] )
}catch( err ){
console.info( err );
continue;
}
}
ajax( this.value, this.dataset.type );
}
function ajax( value, type ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ){
document.getElementById('results').innerHTML=this.response;
}
};
var params='bttn='+value+'&type='+type;
xhr.open( 'post', location.href, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
}
function bindEvents(e){
var col = document.querySelectorAll('input[type="button"]');
if( col && col.length > 0 ){
for( var n in col ){
if( col[ n ].nodeType==1 ){
col[ n ].addEventListener( 'click', setcolours.bind( col[ n ] ), flags );
}
}
}
}
document.addEventListener( 'DOMContentLoaded', bindEvents, flags );
}());
</script>
</head>
<body>
<div align="left">Temperature </div>
<input type="button" class="button" data-class='b' data-type='temperature' value="1">
<input type="button" class="button" data-class='b' data-type='temperature' value="2">
<input type="button" class="button" data-class='b' data-type='temperature' value="3">
<input type="button" class="button" data-class='b' data-type='temperature' value="4">
<br />
<br />
<div align="left">Humidity</div>
<input type="button" class="button1" data-class='b1' data-type='humidity' value="1">
<input type="button" class="button1" data-class='b1' data-type='humidity' value="2">
<input type="button" class="button1" data-class='b1' data-type='humidity' value="3">
<input type="button" class="button1" data-class='b1' data-type='humidity' value="4">
<br />
<br />
<div align="left">Number of people </div>
<input type="button" class="button2" data-class='b2' data-type='people' value="1">
<input type="button" class="button2" data-class='b2' data-type='people' value="2">
<input type="button" class="button2" data-class='b2' data-type='people' value="3">
<input type="button" class="button2" data-class='b2' data-type='people' value="4">
<br />
<br />
<input type='submit' value='submit'>
</form>
<pre id='results'></pre>
</body>
</html>
This is my n3.html code
<html>
<head>
<style>
.box1 {
width: 100px;
height: 45px;
margin: 0px;
padding: 0px;
float: left;
background-color:white;
border: 1px solid black;
}
</style>
</head>
<body>
<div align="left">Speed: </div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<br><br>
<br>
<div align="left">Temperature: </div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
<div align="right" class="box1"></div>
</body>
</html>
Hopefully the following can be adapted to your frameset layout somehow - it uses a new function but is otherwise the same code as previous answer ( more or less anyway )
<?php
session_start();
$svar='buttonClicked';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['bttn'] ) && !empty( $_POST['type'] ) ){
$type=$_POST['type'];
$bttn=$_POST['bttn'];
$_SESSION[ $svar ][ $type ]=$bttn;
header( 'HTTP/1.1 200 OK', true, 200 );
header( 'Content-Type: application/json' );
exit( json_encode( $_SESSION[ $svar ] ) );
}
}
if( !empty( $_GET['reset'] ) && $_GET['reset']=='true' && isset( $_SESSION[ $svar ] ) ){
unset( $_SESSION[ $svar ] );
header('Location: '.$_SERVER['SCRIPT_NAME'] );
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Set Colours of Buttons</title>
<style>
body, body *{
font-family:calibri,verdana,arial;
font-size:1rem;
color:black;
}
input[type='button']{
background-color:white;
border: 1px solid black;
padding: 0.5rem 2rem;
margin:0 0.25rem;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
float: left;
}
.green{
background-color: green!important;
}
.blue{
background-color: blue!important;
}
.yellow{
background-color: yellow!important;
}
.red{
background-color: red!important;
}
.pink{
background-color: pink!important;
}
.orange{
background-color: orange!important;
}
.purple{
background-color: purple!important;
}
.brown{
background-color: brown!important;
}
legend,fieldset{
border:none;
}
legend{
border-bottom:1px solid gray;
border-left:3px solid black;
padding:0.5rem;
margin:0 0 0 0.25rem;
}
fieldset.boxes > div{
width: 4.5rem;
height: 2rem;
margin: 0 0.25rem;
padding: 0;
float: left;
background-color:white;
border: 1px solid black;
}
</style>
<script>
(function(){
var obj={};
var colours={
1:'red',
2:'orange',
3:'yellow',
4:'pink',
5:'brown',
6:'purple',
7:'blue',
8:'green'
};
var flags={
passive:true,
capture:false
};
function setcolours(e){
var col=this.parentNode.querySelectorAll( 'input[type="button"]' );
obj[ this.parentNode.dataset.type ]=this.value;
/* Clear previous colour classes assigned */
col.forEach(function(e,i,a){
Object.values( colours ).forEach(function( c ){
e.classList.remove( c );
});
});
/* Add colour class to any element with a value equal to or less that selected button value */
for( var i=this.value; i > 0; i-- ){
try{
if( col[ i - 1 ].nodeType==1 )col[ i - 1 ].classList.add( colours[ col[ i - 1 ].value ] )
}catch( err ){
console.info( err );
continue;
}
}
/* set the colour of div boxes */
setboxes.call( this, e, obj );
/* send the ajax request to store values into session variables &/or whatever actions are required */
ajax( this.value, this.parentNode.dataset.type );
}
/* new function to set colour of boxes if all buttons clicked have same value */
function setboxes( event, _obj ){
/* get references from global obj */
var keys=Object.keys( _obj );
var values=Object.values( _obj );
if( keys.length==3 ){
/* Are all items of the same value? */
var value=values.reduce( function(a,b){ return a==b ? a : false } );
/* get nodelist of boxes */
var col=document.querySelectorAll('fieldset.boxes div');
/* If the values are all the same - set colour */
if( value ){
/* clear previous colour - if any */
col.forEach(function(e,i,a){
Object.values( colours ).forEach(function( c ){
e.classList.remove( c );
});
});
/* assign new colour */
for( var i=value; i > 0; i-- ){
try{
col.forEach(function(item,index,array){
if( item.dataset.value <= value )item.classList.add( colours[ value ] );
});
}catch( err ){
console.info( err )
continue;
}
}
} else {
/* mismatch in values - remove colours */
col.forEach(function(e,i,a){
Object.values( colours ).forEach(function( c ){
e.classList.remove( c );
});
});
/* ???? */
values.forEach( function(value){
col.forEach( function(box){
if( box.dataset.value <= value ) box.classList.add( colours[ box.dataset.value ] )
});
});
}
}
}
function ajax( value, type ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ){
document.getElementById('results').innerHTML=this.response;
}
};
var params='bttn='+value+'&type='+type;
xhr.open( 'post', location.href, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
}
function reset(e){
location.search='reset=true';
}
function bindEvents(e){
var col = document.querySelectorAll('form > fieldset > input[type="button"]');
if( col && col.length > 0 ){
for( var n in col ){
if( col[ n ].nodeType==1 ){
col[ n ].addEventListener( 'click', setcolours.bind( col[ n ] ), flags );
}
}
}
var bttn = document.querySelectorAll('form > input[ type="reset" ]')[0];
bttn.onclick=reset;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, flags );
}());
</script>
</head>
<body>
<form action='chk.php' method='post'>
<fieldset data-type='temperature'>
<legend>Temperature</legend>
<input type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<input type="button" value="4" />
<input type="button" value="5" />
<input type="button" value="6" />
<input type="button" value="7" />
<input type="button" value="8" />
</fieldset>
<fieldset data-type='humidity'>
<legend>Humidity</legend>
<input type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<input type="button" value="4" />
<input type="button" value="5" />
<input type="button" value="6" />
<input type="button" value="7" />
<input type="button" value="8" />
</fieldset>
<fieldset data-type='people'>
<legend>Number of people</legend>
<input type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<input type="button" value="4" />
<input type="button" value="5" />
<input type="button" value="6" />
<input type="button" value="7" />
<input type="button" value="8" />
</fieldset>
<br />
<br />
<fieldset class='boxes' data-type='box-speed'>
<legend>Speed</legend>
<div data-value=1></div>
<div data-value=2></div>
<div data-value=3></div>
<div data-value=4></div>
<div data-value=5></div>
<div data-value=6></div>
<div data-value=7></div>
<div data-value=8></div>
</fieldset>
<fieldset class='boxes' data-type='box-temperature'>
<legend>Temperature</legend>
<div data-value=1></div>
<div data-value=2></div>
<div data-value=3></div>
<div data-value=4></div>
<div data-value=5></div>
<div data-value=6></div>
<div data-value=7></div>
<div data-value=8></div>
</fieldset>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
</form>
<pre id='results'></pre>
</body>
</html>
I have a table that has some values that whenever the edit button on that row gets clicked all of the values on that row get passed to the corresponding input tags so they can be edited.
This is my code:
$(document).ready(function() {
//"use strict";
cargarDatos();
$('#frmContacto').submit(function(event) {
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
guardarDatos();
cargarDatos();
});
$('input').on('blur', function() {
$(this).addClass('marcado');
//alert(this.value);
});
$('.btnEditar').on('click', function(event) {
event.preventDefault();
//Here is where I call a function that is supposed to pass values to the inputs on my html page so I could update the values
});
$('#inputFoto').on('change', function(e) {
precargarImagen(this);
});
$(window).load(function() {
$(document).ready($('#efecto1').addClass('animacion1'));
// $(document).ready($('#efecto2').addClass('animacion1'));
// cargarDatos();
});
});
/*jshint latedef:false */
function guardarDatos() {
name = $('#inputNombre').val();
direccion = $('#inputDireccion').val();
telefono = $('#inputTelefono').val();
fecha = $('#inputFecha').val();
email = $('#inputEmail').val();
color = $('#inputColor').val();
dataFoto = $("#imgFoto").attr("src");
/*alert("Sus datos son: \n" + nombre + "\n"
+ direccion + "\n" + telefono + "\n"
+ fecha + "\n" + email+ "\n" + color);*/
contacto = {
nombre: name,
direccion: direccion,
telefono: telefono,
fecha: fecha,
email: email,
color: color,
foto: dataFoto
};
contactos.push(contacto);
console.log(JSON.stringify(contactos));
localStorage.setItem('lstcontactos2', JSON.stringify(contactos));
}
/*jshint latedef:false */
function cargarDatos() {
var data = localStorage.getItem('lstcontactos2');
contactos = data && JSON.parse(data);
if (contactos == null)
contactos = new Array();
$('#tablaContactos').bootstrapTable({
data: contactos
});
}
function btnEditar(value) {
console.log("valueformat " + value);
return '<span class="glyphicon glyphicon-pencil"></span>';
}
function imgFoto(value) {
return '<img id="imgFoto" src="' + value +
'" style="width:auto;height:160px;">';
}
function precargarImagen(inputfile) {
var file = inputfile.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
$(".file-caption-name").html(file.name);
$(".file-preview-frame").empty();
$(".file-preview-frame").
append('<img id="imgFoto" src="' + reader.result +
'" style="width:auto;height:160px;">');
};
reader.readAsDataURL(file);
inputfile.val(img.src);
} else {
alert("Archivo no soportando!");
}
}
.marcado {
color: #ff0000;
border: 1px solid #0000ff;
}
.desmarcado {
color: #00000;
border: 0;
}
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
text-align: right;
opacity: 0;
filter: alpha(opacity=0);
opacity: 0;
background: none repeat scroll 0 0 transparent;
cursor: inherit;
display: block;
}
.file-preview-frame {
display: table;
margin: 8px;
height: 160px;
width: 160px;
border: 1px solid #ddd;
box-shadow: 1px 1px 5px 0px #a2958a;
padding: 6px;
float: left;
text-align: center;
vertical-align: middle;
transition: all .4s ease-in-out;
}
.file-preview-frame:hover {
box-shadow: 3px 3px 5px 0px #333;
cursor: pointer;
background-size: 150% 150%;
transform: scale(2.2);
}
/* Shrink */
.hvr-shrink {
display: inline-block;
vertical-align: middle;
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
-webkit-transition-duration: 0.3s;
transition-duration: 0.3s;
-webkit-transition-property: transform;
transition-property: transform;
}
.hvr-shrink:hover,
.hvr-shrink:focus,
.hvr-shrink:active {
-webkit-transform: scale(0.9);
transform: scale(0.9);
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset=utf-8>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>Contactos</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.css">
<link rel="stylesheet" href="estilos.css" />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="script.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/locale/bootstrap-table-es-AR.min.js"></script>
</head>
<body>
<div class="container">
<h1>Contactos personales</h1>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Listado</a>
</div>
</div>
</nav>
<div class="row show-grid">
<div class="animacion1">
<div class="col-sm-6">
<table id="tablaContactos" class="table table-hover" data-toggle="table" data-search="true" data-row-style="rowStyle" data-show-refresh="true" data-show-toggle="true" data-show-columns="true">
<thead>
<tr>
<th data-field="nombre" data-sortable="true">Nombre</th>
<th data-field="direccion" data-sortable="true">Dirección</th>
<th data-field="email" data-sortable="true">Email</th>
<th data-field="fecha" data-sortable="true">Fecha</th>
<th data-field="telefono" data-sortable="true" data-visible="false">Telefono</th>
<th data-field="color" data-sortable="false" data-visible="false">Color</th>
<th data-field="foto" data-sortable="false" data-formatter="imgFoto">Foto</th>
<th data-field="email" data-formatter="btnEditar"></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">Agregar/editar contacto</div>
<div class="panel-body">
<form class="form-horizontal" id="frmContacto">
<div class="form-group">
<label for="inputFoto" class="col-sm-2 control-label">Foto</label>
<div class="col-sm-10">
<div class="file-preview-frame">
<img src="" style="width:auto;height:160px;">
</div>
<input type="file" class="form-control file" id="inputFoto" data-show-upload="false" required="true">
</div>
</div>
<div class="form-group">
<label for="inputNombre" class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputNombre" placeholder="Ingrese nombre" required>
</div>
</div>
<div class="form-group">
<label for="inputDireccion" class="col-sm-2 control-label">Dirección</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputDireccion" required placeholder="Ingrese dirección personal">
</div>
</div>
<div class="form-group">
<label for="inputTelefono" class="col-sm-2 control-label">Telefono</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="inputTelefono" placeholder="Ingrese # telefónico" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Ingrese Email" required>
</div>
</div>
<div class="form-group">
<label for="inputFecha" class="col-sm-2 control-label">Fecha de nacimiento</label>
<div class="col-sm-10">
<input type="date" class="form-control" id="inputFecha" placeholder="Ingrese su fecha de nacimiento" required>
</div>
</div>
<div class="form-group">
<label for="inputColor" class="col-sm-2 control-label">Color favorito</label>
<div class="col-sm-10">
<input type="color" class="form-control" id="inputColor">
</div>
</div>
<div class="form-group">
<label for="inputURL" class="col-sm-2 control-label">Página Web</label>
<div class="col-sm-10">
<input type="url" class="form-control" id="inputURL" placeholder="Ingrese su página web">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btnGuardar">Guardar OK</button>
<button type="button" class="btn btn-default">Cancelar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
How can I do this with jquery or is there a better way of doing this? and also whenever I click the btnGuardar submit button how can I update table without having to refresh the page to see the new added values?
This is my second answer on this question. It have the same structure as the earlier answer but this one picks up all fields on the same row (wich have the same class) at once.
function edit(key) {
var x = document.getElementsByClassName("prow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
var x = document.getElementsByClassName("inputrow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "initial";
}
document.getElementById('inputA' + key ).value = document.getElementById('pA' + key ).innerHTML;
document.getElementById('inputB' + key ).value = document.getElementById('pB' + key ).innerHTML;
document.getElementById('inputC' + key ).value = document.getElementById('pC' + key ).innerHTML;
}
function save(key) {
var x = document.getElementsByClassName("prow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "initial";
}
var x = document.getElementsByClassName("inputrow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById('pA' + key ).innerHTML = document.getElementById('inputA' + key ).value;
document.getElementById('pB' + key ).innerHTML = document.getElementById('inputB' + key ).value;
document.getElementById('pC' + key ).innerHTML = document.getElementById('inputC' + key ).value;
}
*{
font-family: Arial, Helvetica, sans-serif;
}
p {
margin:0px;
}
input[type=text] {
display:none;
height:12px;
width:45px;
}
table, th, td {
border: 2px solid darkslategray ;
background:darkseagreen ;
border-collapse: collapse;
margin:0px;
padding:0px;
}
<table>
<form id=formA>
<tr>
<td>
<p id=pA1 class=prow1>value 1</p><input id=inputA1 type="text" name="A" class=inputrow1 value="value 1"></td>
<td><p id=pB1 class=prow1>value 2</p><input id=inputB1 type="text" name="B" class=inputrow1 value="value 2">
</td>
<td><p id=pC1 class=prow1>value 3</p><input id=inputC1 type="text" name="C" class=inputrow1 value="value 3">
</td>
<td><button type="button" onclick="edit(1)">edit</button><button type="button" onclick="save(1)">save</button>
</td>
</tr>
<tr>
<td>
<p id=pA2 class=prow2>value 1</p><input id=inputA2 type="text" name="D" class=inputrow2 value="value 1"></td>
<td><p id=pB2 class=prow2>value 2</p><input id=inputB2 type="text" name="E" class=inputrow2 value="value 2">
</td>
<td><p id=pC2 class=prow2>value 3</p><input id=inputC2 type="text" name="F" class=inputrow2 value="value 3">
</td>
<td><button type="button" onclick="edit(2)">edit</button><button type="button" onclick="save(2)">save</button>
</td>
</tr>
<tr>
<td colspan=4>
<input type="submit" value="Submit" style="width:100%;">
</td>
</tr>
</form>
</table>
This would be comment but I can't add a comment yet.
It may be a good idea to look at an MVVM library such as:
http://knockoutjs.com/
https://angularjs.org/
http://vuejs.org/
If you're new to the idea of MVVM I would recommend looking at knockout, although it is probably the more complex option the tutorials are excellent: http://learn.knockoutjs.com/
This line gets the text from an element and stores it in the variable y:
var y = document.getElementById('text id').innerHTML;
This line places the value stored in the y variable on the edit box:
document.getElementById('input text id').value = y;
Here it comes a working example:
function edit(key) {
document.getElementById('p' + key).style.display = "none";
document.getElementById('input' + key).style.display = "initial";
var yy = document.getElementById('p' + key).innerHTML;
document.getElementById('input' + key).value = yy;
}
function save(key) {
document.getElementById('p' + key).style.display = "initial";
document.getElementById('input' + key).style.display = "none";
var xx = document.getElementById('input' + key).value;
document.getElementById('p' + key).innerHTML = xx;
}
*{
font-family: Arial, Helvetica, sans-serif;
}
p {
margin:0px;
}
input[type=text] {
display:none;
height:12px;
width:40px;
}
table, th, td {
border: 2px solid tomato;
background:gold;
border-collapse: collapse;
margin:0px;
padding:0px;
}
<table>
<form id=formA>
<tr>
<td>
<p id=pA>value 1</p><input id=inputA type="text" name="A" value="value 1"></td><td><p id=pB>value 2</p><input id=inputB type="text" name="B" value="value 2">
</td>
</tr>
<tr>
<td>
<button type="button" onclick="edit('A')">edit 1</button><button type="button" onclick="save('A')">save 1</button></td>
<td><button type="button" onclick="edit('B')">edit 2</button><button type="button" onclick="save('B')">save 2</button>
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Submit" style="width:100%;">
</td>
</tr>
</form>
</table>
I have to write a calculator in HTML. I really can't find what is going wrong and it does not show the results. I can't find something wrong can you help? I'm running it in Chrome.
JavaScript File and and the HTML:
showresult(choise){
var n1=parsefloat(document.getElementById('num1').value);
var n2=parsefloat(document.getElementById('num2').value);
var r;
var c=choise;
switch(c)
{
case '1':
r=n1+n2;
break;
case '2':
r=n1-n2;
break;
case '3':
r=n1*n2;
break;
case '4':
r=n1/n2;
break;
case '5':
r=n2*100/n1;
break;
default:
break;
}
document.getElementById('result').innerHTML=r;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<script src="calculator.js" type="text/javascript"></script>
</head>
<body>
<h1>My calculator</h1>
<table border="1" cellpadding="5" cellspacing="5" width="600">
<tr align="center">
<td>First number</td>
<td>Second Number</td>
<td>Result</td>
</tr>
<tr align="center">
<td><input name="number1" type="text" size=10 id='num1'/></td>
<td><input name="number2" type="text" size=10 id='num2'/></td>
<td> <input type="text" id='result' readonly ></td>
</tr>
<tr>
<td colspan="3">
<button onclick="showresult('1')">+</button>
<button onclick="showresult('2')">-</button>
<button onclick="showresult('3')">*</button>
<button onclick="showresult('4')">/</button>
<button onclick="showresult('5')">%</button>
</td>
</tr>
</table>
</body>
</html>
Things to fix:
1) Assign to value, not innerHTML, when referring to an input element. (They have no content, hence no innerHTML.
2) Start a function declaration with the keyword function.
3) It’s parseFloat, not parsefloat. JavaScript is case-sensitive.
Minimally fixed code:
function showresult(choise){
var n1=parseFloat(document.getElementById('num1').value);
var n2=parseFloat(document.getElementById('num2').value);
var r;
var c=choise;
switch(c)
{
case '1':
r=n1+n2;
break;
case '2':
r=n1-n2;
break;
case '3':
r=n1*n2;
break;
case '4':
r=n1/n2;
break;
case '5':
r=n2*100/n1;
break;
default:
break;
}
document.getElementById('result').value=r;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<script src="calculator.js" type="text/javascript"></script>
</head>
<body>
<h1>My calculator</h1>
<table border="1" cellpadding="5" cellspacing="5" width="600">
<tr align="center">
<td>First number</td>
<td>Second Number</td>
<td>Result</td>
</tr>
<tr align="center">
<td><input name="number1" type="text" size=10 id='num1'/></td>
<td><input name="number2" type="text" size=10 id='num2'/></td>
<td> <input type="text" id='result' readonly ></td>
</tr>
<tr>
<td colspan="3">
<button onclick="showresult('1')">+</button>
<button onclick="showresult('2')">-</button>
<button onclick="showresult('3')">*</button>
<button onclick="showresult('4')">/</button>
<button onclick="showresult('5')">%</button>
</td>
</tr>
</table>
</body>
</html>
You are setting the innerHTML property of an input, which doesn't work
because inputs have value property, if you want to show text/data in them.
you should change this line:
document.getElementById('result').innerHTML=r;
to:
document.getElementById('result').value = r;
on creating a calculator in simple javascript, also check this tutorial out that i wrote, it may help you:
Create a calulator in javascript - Tutorial by 10code.dev
var cnum = document.getElementsByClassName('c-num')[0];
var cope = document.getElementsByClassName('c-operator')[0];
var intom = document.getElementById('intop');
var inbottom = document.getElementById('inbottom');
var newinbottom;
var newinbottom2;
var sign;
for(i=0;i<10;i++){
cnum.innerHTML +='<span class="numb" value="'+i+'" id="numid'+i+'" onclick="puton('+i+')">'+i+'</span>';
}
document.getElementById('numid0').style.order = "1";
function puton(numb){
inbottom.value += numb
}
function ans(answer){
//console.log(sign)
if(inbottom.value ==''){
alert('type input');
}else if(sign == "plus"){
newinbottom2 = inbottom.value;
intom.value = inbottom.value;
inbottom.value = parseInt(newinbottom) + parseInt(newinbottom2);
}else if(sign == "minus"){
newinbottom2 = inbottom.value;
intom.value = inbottom.value;
inbottom.value = newinbottom - newinbottom2;
}else if(sign == "divi"){
newinbottom2 = inbottom.value;
intom.value = inbottom.value;
inbottom.value = newinbottom / newinbottom2;
}else if(sign == "mul"){
newinbottom2 = inbottom.value;
intom.value = inbottom.value;
inbottom.value = newinbottom * newinbottom2;
}
sign ='';
}
function opr(opra){
if(sign != '' && sign != undefined){
ans();
}
else if(opra == "clr"){
intom.value =''
inbottom.value ='';
newinbottom='';
newinbottom='';
sign ='';
}
else if(opra == "plus"){
newinbottom = inbottom.value;
intom.value = inbottom.value;
inbottom.value = '';
sign = "plus";
}else if(opra == "minus"){
newinbottom = inbottom.value;
intom.value = inbottom.value;
inbottom.value = '';
sign = "minus";
}else if(opra == "divi"){
newinbottom = inbottom.value;
intom.value = inbottom.value;
inbottom.value = '';
sign = "divi";
}else if(opra == "mul"){
newinbottom = inbottom.value;
intom.value = inbottom.value;
inbottom.value = '';
sign = "mul";
}
}
.main{
width:100vw;
height: 100vh;
display: flex;
justify-content: center;
}
.c-body {
width: 400px;
height: 255px;
background: #ccc;
border: 1px solid;
}
.c-num{
width: 100%;
display: flex;
flex-wrap: wrap;
}
.c-operator{
flex-shrink: 1;
display: flex;
flex-wrap: wrap;
flex-direction: column;
}
.c-row{
display: flex;
flex-flow: row;
}
.c-operator [id^='numid']{
width: 90px;
flex-direction: initial;
}
[id^='numid'] {
display: flex;
flex-shrink: 1;
background: #fff;
padding: 4px;
margin: 4px;
width: 80px;
justify-content: center;
cursor: pointer;
flex-direction: inherit;
}
.c-minputs .inbox{
display: block;
width: 100%;
}
[id^='numid']:hover{
background: #f5f5f5;
}
<div class="main">
<div class="c-body">
<div class="c-minputs">
<input id="intop" type="number" class="topin inbox" disabled>
<input id="inbottom" type="number" class="bottomin inbox" placeholder="Type Here">
</div>
<div class="c-row">
<div class="c-num">
</div>
<div class="c-operator">
<span class="numb" id="numidplus" onclick="opr('plus')">+</span>
<span class="numb" id="numidminus" onclick="opr('minus')">-</span>
<span class="numb" id="numiddiv" onclick="opr('divi')">/</span>
<span class="numb" id="numidmul" onclick="opr('mul')">*</span>
<span class="numb" id="numidans" onclick="ans('answer')">=</span>
<span class="numb" id="numidclr" onclick="opr('clr')">c</span>
</div>
</div>
</div>
</div>
Make sure you declare the function correctly.
function showresult(choise) {
/* ... */
}
Also, remember that Javascript is case sensitive therefore the right way to parse a float is
parseFloat()
Lastly, as pointed out by gillesc, use the attribute value on the input element.
document.getElementById('result').value=r;
you should replace "innerHTML" to "value" in your code.
If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property instead of value
Now code becomes:
document.getElementById('result').value=r;
Here we used the value property that all input elements have to use to grab the value the user enters.
You can use this in your code
function calc(form) {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
switch(B){
case'+':
D= parseInt(A)+parseInt(C); break;
case'-':
D= parseInt(A)-parseInt(C); break;
case'*':
D=parseInt(A)*parseInt(C); break;
case'/':
D=parseInt(A)/parseInt(C); break;
}
}
<script>
var num1;
var op;
function pressBtn(value){
var prev = document.forms["calc"]["display"].value;
if (!(prev == "" && value==0)){
var newval = prev+value;
document.forms["calc"]["display"].value = newval;
}
}
function pressOP(operator){
op = operator;
var display = document.forms["calc"]["display"].value;
num1 = parseInt(display);
document.forms["calc"]["display"].value = "";
}
function pressEq(){
var display = document.forms["calc"]["display"].value;
var num2 = parseInt(display);
switch(op){
case "P":
var ans=num1+num2;
break;
case "M":
var ans=num1-num2;
break;
}
document.forms["calc"]["display"].value = ans;
}
</script>
<style>
input[type=button]{
width: 100px;
height: 100px;
font-size: 36px;
margin: 5px;
}
input[type=text]{
width: 300px;
height: 75px;
font-size: 48px;
margin: 5px;
text-align: right;
}
</style>
<body style="background: #ccc;">
<div style="width: 500px; margin: auto; background: #fff; text-align: center">
<form name="calc">
<input type="text" name="display" readonly ><br>
<input type="button" name="btn7" value="7" onClick="pressBtn(7)">
<input type="button" name="btn8" value="8" onClick="pressBtn(8)">
<input type="button" name="btn9" value="9" onClick="pressBtn(9)"><br>
<input type="button" name="btn4" value="4" onClick="pressBtn(4)">
<input type="button" name="btn5" value="5" onClick="pressBtn(5)">
<input type="button" name="btn6" value="6" onClick="pressBtn(6)"><br>
<input type="button" name="btn1" value="1" onClick="pressBtn(1)">
<input type="button" name="btn2" value="2" onClick="pressBtn(2)">
<input type="button" name="btn3" value="3" onClick="pressBtn(3)"><br>
<input type="button" name="btn0" value="0" onClick="pressBtn(0)">
<input type="button" name="btnPlus" value="+" onClick="pressOP('P')" >
<input type="button" name="btnPlus" value="-" onClick="pressOP('M')" ><br>
<input type="button" name="btnEq" value="=" onClick="pressEq();" >
</form>
</div>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>stackoverflow</title>
<style>
body{
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 35%, rgba(0,212,255,1) 100%);
}
.button {
box-shadow: 0px 10px 14px -7px #276873;
background: linear-gradient(to bottom, #599bb3 5%, #408c99 100%);
background-color: #599bb3;
border-radius: 4px;
border: 1px solid #29668f;
display: inline-block;
cursor: pointer;
color: #ffffff;
font-family: Arial;
font-size: 25px;
font-weight: bold;
padding: 21px 6px;
text-decoration: none;
text-shadow: 0px 1px 0px #3d768a;
height: 50px;
width: 80px;
padding: 0px;
}
.button:hover {
background:linear-gradient(to bottom, #408c99 5%, #599bb3 100%);
background-color:#408c99;
}
form>input{
height: 40px;
width: 329px;
border-radius: 4px;
border: none;
margin-left: 500px;
font-size: 30px;
}
table{
margin-left: 500px;
}
</style>
</head>
<body>
<div id="main">
<form name="form">
<input name="textview">
</form>
<table>
<tr>
<td><input type="button" class="button" value="Clear" onClick="c()"></td>
</tr>
<tr>
<td><input type="button" class="button" value="7" onClick="insert(7)"></td>
<td><input type="button" class="button" value="8" onClick="insert(8)"></td>
<td><input type="button" class="button" value="9" onClick="insert(9)"></td>
<td><input type="button" class="button" value="/" onClick="insert('/')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="4" onClick="insert(4)"></td>
<td><input type="button" class="button" value="5" onClick="insert(5)"></td>
<td><input type="button" class="button" value="6" onClick="insert(6)"></td>
<td><input type="button" class="button" value="-" onClick="insert('-')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="1" onClick="insert(1)"></td>
<td><input type="button" class="button" value="2" onClick="insert(2)"></td>
<td><input type="button" class="button" value="3" onClick="insert(3)"></td>
<td><input type="button" class="button" value="+" onClick="insert('+')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="0" onClick="insert(0)"></td>
<td><input type="button" class="button" value="." onClick="insert('.')"></td>
<td><input type="button" class="button" value="=" onClick="equal('=')"></td>
<td><input type="button" class="button" value="*" onClick="insert('*')"></td>
</tr>
</table>
</div>
<script>
function insert(num){
document.form.textview.value = document.form.textview.value+num;
}
function equal(){
let exp = document.form.textview.value;
if(exp){
document.form.textview.value = eval(exp)
}
else{
console.log('Something Wrong')
}
}
function c(){
document.form.textview.value = null;
}
</script>
</body>
</html>