1

I want to change the input value when the user select data on the input dropdown. The first thing to do after looping and setting data value in the html dropdown is to check whether the option is selected or not, but I am confused about how to check it, so I just checked by dropdown id but it didn't work, so how to check data input if selected?

this is my ajax code to return data dropdown for the first time:

$.ajax({
    url : "{{ url('web/city/getdatacity') }}",
    type : "POST",
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
    },
    data : {
        province_id:id
    },
    success : function(data){
        var html = '';
        var postcode = '';
        var i;

        if(data.length == 0) {
          html += '<option value = ""> City not found!</option>';
        } else {
            for(i=0; i<data.length; i++) {
                html += '<option value = "'+ data[i].city_id +'">' + data[i].city_name +'</option>';
                
                if($('#city_id').is(':selected')) { //here the problem when check if option above selected or not
                    postcode = data[i].postal_code;  //input postal code in var postcode if true
                }
            }
        }
        $('.city').html(html);
        $('#postalcode').val(postcode);   //auto fill postal code value from postcode
    })
});
chiper4
  • 303
  • 5
  • 18
  • This sounds like mostly a client side problem, can you make a dummy ajax call and create a fiddle like this? https://jsfiddle.net/GRMule/WQXXT/ – react_or_angluar Dec 06 '20 at 08:17
  • Some of the code here should help https://stackoverflow.com/questions/11179406/jquery-get-value-of-select-onchange – react_or_angluar Dec 06 '20 at 08:20
  • Hi , `$('#city_id')` is dropdown where you adding options from ajax ? If dropdown is just loaded then only first value will be set as selected by default . I am not sure which dropdown you are taking about .Please elaborate – Swati Dec 06 '20 at 14:37

1 Answers1

0

Instead of using selected or onchange try something like this with your options attribute.

Look at the oninput

<label for="cars">Choose a car:</label>

<select id="cars" name="cars" oninput="console.log(this.value)">
  <option value="volvo">Volvo XC90</option>
  <option value="saab">Saab 95</option>
  <option value="mercedes">Mercedes SLK</option>
  <option value="audi">Audi TT</option>
</select>
norcal johnny
  • 2,050
  • 2
  • 13
  • 17