0

Estimados necesito su ayuda, como podría realizar operaciones con :

<span> y <select> <option> con javascript Mi código.

<table border="1">
  <thead>
    <tr>
      <th>Categoria</th>
      <th>Precio</th>
      <th>cantidad Habitacion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Matrimonial</td>
      <td><span id="precio_1">200.00</span></td>
      <td>
        <select id="reserva_1" name="reserva_1">
          <option id="matrimonial_0" value="0">0</option>
          <option id="matrimonial_1" value="1">1-habitacion</option>
          <option id="matrimonial_2" value="2">2-habitaciones</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>Simple</td>
      <td><span id="precio_2">120.00</span></td>
      <td>
        <select id="reserva_2" name="reserva_2">
          <option id="simple_0" value="0">0</option>
          <option id="simple_1" value="1">1-habitacion</option>
          <option id="simple_2" value="2">2-habitaciones</option>
          <option id="simple_3" value="3">3-habitaciones</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>Doble</td>
      <td><span id="precio_3">200.00</span></td>
      <td>
        <select id="reserva_3" name="reserva_3">
          <option id="doble_0" value="0">0</option>
          <option id="doble_1" value="1">1-habitacion</option>
          <option id="doble_2" value="2">2-habitaciones</option>
          <option id="doble_3" value="3">3-habitaciones</option>
          <option id="doble_4" value="4">4-habitaciones</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>
<button type="button" id="calcular" name="button">Calcular</button> Total de reservas : <input type="text" name="resultado" id="resultado" disabled="" value="">

Esta tabla es dinámica, el javascript tiene que poder realizar las operaciones,cuando haya solo un tipo de habitación o mas, las filas no son estáticas, (en mi bucle en php pongo un id diferente en las etiquetas span y select y sus option respectivos, con eso deseo trabajar las operaciones) Como debe de calcular

el option se multiplica con span (por fila) y al final realizaría la sumatoria.

mejor dicho precio * cantidad habitacion y su total. Poniendo el resultado en el input id='resultado'

1 respuesta 1

2

puedes hacerlo asi:

// seleccionamos todos los select cuyo id empieze con la palabra reserva
var sele = document.querySelectorAll('select[id^="reserva"]');
// seleccionamos el id resultado del input 
var res = document.querySelector("#resultado");
//creamos un arreglo vacio
var total = [];

//interamos por cada select que este en el documento
for(var i=0 ; i < sele.length; i++){
// rellenamos las posiciones de total con base a la cantidad de select
// y le asignamos 0 como valor inicial a todos
total[i]=0;
// agregamos un evento change por cada select del documento
sele[i].addEventListener("change", (e)=>{

// creamos un variable llamada el que guardara el select seleccionado xD
let el = e.target;
// creamos un variable ids que almacenara la numeracion del id con una 
// expresion regular solo nos extrae el numero 1 2 u 3 a eso 
// le restamos -1 porque las posiciones de un arreglo son desde 0
  	let ids= el.id.match(/\d+/)[0]-1;
// del select buscamos su padre que seria td
   // luego el padre de td que seria tr
   // de ahi buscamos el td que contega un span que contenga un id que empieze
   //  con la palabra precio y obtenemos el texto
  	let price = el.parentElement.parentElement.querySelector('td span[id^="precio"]').textContent;
// asignamos a total en la posicio ids el valor de options
// lo multiplicamos por el precio
total[ids] =  ( el.value*price );
// sumamos todos los valores del arreglo total
sum = total.reduce((a, b) => a + b, 0);
// cambiamos el attributo value por el valor de la suma
// le decimos que queremos 2 decimales con toFixed();
res.setAttribute("value",sum.toFixed(2));

  });
}
<table border="1">
  <thead>
    <tr>
      <th>Categoria</th>
      <th>Precio</th>
      <th>cantidad Habitacion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Matrimonial</td>
      <td><span id="precio_1">200.00</span></td>
      <td>
        <select id="reserva_1" name="reserva_1">
          <option id="matrimonial_0" value="0">0</option>
          <option id="matrimonial_1" value="1">1-habitacion</option>
          <option id="matrimonial_2" value="2">2-habitaciones</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>Simple</td>
      <td><span id="precio_2">120.00</span></td>
      <td>
        <select id="reserva_2" name="reserva_2">
          <option id="simple_0" value="0">0</option>
          <option id="simple_1" value="1">1-habitacion</option>
          <option id="simple_2" value="2">2-habitaciones</option>
          <option id="simple_3" value="3">3-habitaciones</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>Doble</td>
      <td><span id="precio_3">200.00</span></td>
      <td>
        <select id="reserva_3" name="reserva_3">
          <option id="doble_0" value="0">0</option>
          <option id="doble_1" value="1">1-habitacion</option>
          <option id="doble_2" value="2">2-habitaciones</option>
          <option id="doble_3" value="3">3-habitaciones</option>
          <option id="doble_4" value="4">4-habitaciones</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>
<button type="button" id="calcular" name="button">Calcular</button> Total de reservas : <input type="text" name="resultado" id="resultado" disabled="" value="0.00">

1
  • Tu código esta muy bien pero intenta desarrollarlo un poco. Explicar como funciona ese JS y que hace. Puede que la persona que pregunta o los próximos usuarios no entiendan como aplicarlo.
    – GDP
    el 8 ene. 2019 a las 9:12

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.