user3733831
user3733831

Reputation: 2936

How I use this jquery function correctly?

I have a dropdown and its populating with dynamic data. Here I have used a function to call ajax and get the dynamic data.

This is how I create this function:

function Banks($selecter, selected) {

 // my stuff ----

}

I am using it like this when the document ready:

Banks($('#DropDownEdit'));

HTML look like this:

<select id="DropDownEdit" name="bank_one" data-id="4"></select>

Now I need to get data-id value to the function when document is ready.

I tried it something like this:

$(document).on('change', '#DropDownEdit', function(){
  var ID     = $(this).data('id');
  Banks($('#DropDownEdit'), ID);

}); 

But It doesn't work for me. Can anybody tell me how I do this rightly?

Upvotes: 0

Views: 64

Answers (4)

user5039044
user5039044

Reputation:

You need to get data-id value to the function when document is ready.

try to use $(document).ready();

$(document).**ready**(function(){ var ID = $('#DropDownEdit').data('id'); Banks($('#DropDownEdit'), ID); });

hope this help.

Upvotes: 0

2hamed
2hamed

Reputation: 9067

Your HTML markup seems to be all wrong. An empty select tag is not a valid markup and onchage never triggers for an empty select. The select tag must have at least one option inside.

<select id="DropDownEdit" name="bank_one" data-id="4">
    <option value="one">1</option>
    <option value="two">2</option>
    <option value="three">3</option>
</select>

Upvotes: 1

Mayank
Mayank

Reputation: 1392

Try the FIDDLE

I have updated the event delegation assignment as following and it works

function Banks($selecter, selected) {
  //alert(selected);
  $selecter.append('<option>1</option><option>2</option><option>3</option><option>4</option>')
    // my stuff ----

}

$(function () {
  Banks($('#DropDownEdit'), $('#DropDownEdit').data('id'));
  $('#DropDownEdit').on('change', function () {
    var ID = $(this).data('id');
    alert(ID);
    Banks($('#DropDownEdit'), ID);
  });
});

Hope it works for you

Upvotes: 0

Harry Bomrah
Harry Bomrah

Reputation: 1668

Try this.

$(document).ready(function(){
    var ID = $('#DropDownEdit').data('id');
})

Upvotes: 0

Related Questions