Mark Selected in option that has the same id brought in array

Asked

Viewed 208 times

3

I have a select $(".methods option") that has 3 options with payment methods and each option has a value that has an ID (in case 1, 2 and 3 respectively). I need to mark as Selected the option that match with the Ids brought on data-payment-methods="{{ $timeline->paymentMethods }}" that in this example brings 2 objects with Ids 2 and 3. In if I did in javascript, is already checking and returning me that the options with Ids 2 and 3 coincided with the Ids returned in the array. I now need to place Selected in the options that have value 2 and 3.

Console with the variable payment javascript

inserir a descrição da imagem aqui

<div class="row">
<div class="col-sm-12">
    <div class="timeline">

        <article class="timeline-item alt">
            <div class="text-right">
                <div class="time-show">
                    <a href="#" class="btn btn-custom w-lg">Histórico</a>
                </div>
            </div>
        </article>

        @foreach($timelines as $timeline)
            <article class="timeline-item @if($timeline->user_id == Auth::user()->id) alt @else "" @endif">
                <div class="timeline-desk">
                    <div class="panel m-t-20 m-b-20">
                        <div class="panel-body">
                            <span class="arrow-alt"></span>
                            <span class="timeline-icon bg-info"><i class="zmdi zmdi-circle"></i></span>
                            <p class="timeline-date text-muted"><small>{{ date( 'd/m/Y H:i' , strtotime($timeline->created_at)) }}</small></p>
                            <p class="m-t-10">Serviço: {{ $order->category->name }}</p>
                            <p class="m-t-10">Status: {{ $timeline->status }}</p>
                            @isset($timeline->price_average)
                                <p class="m-t-10">Valor: R$ {{ number_format($timeline->price_average, 2, ',', '.') }}</p>
                            @endisset
                            @isset($timeline->price_average)
                                @foreach($timeline->paymentMethods as $paymentMethod)
                                    <p class="m-t-10">{{ $paymentMethod['name'] }}</p>
                                @endforeach
                            @endisset
                            <p class="m-t-10">{{ $timeline->description }}</p>
                            <div class="btn-group dropup @if($timeline->user_id == Auth::user()->id) pull-right @else pull-left @endif m-t-10">
                                <a type="button" class="btn btn-primary responder" 
                                    data-category="{{ $order->category->name }}" 
                                    data-price="{{ number_format($timeline->price_average, 2, ',', '.') }}"
                                    data-payment-methods="{{ $timeline->paymentMethods }}" 
                                href="#" data-toggle="modal" data-target="#con-close-modal">Responder</a>
                            </div>
                        </div>
                    </div>
                </div>
            </article>
        @endforeach
    </div>
</div>
</div>

<!-- Modal -->
<div id="con-close-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
    <div class="modal-content">
        <form method="POST" action="{{ route('customer.timelines.store', ['order' => $order, 'supplier' => $supplier]) }}">
        {{ csrf_field() }}
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title category" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="control-label m-b-10 price" style="text-align: left"></label>
                            <select class="form-control" id="status" name="status">
                                <option value="">Selecione</option>
                                <option value="Aprovado">Aprovado</option>
                                <option value="Contraproposta">Contraproposta</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div id="price-average-div">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="control-label">Informe um valor em reais para contraproposta:</label>
                                <input type="text" class="form-control" id="price-average" name="price_average">
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('payment_methods') ? ' has-error' : '' }}">
                            <div class="col-md-9">
                                <label for="payment_methods">Formas de Pagamento<h6>Selecione as formas de pagamento oferecidas.</h6></label>
                                <select multiple class="form-control methods" name="payment_methods[]" required>
                                    @foreach($paymentMethods as $paymentMethod)
                                        <option value="{{ $paymentMethod->id }}">{{ $paymentMethod->name }}</option>
                                    @endforeach
                                </select>
                                @if ($errors->has('payment_methods'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('payment_methods') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group no-margin">
                            <label class="control-label m-t-15">Observações:</label>
                            <textarea name="description" class="form-control autogrow" style="overflow: hidden; word-wrap: break-word; resize: horizontal; height: 104px;"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Fechar</button>
                <button type="submit" class="btn btn-primary waves-effect waves-light warning-alert-interest">Enviar</button>
            </div>
        </form>
    </div>
</div>

$(".responder").click(function(){

    //Select
    var methods = $(".methods option"); //select com options: <option value="{{ $paymentMethod->id }}">{{ $paymentMethod->name }}</option>

    var payment = $(this).data("payment-methods"); //Retorna array de objetos com o value contendo o ID

    $.each(methods, function() {
        var methods = $(this).val();
        console.log(methods); // Retorna 1, 2 e 3
        $.each(payment, function(indexPayment, valuePayment) {
            if (valuePayment.id == methods) {
            console.log("OK: " + valuePayment.id); // Retorna OK: 2 e OK: 3
            //Preciso pegar o option que bateu e colocar selected nele
            }
        });
   });

});
  • Also put your HTML

  • Face your question is confused, in the title you want to compare id in the body of the question you do not specify what each select is comparing, try to edit question and specify your question.

  • Edit the question and present the rendered html, this will make it much easier to help solve the problem.

2 answers

1


Enter the code below to see if the value exists in select and marks the option:

//Preciso pegar o option que bateu e colocar selected nele
var val = $('.methods option[value="'+valuePayment.id+'"]');
val.prop('selected', val ? true : false );

The code would look like this:

$(".responder").click(function(){

    //Select
    var methods = $(".methods option"); //select com options: <option value="{{ $paymentMethod->id }}">{{ $paymentMethod->name }}</option>

    var payment = $(this).data("payment-methods"); //Retorna array de objetos com o value contendo o ID

    $.each(methods, function() {
        var methods = $(this).val();
        console.log(methods); // Retorna 1, 2 e 3
        $.each(payment, function(indexPayment, valuePayment) {
            if (valuePayment.id == methods) {
            console.log("OK: " + valuePayment.id); // Retorna OK: 2 e OK: 3
            //Preciso pegar o option que bateu e colocar selected nele
               var val = $('.methods option[value="'+valuePayment.id+'"]');
               val.prop('selected', val ? true : false );
            }
        });
   });

});
  • I edited the question because I was a little confused, because it’s actually just a select.

  • @Marcelo I updated the answer. See if this is it. You want to take the values of an array?

  • If (valuePayment.id == methods), the variable valuePayment.id already brings me the Ids of the array that in the case is 2 and 3. The methods brings me the values of the select that in the case is 1, 2 and 3. I now need to put Selected in the second and third options.

  • @Marcelo From what I understood, it was just change the value I put in my code. See in the updated answer now.

  • That’s exactly what it was. Thank you.

0

Well I consider a straightforward answer to the title of the question itself. Thus generating a more succinct code, if I meet the main objective, that would work this way below:

var sel = 'select.methods',
    ary = $(sel).attr('data-payment-methods').split(',');

ary.forEach(function(x){ $(sel+' option').eq(x-1).attr('selected', ''); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select data-payment-methods=1,2,3 multiple class="form-control methods" name="payment_methods[]" required>
<!-- alterar 1,2,3 para o valor que for retornar do php para testes -->
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

You can change the value of the attribute data-payment-methods which is in 1,2,3 for any you want for testing purposes, since the value of this, will be generated, in fact, by the .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.