简体   繁体   中英

Get selected value from a dropdown to use it in another dropdown Laravel

In my view, I have two dropdowns, the first dropdown have items and the second dropdown don't have item. It looks like this:

 <form action="http://localhost/AutoFill/public/handle-form" method="POST"> <div> City:<br> <select name="city"> <option value="">Choose Place</option> <option value="0">HCM</option> <option value="1">HN</option> </select> </div> <br> <div> Ward:<br> <select name="ward"> <option value="">---</option> </select> </div> <br> </form> 

Now I want to get the value of the first dropdown to fill data into the second dropdown. I create a function in my controller for returned second dropdown data:

public function getSecondEnumData(Request $request)
{
    $firstEnumSelected = $request->city;

    $client = new Client();
    if ($firstEnumSelected === 0) {
        $enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/zcyj2');
    } else {
        $enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/1bx7e6');
    }

    return json_decode($enumValueResponse->getBody(), true);
}

I searched some post in here, and I think I should write some JavaScript code in my view to do this but I'm not familiar with it so can you help me?

Route

Route::get('/', 'RestController@getFirstEnumData');

You can try like this, My Answer will not give you 100% soluton of your problem as I am little bit confused about your controller function. But I hope it will help you.

First of all your route need to be POST as you are taking Request data in the function.

Route::POST('getFirstEnumData', 'RestController@getSecondEnumData');

add csrf in the meta

<meta name="csrf-token" content="{{ csrf_token() }}" />

And then

<form action="http://localhost/AutoFill/public/handle-form" method="POST">
<div>
City:<br>

<select name="city" id="city">
<option value="">Choose Place</option>
<option value="0">HCM</option>
<option value="1">HN</option>       
</select>
</div>         
<br>

<div>
Ward:<br>

<select name="ward" id="ward">
  <option value="">---</option>
</select>
</div>    
<br>
</form>




$("#city").change(function() { 
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');               
var city = $( "#city" ).val();
$.ajax({    //create an ajax request to get tour list
type: "POST",
url: "/getFirstEnumData",
data : ({
  _token: CSRF_TOKEN, 
  city : city
}),                           
success: function(response){
  var responseData = JSON.parse(response);
  var dataLength = responseData.length;
  $("#ward").empty();

  $("#ward").append("<option value=''>Select</option>");
  for( var i = 0; i< dataLength; i++){
      var id = responseData[i].id;
      var name = responseData[i].name;
      $("#ward").append("<option value='"+id+"'>" + name + "(" + name+")"+" 
   </option>");
  }                 
  }
 });
});

Place the following code just above your </body> tag, change the success according to your reponse data, also url according to your url

  <script>
    let origin = document.querySelector(select[name='city'])
    let target = document.querySelector(select[name='ward'])
    origin.addEventListener('change', function(){
      $.ajax({
         url: '{{ url('/') }}',
         method: 'POST',
         data:{ city: origin.value, _token: '{{ csrf_token() }}' },
         success: function(response){
            response.forEach((opt) => {
             target.innerHTML += `<option value=${opt.id}>${opt.value}</option>` //this varies according to your response data
          })
         }

      })
    })
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM