Laravel: change text of a button depending on array selected

Viewed 234

I have a dropdown form that outputs an array taken from my controller

1

Blade:

<div class="form-group row">
  <label for="action" class="col-sm-2 col-form-label">Action: </label>
    <div class="col-sm-4">
      {!! Form::select('action',  $action, 'all', ['class' => 'form-control', 'id' => 'action']) !!}
    </div>
</div>

Controller:

    $action = ['exclusion' => 'CRR Exclusion', 'auto-closure' => 'CRR Auto Closure'];

my Form::select uses $action in my controller

I am trying to figure out how to change the text here in my button depending on which is clicked, either CRR Exclusion or CRR Auto Closure (array list)

<button id="add-new" type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#targetModal"><i class="fas fa-plus-square"></i> Add New CRR Exclusion</button><br><br>

Just for a reference, here is a separate code I did where the text changes depending on my selection option tag

      <select id="edit_bbrmode_view_type">
         <option value="P">Public</option>
         <option value="R">Restricted</option>
      </select>

    $("#config_view_type").on('change',function(){
   if($(this).find('option:selected').text()=="Public")
       $('#target-header').text('Add Public');
   else
       $('#target-header').text('Add Private');
    }).trigger("change");

I am trying to do something similar here but my problem is that the current code has Form::select instead of <option>

How do I do a similar if condition text change?

Pseudocode: (my intention need advice on code implementation)

    $("#action").on('change',function(){
   if(Form::select == 'CRR Exclusion')
       $('#add-new').text('Add New CRR Exclusion');
   else
       $('#add-new').text('Add New CRR Auto-Closure');
    }).trigger("change");

I hope I made it clear, thanks for any help

2 Answers

try this

$("#action").on('change',function(){
   var selected = $(this).find(':selected').val();
   if(selected == 'CRR Exclusion')
      $('#add-new').text('Add New CRR Exclusion');
   else
      $('#add-new').text('Add New CRR Auto-Closure');
});

Check this also

add this your controller after $action

$otherAttributes = [
                    'exclusion' => [
                        'data-buttontext' => 'Add New CRR Exclusion',
                    ],
                    'auto-closure' => [
                        'data-buttontext' => 'Add New CRR Auto-Closure',
                    ]
                ];

and send $otherAttributes with $action to blade file

then in your blade file

{!! Form::select('action',  $action, 'all', ['class' => 'form-control', 'id' => 'action'],$otherAttributes) !!}

now in js script

$('#action').on('change',function(){
   var buttonText = $(this).find(':selected').data('buttontext');
   $('#add-new').text(buttonText);
});
Related