javascript - 如何通过将值传递给输入类型来编辑 html 表值

标签 javascript jquery html css

我有一个,它有一些值,每当该行上的编辑按钮被点击时,该行上的所有值都会传递给相应的输入 标签,以便对其进行编辑。

这是我的代码:

$(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 '<a href="#' + value + '" class="btn btn-default btnEditar"><span class="glyphicon glyphicon-pencil"></span></a>';
}

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>

我怎样才能用 jquery 做到这一点,或者有更好的方法吗?以及每当我单击 btnGuardar 提交按钮 时,如何更新表格而无需刷新页面以查看新添加的值?

最佳答案

这是我对这个问题的第二个回答。它与前面的答案具有相同的结构,但是这个答案会同时拾取同一行(具有相同类)的所有字段。

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>

关于javascript - 如何通过将值传递给输入类型来编辑 html 表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386202/

相关文章:

javascript - 如何在不覆盖 javascript 中的所有其他内容的情况下动态地将段落添加到文档中?

javascript - 日期选择器的缩放显示

javascript - 将日期与 10 年前的今天日​​期进行比较

javascript - X-可编辑 AJAX 请求未发送

javascript - 来自 geojson 的传单格式值

html - 屏幕阅读器的局限性

javascript - 使用 Javascript 更改类的内容

javascript - 来自 javascript 的带有发布数据的新 Razor 页面

javascript - 替换 javascript 中的样式值

javascript - 关于在 jQuery 中工作的更改事件