1

I want to call the ajax function once user clicks on the select control or the select control gets focus to itself from keyboard.

HTML code is as follows :

<select id="scanner" name="scanner" class="form-control"></select>

The jQuery-AJAX function I wrote is as follows but the aler("Hello") is not getting printed. why so?

 $("#scanner").bind("change",function() { alert("Hello");

    var mod_url = $('#mod_url').val(); 

    $.ajax({
      url : mod_url,
      cache: false,
      dataType: "json",
      type: "GET",
      async: false,
      data: {
        'request_type':'ajax', 
        'op':'get_all_stores'
      },
      success: function(result, success) { alert(result);
        $('#scanner').html(result);
      },
      error: function() {
        alert("Error is occured");
      }
    });
  });
PHPFan
  • 4,000
  • 11
  • 50
  • 104

3 Answers3

2

In your code i haven't seen any options for html select box

And, you have registered a change event on select box which will occur only on selecting the options in select box

Add few options in select box and try to select options which will fire the ajax call

See JS FIDDLE HERE

Murali Prasanth
  • 3,178
  • 2
  • 23
  • 36
1

I think you should do this instead:

 $("#scanner").bind("focus", function() { 
    alert("Hello");
    var mod_url = $('#mod_url').val(); 
    $.ajax({
      url : mod_url,
      cache: false,
      dataType: "html",
      type: "GET",
      data: {
        'request_type':'ajax', 
        'op':'get_all_stores'
      },
      success: function(result, success) { 
          alert(result);
          $('#scanner').html(result);
      },
      error: function() {
        alert("Error is occured");
      }
    });
  });

And one suggestion about bind is, you can use .on() method instead if you are using jQuery version 1.7+.


What seems to me you want to generate your #scanner elements options by your ajax call, so the changes are:

  1. remove the async:false because ajax has to be asynchronous.
  2. change the dataType to html because it seems that you are returning options from there as $('#scanner').html(result); suggests.
Jai
  • 71,335
  • 12
  • 70
  • 93
1

I Think This is what you want

  $("#scanner").bind('focus',function () {
            Myfunction(); // call what you want to call on focus 
        }).change(function() {
              Myfunction()      // call what you want to call on Change                    
      });



function Myfunction()
{
    var mod_url = "http://google.com"; 

    $.ajax({
      url : mod_url,
      cache: false,
      dataType: "json",
      type: "GET",
      async: false,
      data: {
        'request_type':'ajax', 
        'op':'get_all_stores'
      },
      success: function(result, success) { alert(result);
        $('#scanner').html(result);
      },
      error: function() {
        alert("Error is occured");
      }
    });
}

here js fiddle DEMO

Shailendra Sharma
  • 6,835
  • 2
  • 24
  • 42