Take attribute value when page is loaded and select or modified

Asked

Viewed 35 times

2

I have a select. I need to get the value of the attribute data-idconta when the page is loaded and also when the select is changed.

I’m trying to:

$(document).ready(function() {

  $('#formaEntrada').on('ready change', function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta)
  });

});

I’ve tried: ready, load, onload, live...

But to no avail.

3 answers

2


You need to view the idconta as soon as the page is ready. You are only configured the event, but #formantry is never initialized. See an example of how to proceed:

function getIDConta(){
	return $("#formaEntrada option:selected").attr('data-idconta');
}


$(document).ready(function() {

  $('#formaEntrada').on('change', function() {
    $("#contaBancaria").val(getIDConta())
  });

  $("#contaBancaria").val(getIDConta())

});
label {
  display: inline-block;
  width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="formaEntrada">Tipo de Entrada</label>
<select id="formaEntrada">
  <option data-idconta= "10000-0">Tipo de Entrada 1</option>
  <option data-idconta= "20000-0">Tipo de Entrada 2</option>
</select>

<br>
<br>

<label for='contaBancaria'>Conta Bancária</label>
<input type='text' id='contaBancaria' readonly />

The field is initialized after you set up the event and not inside it.

0

Instead of:

$('#formaEntrada').on('ready change', function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta);
})

Utilize:

$('#formaEntrada').change(function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta)
})
  • 1

    The event change execute when the page is loaded?

0

Hitching a ride in the answer of Fabiano Salles, with Jquery you can evoke an event with the method .trigger().

$(document).ready(function() {
    
      //Configura o evento change
      $('#formaEntrada').on('change', function() {
        var IDConta = $("#formaEntrada option:selected").data('idconta');
        $("#contaBancaria").val(IDConta)
      });
      
      //evoca o evento configurado
      $('#formaEntrada').trigger('change');
    
});
label {
  display: inline-block;
  width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="formaEntrada">Tipo de Entrada</label>
<select id="formaEntrada">
  <option data-idconta= "10000-0">Bradesco</option>
  <option data-idconta= "20000-0">Santander</option>
</select>

<br>
<br>

<label for='contaBancaria'>Conta Bancária</label>
<input type='text' id='contaBancaria' readonly />

Browser other questions tagged

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