Select Items of a Select Multiple in laravel JS

4

View

<div class="form-group">
    <label class="col-sm-3 control-label" for="exampleInputEmail1">productos para la orden:*</label>
    <div class="col-sm-5">
       {{ Form::select('products[]', $products, null, ['id' => 'products', 'multiple' => 'multiple', "class"=>"form-control multi-select"]) }}
       <span class="errors">{{ $errors->first('shipping_method_id') }}</span>
    </div>
</div>

That is my SELECT multiple where I call from my controller all my products whose stock is greater than 0

Controller

$products = Product::where('stock','>','0')->lists('name', 'id');

return View::make("backend.orders.create")
       ->with("action","create")
       ->with('products',$products);

How do I select those items so that I can print them below and then be able to select the amount of this item? Suppose you have a coffee item, select it and down load this item and put an accountant to tell you the number of coffees you want and then in the controller are out of stock.

    
asked by user6581 12.05.2016 в 21:26
source

1 answer

1

to select the elements in a select multiple you can use the click function of jquery, when you make some selection in the select, the function .click returns an array with the previously selected options, what I did was assign an identifier value in the value to be able to make the changes that are desired, I leave the code to give you an idea.

$('#products').click(function (e) {
  //se consigue todos los valores seleccionados en el select multiple
  //en este caso el valor que se consigue en el atributo value
  //es un identificador del producto
  this.seleccion  = $(this).val();

  //se limpia el div para imprimir
  $('#imprimir').html('');

  //se valida que this.seleccion sea mayor a 0
  if ( this.seleccion.length > 0 ) {
    //se recorren todos los valores seleccionados en el select products
    for (var i = this.seleccion.length - 1; i >= 0; i--) {
      this.cantidad = $("#products [value='" + this.seleccion[i] + "']").attr('data-cantidad');
      this.texto    = $("#products [value='" + this.seleccion[i] + "']").text();
      this.cambio   = $("#products [value='" + this.seleccion[i] + "']").attr('data-cambio');

      //se crea el html con un input para poner la cantidad a descontar
      this.html = '<div>' + this.texto + '- Stock: <span id="cambio' + this.seleccion[i] + '">' + this.cantidad 
      + '</span> - <input type="text" id="cantidad' + this.seleccion[i] 
      + '" data-i="' + this.seleccion[i] 
      + '" class="accion" value="' + this.cambio + '" /> Quedarian <span id="nueva_cantidad' 
      + this.seleccion[i] + '">' + this.cantidad + '</span></div>';

      $('#imprimir').append( this.html );
    }
    //una vez creado los input con la clase .accion
    //se ejecuta un trigger para hacer las operaciones del stock
    $('.accion').trigger('keyup');
  };
});

$('#imprimir').on('keyup', '.accion', function(event) {
  event.preventDefault();
  //identificador del input
  this.i = $(this).attr('data-i');

  this.numero_uno = parseInt( $(this).val() );
  this.numero_dos = parseInt( $('#cambio' + this.i ).text() );

  //cada vez que hacemos un cambio a #products
  //el valor del input .accion se pierde ya que lo dibuja desde 0
  //para evitar esto, en esta linea se lo asigno a un atributo para guardarlo
  $("#products [value='" + this.i + "']").attr('data-cambio', $(this).val() );

  //resta del stock con la cantidad del input .accion
  this.nueva_cantidad = this.numero_dos - this.numero_uno;

  //cambiando la cantidad en stock
  $('#nueva_cantidad' + this.i ).text( this.nueva_cantidad );

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="form-group">
        <label class="col-sm-3 control-label" for="exampleInputEmail1">productos para la orden:*</label>
        <div class="col-sm-5">
          <select name="productos" multiple id="products" class="form-control multi-select">
            <option value="1" data-cantidad="8" data-cambio="0">cafe</option>
            <option value="2" data-cantidad="3" data-cambio="0">jugo</option>
            <option value="3" data-cantidad="4" data-cambio="0">dulce</option>
            <option value="4" data-cantidad="6" data-cambio="0">refresco</option>
          </select>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <p>Selecionaste:</p>
    </div>
    <div id="imprimir" class="col-md-12">

    </div>
    <div class="col-md-12">
      <button class="btn btn-info" >Guardar</button>
    </div>
  </div>
</div>

Each time you select an element of the select, you draw in the div #print the stock of the product, an input .accion to assign the value to subtract and finally the subtraction of the stock minus the value to subtract.

I hope it helps you.

    
answered by 23.07.2016 в 20:00