3

I have the next code to load all countries in my website:

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: '/comunidades',

    success: function(response) {
      $("#cbx_comunidad").empty();
      // console.log(response);
      $("#cbx_comunidad").prepend("<option value='' selected='selected'>Seleccione Comunidad</option>");
      for (i = 0; i < response.length; i++) {
        $("#cbx_comunidad").append("<option value='" + "rellena una opcion" + "</option>");
        //console.log('response' + response[i].id);
        $("#cbx_comunidad").append("<option value='" + response[i].id + "'>" + response[i].comunidad + "</option>");
      }
    }
  });
});

And with this load all my provinces on my website:

$('#cbx_comunidad').on('change', function(event) {
  $.ajax({
    type: 'GET',
    url: '/provincias/' + event.target.value,

    success: function(response) {
      $("#cbx_provincia").empty();
      // console.log(response);
      $("#cbx_provincia").prepend("<option value='' selected='selected'>Seleccione Provincia</option>");
      for (i = 0; i < response.length; i++) {
        $("#cbx_provincia").append("<option value='" + "rellena una opcion" + "</option>");
        $("#cbx_provincia").append("<option value='" + response[i].id + "'>" + response[i].provincia + "</option>");
      }
    }   
  });
});

I want set default value from select like this:

function setDefault(defValue) {
  alert(defValue);
  $('#cbx_comunidad option').each(function () {
    if (($(this).attr('value')) === defValue) {
      $(this).attr('selected', 'selected');
    }    
  });
}

and in my php code I need something similar as next:

<label for="cbx_comunidad">Seleccione Comunidad:</label>
$usercomunidad = $user->comunidad_id
<select onload="setDefault($user->comunidad_id)"
        class="form-control @error('cbx_comunidad') is-invalid @enderror"
        name="cbx_comunidad"
        id="cbx_comunidad"
        required></select>

This is possible have a trigger to pass my php variable to my jquery code? How can select my default value to update view?

3 Answers 3

1

You need to echo the php variables if you plan on passing them as JS params. (onload="setDefault({{ $user->comunidad_id }})")

You could also use a data-* attribute on your select instead.

<label for="cbx_comunidad">Seleccione Comunidad:</label>
<select class="form-control @error('cbx_comunidad') is-invalid @enderror"
        name="cbx_comunidad"
        id="cbx_comunidad"
        data-id="{{ $user->comunidad_id ?: '' }}"
        required></select>
$('#cbx_comunidad').on('change', function(event) {
  $.ajax({
    type: 'GET',
    url: '/provincias/' + event.target.value,

    success: function(response) {
      let value = $("#cbx_provincia").attr('data-id');
      $("#cbx_provincia").empty();
      $("#cbx_provincia").prepend("<option disabled "+(value ? '' : 'selected')+">Seleccione Provincia</option>");
      for (i = 0; i < response.length; i++) {
        $("#cbx_provincia").append("<option value='" + response[i].id + "'" + (value == response[i].id ? 'selected' : '') + ">" + response[i].provincia + "</option>");
      }
    }   
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

I should be able to just print your sanitized PHP data in your markup as follows.

<label for="cbx_comunidad">Seleccione Comunidad:</label>
<select onload="setDefault('<?php echo htmlentities($user->comunidad_id, ENT_QUOTES, 'UTF-8'); ?>')" class="form-control @error('cbx_comunidad') is-invalid @enderror" name="cbx_comunidad" id="cbx_comunidad" required>
</select>

Comments

0

You are populating the select from ajax on document load, but trying to set the selected value as soon as the select element is loaded. Which means the select is empty and has no options to match at that time. You should try to do the select AFTER adding/appending all the options. So in the select use data-id to store the selected value and read this value to pre-select the option AFTER all options are appended.

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: '/comunidades',

    success: function(response) {
      $("#cbx_comunidad").empty();
      // console.log(response);
      $("#cbx_comunidad").prepend("<option value='' selected='selected'>Seleccione Comunidad</option>");
      for (i = 0; i < response.length; i++) {
        $("#cbx_comunidad").append("<option value='" + "rellena una opcion" + "</option>");
        //console.log('response' + response[i].id);
        $("#cbx_comunidad").append("<option value='" + response[i].id + "'>" + response[i].comunidad + "</option>");
      }

      $("#cbx_comunidad").val($("#cbx_comunidad").data('id'));
    }
  });
});

And in your html:

<select data-id="$user->comunidad_id"
        class="form-control @error('cbx_comunidad') is-invalid @enderror"
        name="cbx_comunidad"
        id="cbx_comunidad"
        required>
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.