How to change value of an input with buttons - javascript

I have a form in which I want the user to be able to set the value in 15 minute increments with the use of two buttons.
Here is what I have so far:
<div class="form-group">
<label class="control-label " for="time">Authorisation Duration</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
<input type="text" class="form-control" id="time" name="time" value="00:00">
<span class="input-group-btn">
<button class="btn btn-info" type="button">+ 15 Minutes</button>
<button class="btn btn-danger" type="button">- 15 Minutes</button>
</span>
</div>
</div>
I am wondering how to go about making it change the value according to which button is pressed. Also, how to I make sure it does not go into the negative.
Thank you in advance.

An example with native functions ( stepUp() & stepDown() ):
function incr() {
document.getElementById("myTime").stepUp(15);
}
function decr() {
document.getElementById("myTime").stepDown(15);
}
Time: <input type="time" id="myTime" value="16:32:55">
<p>Click the button to increment the value of the time field by 10 minutes (each time you click).</p>
<button onclick="incr()">+ 15</button>
<button onclick="decr()">- 15</button>
An example ( with jQuery ) - integers:
// Set counter default to zero
var counter = 0
// Display total
$("#counter").text(counter);
// When button is clicked
$("#add").click(function(){
//Add 10 to counter
counter = counter + 15;
// Display total
$("#counter").text(counter);
});
//Subtract
$("#subtract").click(function(){
counter = counter - 15;
$("#counter").text(counter);
});
// Reset
$("#reset").click(function(){
counter = 0;
$("#counter").text(counter);
});
body{
font-size: 1.5em;
font-family: 'Oswald', sans-serif;
font-weight: 700;
}
.button_group{
width: 100%;
display: flex;
}
button {
font-family: 'Oswald', sans-serif;
font-size: 1em;
font-weight: 300;
border: 0;
padding: 1em 2em;
margin: 0.5em 0;
width: 100%;
background: rgba(0,0,0,0.1);
-webkit-transition:.2s;
}
button:nth-child(2){
margin: 0.5em;
}
button:hover{
background: rgba(0,0,0,0.3);
}
button:active{
background: rgba(0,0,0,0.5);
}
#add:active{
-webkit-transform:translateY(-1em);
}
#subtract:active{
-webkit-transform:translateY(1em);
}
#counter{
font-size: 3em;
text-align: center;
width: 100%;
display block;
background: rgba(0,0,0,0.1);
padding: 2em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter"></div>
<div class="button_group">
<button id="subtract">- 15</button>
<button id="reset">Reset</button>
<button id="add">+ 15</button>
</div>
Sources:
CSS tricks
Good example ( with Bootstrap & jQuery )
Example

This should help
$(function()
{
$(".btn-inc").click(function(){
var v = $(this).data("val");
$("#time").val(addMinutes($("#time").val(), v));
});
/*http://stackoverflow.com/questions/13338960/add-20-minutes-in-string-time-and-populate-it-in-the-textbox-or-alert-it*/
function addMinutes(time/*"hh:mm"*/, minsToAdd/*"N"*/) {
function z(n){
return (n<10? '0':'') + n;
}
var bits = time.split(':');
var mins = bits[0]*60 + (+bits[1]) + parseInt(minsToAdd);
if(mins < 0) return time;
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label " for="time">Authorisation Duration</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
<input type="text" class="form-control" id="time" name="time" value="00:00">
<span class="input-group-btn">
<button class="btn-inc btn btn-info" data-val="15" type="button">+ 15 Minutes</button>
<button class="btn-inc btn btn-danger" data-val="-15" type="button">- 15 Minutes</button>
</span>
</div>
</div>

You can use native html5 time input:
<input type="time" step="900">
Try it:
<input type="time" step="900">
The disadvantage is that is bad supported on Firefox and Safari so you can use this as alternative:
<input type="number" min="0" max="100" step="5">
<input type="range" min="0" max="15" step="5">

Related

Display results of onkeyup event on multiple id

I am trying to get the text in a multiple text box as the user types in it (jsfiddle playground):
function Input1(a) {
document.getElementById("Input11").innerHTML = a.value;
document.getElementById("Input12").innerHTML = a.value;
document.getElementById("Input13").innerHTML = a.value;
}
function Input2(b) {
document.getElementById("Input21").innerHTML = b.value;
document.getElementById("Input22").innerHTML = b.value;
document.getElementById("Input23").innerHTML = b.value;
}
And Result as
<span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span id="Input11">Input11</span><br>
<span id="Input12">Input12</span><br>
<span id="Input13">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span id="Input21">Input21</span><br>
<span id="Input22">Input22</span><br>
<span id="Input23">Input23</span><br><br>
The above code is working fine.
But I want to Display each "onkeyup" input multiple times on-page. So here I need to update the function and span id (As if I use the same id then it will not display anything after 2nd call)
Please help me to reformat the above JavaScript and HTML so Just Define function for input and display it on all HTML span id without changing span id each time...
you can use class instead of id and use querySelectorAll to select all elements here is sample code
function Input1(a) {
const elements = document.querySelectorAll(".Input1");
elements.forEach((e)=>{
e.innerHTML = a.value;
})
}
function Input2(b) {
const elements = document.querySelectorAll(".Input2");
elements.forEach((e)=>{
e.innerHTML = b.value;
})
}
<html>
<body><span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span class="Input1">Input11</span><br>
<span class="Input1">Input12</span><br>
<span class="Input1">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span class="Input2">Input21</span><br>
<span class="Input2">Input22</span><br>
<span class="Input2">Input23</span><br><br>
</body>
</html>
you can do somthing like that:
document.querySelectorAll('div.text-box').forEach( (box,i) =>
{
let
intxt = box.querySelector('input')
, spTxts = box.querySelectorAll('span')
;
intxt.mane = `Jname${++i}`
intxt.placeholder = `Input${i}`
intxt.onkeyup = () => spTxts.forEach(sp=>sp.textContent = intxt.value)
})
.text-box {
margin : 20px 0 15px 0;
}
.text-box input {
width : 100%;
font-size : 13px;
padding : 5px;
margin-top : -5px;
margin-bottom : 1em;
box-shadow : 1px 5px 7px #75757578;
}
.text-box span {
display : block;
}
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
this is the best for you!
function Input(a, n) {
var spans = document.querySelectorAll('#tb' + n + ' span')
spans.forEach(function(span){
span.innerHTML = a.value;
})
}
.textbox-value {
width: 100%;
font-size: 13px;
padding: 5px;
margin-top: -5px;
box-shadow: 1px 5px 7px #75757578;
}
<html>
<body>
<div id="tb1" class="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input(this, '1');" />
<br><br>
<span>Input11</span><br>
<span>Input12</span><br>
<span>Input13</span><br>
</div>
<br>
<div id="tb2" class="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input(this, '2');">
<br><br>
<span>Input21</span><br>
<span>Input22</span><br>
<span>Input23</span><br>
</div>
<br>
</body>
</html>

Why I can't add another class inside my element with bootstrap class form-control? if I add but it does not work

When I try to insert class using element.classList.add("anyClass"); it does not work, if it had form-control bootstrap class as I have given inside code, if I use remove instead of add and type element.classList.remove("form-control"); it works fine
function validation() {
var first_name = document.getElementById("first_name");
// var last_name=document.getElementById("last_name");
// var address=document.getElementById("address");
// var phone_no=document.getElementById("phone_no");
// var email=document.getElementById("email");
if (first_name.value === "") {
first_name.classList.add("add_border_left");
first_name.focus();
return false;
}
return true;
}
.add_border_left {
border-left: #d9534f 4px solid;
}
<div class="row">
<label for="">First Name</label>
<input class="form-control" onkeydown="clear_first_name();" autocomplete="off" type="text" id="first_name" autofocus>
<!-- <label id="valid_first_name" for="">Please Enter Valid First Name</label> -->
</div>
<div class="row">
<button type="submit" style=" margin-top: 30px; letter-spacing: 2px;" class="btn btn-outline-info btn-block">Submit</button>
</div>
Would you please also mention clear_first_name() method.
For now, I just place validation() method on replacing of that and class is added.
function validation()
{
var first_name=document.getElementById("first_name");
// var last_name=document.getElementById("last_name");
// var address=document.getElementById("address");
// var phone_no=document.getElementById("phone_no");
// var email=document.getElementById("email");
console.log(first_name.value)
if(first_name.value === "")
{
first_name.classList.add("add_border_left");
first_name.focus();
return false;
}
return true;
}
.add_border_left
{
border-left: #d9534f 4px solid;
}
<div class="row">
<label for="">First Name</label>
<input class="form-control" onkeydown="validation();" autocomplete="off" type="text"
id="first_name" autofocus>
<!-- <label id="valid_first_name" for="">Please Enter Valid First Name</label> -->
</div>
<div class="row">
<button type="submit" style=" margin-top: 30px; letter-spacing: 2px;"
class="btn btn-outline-info btn-block">Submit</button>
</div>

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 disable a key on key press on javascript?

This how the code works, when i press left key button (e.keyCode =39) it jumps up to the next page. All in all there are 7 ($('#btn-group input').length) pages in my program. I tried using preventDefault(); command inside the condition where the comment i dont know hat will put here but i wont work on my program( it jumps to page 8 and returns to page 7). Thank you
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
if (new_num == $('#btn-group input').length) {
// i dont know what will put here
}
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" style ="background-color:#66cdaa" value="1">
<input class="btn butt" type="button" id="btn_page2" style ="background-color:#66cdaa" value="2">
<input class="btn butt" type="button" id="btn_page3" style ="background-color:#66cdaa" value="3">
<input class="btn butt" type="button" id="btn_page4" style ="background-color:#66cdaa" value="4">
<input class="btn butt" type="button" id="btn_page5" style ="background-color:#66cdaa" value="5">
<input class="btn butt" type="button" id="btn_page6" style ="background-color:#66cdaa" value="6">
<input class="btn butt" type="button" id="btn_page7" style ="background-color:#66cdaa" value="7">
<input class="btn butt active-btn" type="button" style ="background-color:#66cdaa" id="next_btn" value="Next">
</div>
You can call this function on keypress of an element.
function ValidateClientname(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
} else if (e) {
var charCode = e.which;
} else {
return true;
}
alert (charCode); // this will give you key value and you can pass it in if statement like if ((charCode > 47 && charCode < 58) || (charCode ==8))
if ((charCode > 47 && charCode < 58) )
return true;
else
return false;
} catch (err) {
alert(err.Description);
}
}
You need to "short circuit" your function before it reaches the .toggle function. This will prevent all further execution of the function.
$(function() {
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
// if new number is for a page that doesnt exist
// short circuit
if (new_num == $('#btn-group input').length) {
return false;
}
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
});
.active-btn {
background-color: red !important;
}
.page {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<input class="btn butt active-btn" type="button" id="btn_page1" style="background-color:#66cdaa" value="1" />
<input class="btn butt" type="button" id="btn_page2" style="background-color:#66cdaa" value="2" />
<input class="btn butt" type="button" id="btn_page3" style="background-color:#66cdaa" value="3" />
<input class="btn butt" type="button" id="btn_page4" style="background-color:#66cdaa" value="4" />
<input class="btn butt" type="button" id="btn_page5" style="background-color:#66cdaa" value="5" />
<input class="btn butt" type="button" id="btn_page6" style="background-color:#66cdaa" value="6" />
<input class="btn butt" type="button" id="btn_page7" style="background-color:#66cdaa" value="7" />
<input class="btn butt active-btn" type="button" style="background-color:#66cdaa" id="next_btn" value="Next" />
</div>
</div>
<div id="pages_all">
<div id="page1" class="page active-page" style="display:block">Page 1</div>
<div id="page2" class="page">Page 2</div>
<div id="page3" class="page">Page 3</div>
<div id="page4" class="page">Page 4</div>
<div id="page5" class="page">Page 5</div>
<div id="page6" class="page">Page 6</div>
<div id="page7" class="page">Page 7</div>
</div>
you can try this:
$('.btn').click(function(){
$(this).addClass('active-btn').siblings().removeClass('active-btn');
});
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
var old_num = parseInt($('#btn-group').find('.active-btn').val());
var new_num = old_num+1;
if (new_num == $('#btn-group input').length) {
new_num=1;
}
if (e.keyCode == '39') {
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
.pager:not(:first-child) { display:none;}
.butt{background-color:#66cdaa}
.active-btn {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p id="page1" class="pager" style="display:inline-block">1</p>
<p id="page2" class="pager">2</p>
<p id="page3" class="pager">3</p>
<p id="page4" class="pager">4</p>
<p id="page5" class="pager">5</p>
<p id="page6" class="pager">6</p>
<p id="page7" class="pager">7</p>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" value="1">
<input class="btn butt" type="button" id="btn_page2" value="2">
<input class="btn butt" type="button" id="btn_page3" value="3">
<input class="btn butt" type="button" id="btn_page4" value="4">
<input class="btn butt" type="button" id="btn_page5" value="5">
<input class="btn butt" type="button" id="btn_page6" value="6">
<input class="btn butt" type="button" id="btn_page7" value="7">
<input class="btn butt" type="button" id="next_btn" value="Next">
</div>
I think you can just use a switch statement to test for the key :
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
I have written my own version of what you're trying to do (at least what I think you're trying to do), feel free to use that as an inspiration.
I use CSS3 transitions instead of jQuery's toggle.
const pagesCount = 7;
let currentPage = 1;
// ---- Generating buttons and pages
const $btnGroup = $("#btn-group");
const $pagesContainer = $("#pages");
for(let i=1; i<=pagesCount; i++){
$pagesContainer.append(`<div class='page'><h2>PAGE ${i}</h2></div>`);
$btnGroup.append(`<input type='button' value='${i}'/>`);
}
const $btns = $btnGroup.find("input")
$btns.first().addClass("active");
const $pages = $(".page");
$pages.not(":eq(0)").addClass("toRight");
// ---- End generating buttons
$btns.click( function() {
currentPage = +$(this).val();
changePage(currentPage);
});
changePage = (pageNum) => {
$pages.removeClass("toLeft toRight");
$pages.slice(0, pageNum-1).addClass("toLeft");
$pages.slice(pageNum, pagesCount).addClass("toRight");
updateButtons();
}
updateButtons = () => {
$btns.removeClass("active");
$btns.eq(currentPage-1).addClass("active");
}
nextPage = () => {
return currentPage===pagesCount ? null : changePage(++currentPage);
}
prevPage = () => {
return currentPage===1 ? null : changePage(--currentPage);
}
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
$("#prev_btn").click(prevPage);
$("#next_btn").click(nextPage);
#pages {
position: relative;
width: 400px;
height: 200px;
overflow: hidden;
}
#pages .page {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #000;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
#pages .page:nth-child(even) {
background: #008000;
}
#pages .page:nth-child(odd) {
background: #00f;
}
#pages .page.toLeft {
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
#pages .page.toRight {
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
#pages .page h2 {
color: #fff;
}
nav {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
width: 400px;
}
nav input {
background-color: #66cdaa;
}
nav #btn-group input {
margin: 0 5px;
}
nav #btn-group input.active {
background: #00f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pages"></div>
<nav>
<input class="btn active-btn" type="button" id="prev_btn" value="Prev.">
<div id="btn-group"></div>
<input class="btn butt active-btn" type="button" id="next_btn" value="Next">
</nav>
One could also imagine a solution where all the pages would be in a line, forming a ribbon, and the pagination buttons would just translate the whole ribbon to the right place, to show the correct page transform : translateX(n%)
I hope it helps.

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>

Categories

Resources