Simple calculator in HTML and JavaScript - javascript

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>

Related

Sort table row using javascript's array method- sort( ) & reverse( )

I want to put the table row in an array than use the loop to iterate the array for comparing two rows but i don't know how this sort method of array works is it going to compare from S.No column than initials column and so on.
how to use the array method to sort()- ascending order and descending order by reverse().
I don't want to use code from google want to make my own logic just help me where i am lacking.
<!DOCTYPE html>
<html>
<head>
<style>
.tab,
.tab th,
.tab tr,
.tab td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
}
.circle {
background-color: yellow;
border-radius: 50%;
margin: 2px 22px 2px;
line-height: 10px;
padding: 12px;
text-align: center;
vertical-align: middle;
display: inline-block;
}
</style>
</head>
<body>
<h2><u>CONTACT MANAGEMENT </u></h2></br></br>
<form>
<label>First Name</label>
<input type="text" id="fname" style="text-transform: capitalize;" />
<label>Last Name</label>
<input type="text" id="lname" style="text-transform: capitalize;" /></br></br>
<label>Number</label>
<input type="text" id="phone" pattern="[1-9]{1}[0-9]{9}" maxlength="10" /></br></br>
<input type="hidden" id="hdn" value="1">
<button type="button" onclick="dataSave()">save</button></br></br>
</form>
</br></br>
<div class="div1">
<table class="tab" id="table">
<th>S.No</th>
<th>Initals</th>
<th>FullName</th>
<th>PhoneNo.</th>
<tbody id="table_row">
</tbody>
</table>
</div>
<button type="button" id="asort_btn" class="sort" onclick="asec_sort()">Asec</button>
<button type="button" id="dsort_btn" class="sort" onclick="desc_sort()">Desc</button>
<script>
function dataSave()
{
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var phone = document.getElementById('phone').value;
var firstNameArr = new Array();
var lastNameArr = new Array();
var phoneNoArr = new Array();
firstNameArr.push(first);
lastNameArr.push(last);
phoneNoArr.push(phone);
var num = parseInt(document.getElementById("hdn").value);
for(i=0;i<firstNameArr.length;i++)
{
var preFirstName = firstNameArr[i].slice(0,1);
var preLastName = lastNameArr[i].slice(0,1);
document.getElementById('table_row').innerHTML += `<tr><td>${num}</td>
<td class="circle">${preFirstName}${preLastName}</td>
<td>${firstNameArr[i]} ${lastNameArr[i]}</td>
<td>${phoneNoArr[i]}</td></tr>`;
}
num = num+1;
document.getElementById('hdn').value=num;
document.getElementById('fname').value="";
document.getElementById('lname').value="";
document.getElementById('phone').value="";
}
function asec_sort()
{
alert('hi');
var tableRowArr = new Array();
tableRowArr = document.getElementById('table_row').innerHTML;
console.log(tableRowArr);
console.log(tableRowArr.sort());
}
</script>
</body>
</html>

Javascript form calculations output

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>

How to edit html table values by passing values to input type

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>

Changing paragraph text with data from multiple inputs

I want to type in measurements of my items into text fields, and then by clicking on a button have it transfer those measurements into a paragraph to its corresponding fields. My current code looks like this
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td id="inputmeasurements">
<p align=right>
Bust:<input type="text" name="bust"><br>
Waist:<input type="text" name="waist"><br>
Hips:<input type="text" name="hips"><br>
Lenght:<input type="text" name="lenght"><br>
Shoulders:<input type="text" name="shoulders"><br>
Sleeves:<input type="text" name="sleeves"><br>
Inseam:<input type="text" name="inseam"><br>
</p>
</td>
<td id="finishedmeasurements">
<p id="m1" align=left><FONT size=3 face=Trebuchet MS>
B1 Bust inches flat </br>
W1 Waist inches flat </br>
H1 Hips inches flat </br>
L1 Length </br>
S1 Shoulders </br>
S2 Sleeves </br>
I1 Inseam </br>
</FONT></p>
</td>
</tr>
</table>
<p>This is a test for measurements entering and copying to metadata</p>
<button onclick="myFunction2()">Enter</button>
<script>
function myFunction2() {
var str = document.getElementById("m1").innerHTML;
var res = str.replace(/B1/g, "bust").replace(/W1/g, "waist").replace(/H1/g, "hips").replace(/L1/g, "lenght").replace(/S1/g, "shoulders").replace(/S2/g, "sleeves").replace(/I1/g, "inseam");
document.getElementById("m1").innerHTML = res;
}
</script>
<button onclick="myFunction3()">New</button>
<script>
function myFunction3() {
window.location.reload();
}
</script>
</body>
<style>
#finishedmeasurements {
font-family: Trebuchet MS;
line-height: 24px;
}
#inputmeasurements {
font-family: Trebuchet MS;
padding-right: 20px;
line-height: 23px;
}
input {
width: 30px !important;
margin-left: 5px;
}
</style>
</html>
Try this:
<table>
<tr>
<td id="inputmeasurements">
<p align=right>
Bust:<input type="text" name="bust" class="bust"><br>
Waist:<input type="text" name="waist" class="waist"><br>
Hips:<input type="text" name="hips" class="hips" ><br>
Lenght:<input type="text" name="lenght" class="lenght" ><br>
Shoulders:<input type="text" name="shoulders" class="shoulders" ><br>
Sleeves:<input type="text" name="sleeves" class="sleeves" ><br>
Inseam:<input type="text" name="inseam" class="inseam" ><br>
</p>
</td>
<td id="finishedmeasurements">
<p id="m1" align=left><FONT size=3 face=Trebuchet MS>
B1 Bust inches flat </br>
W1 Waist inches flat </br>
H1 Hips inches flat </br>
L1 Length </br>
S1 Shoulders </br>
S2 Sleeves </br>
I1 Inseam </br>
</FONT></p>
</td>
</tr>
</table>
<p>This is a test for measurements entering and copying to metadata</p>
<button class='enter'>Enter</button>
<button class="new">New</button>
<script>
$(function() {
$('.new').on('click', function() {
location.reload();
});
$('.enter').on('click', function() {
var str = document.getElementById("m1").innerHTML;
var bust = $('.bust').val();
var waist = $('.waist').val();
var hips = $('.hips').val();
var lenght = $('.lenght').val();
var shoulders = $('.shoulders').val();
var sleeves = $('.sleeves').val();
var inseam = $('.inseam').val();
var res = str.replace(/B1/g, bust).replace(/W1/g, waist).replace(/H1/g, hips).replace(/L1/g, lenght).replace(/S1/g, shoulders).replace(/S2/g, sleeves).replace(/I1/g, inseam);
document.getElementById("m1").innerHTML = res;
});
});
</script>
<style>
#finishedmeasurements {
font-family: Trebuchet MS;
line-height: 24px;
}
#inputmeasurements {
font-family: Trebuchet MS;
padding-right: 20px;
line-height: 23px;
}
input {
width: 30px !important;
margin-left: 5px;
}
</style>
Hope this will help you.
Please describe your problem.
Please tall me what type of output you need.
I give you modified html file
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td id="inputmeasurements">
<p align=right>
Bust:<input type="text" name="bust" id="bust"><br>
Waist:<input type="text" name="waist" id="waist"><br>
Hips:<input type="text" name="hips" id="hips"><br>
Lenght:<input type="text" name="lenght" id="lenght"><br>
Shoulders:<input type="text" name="shoulders" id="shoulders"><br>
Sleeves:<input type="text" name="sleeves" id="sleeves"><br>
Inseam:<input type="text" name="inseam" id="inseam"><br>
</p>
</td>
<td id="finishedmeasurements">
<p id="m1" align=left><FONT size=3 face=Trebuchet MS>
B1 Bust inches flat </br>
W1 Waist inches flat </br>
H1 Hips inches flat </br>
L1 Length </br>
S1 Shoulders </br>
S2 Sleeves </br>
I1 Inseam </br>
</FONT></p>
</td>
</tr>
</table>
<p>This is a test for measurements entering and copying to metadata</p>
<button onclick="myFunction2()">Enter</button>
<script>
function myFunction2() {
var str = document.getElementById("m1").innerHTML;
var res = str.replace(/B1/g, document.getElementById("bust").value).replace(/W1/g, document.getElementById("waist").value).replace(/H1/g, document.getElementById("hips").value).replace(/L1/g, document.getElementById("lenght").value).replace(/S1/g, document.getElementById("shoulders").value).replace(/S2/g, document.getElementById("sleeves").value).replace(/I1/g, document.getElementById("inseam").value);
document.getElementById("m1").innerHTML = res;
}
</script>
<button onclick="myFunction3()">New</button>
<script>
function myFunction3() {
window.location.reload();
}
</script>
</body>
<style>
#finishedmeasurements {
font-family: Trebuchet MS;
line-height: 24px;
}
#inputmeasurements {
font-family: Trebuchet MS;
padding-right: 20px;
line-height: 23px;
}
input {
width: 30px !important;
margin-left: 5px;
}
</style>
</html>

Javascript tabindex focus sets focus to next element

In the below sample, I am trying to have the navigation within the div. Used a JS function to get the current element and check and set the focus. But it sets the focus to next element always. Can somebody check?
function loadOverlay(event) {
var oly = document.getElementById('overlay');
oly.style.display = "block";
document.getElementById('userName').focus();
}
// restore page to normal
function restore() {
// document.body.removeChild(document.getElementById("overlay"));
//document.getElementById('overlay').focus();
}
// restore page to normal
function sayHi() {
alert("Hi");
}
function navigate(event, maxtab) {
//alert(event);
if (window.event) {
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
} else {
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
var currtab = document.activeElement.tabIndex;
// alert(key);
if (key == 9) {
if (currtab == 6) {
document.getElementById("userName").focus();
}
}
}
#outer {
width: 100%;
height: 100%;
}
.overlay {
background-color: grey;
opacity: .7;
filter: alpha(opacity=70);
position: fixed;
top: 100px;
left: 100px;
width: 500px;
height: 300px;
z-index: 10;
border: 1px solid black;
display: none;
}
<div id="outer">
<p>Check overlay</p>
<input type=button onclick="loadOverlay(event)" value="Open overlay">
</div>
<div id="overlay" class="overlay" onkeydown="navigate(event, 5)">
<h1>Enter your Name and Pasword </h1><br>
<table border=1>
<tr>
<td>Enter Your Name :</td>
<td>
<input tabindex="2" type="text" id="userName" value=""></td>
</tr>
<tr>
<td>Enter Your PassWord :</td>
<td><input tabindex="3" type="password" id="userPassWord" value=""></td>
</tr>
<tr>
<td>Confirm Your PassWord :</td>
<td><input tabindex="4" type="password" id="userRePassWord" value=""></td>
</tr>
<tr>
<td align=center><input tabindex="5" type="submit" id="formsub" name="Submit" value="Submit"></td>
<td align=center><input tabindex="6" type="reset" id="formref" name="reset" value="Refresh"></td>
</tr>
</table>
</div>

Categories

Resources