如何选择onclick?

时间:2013-06-20 11:53:59

标签: html jquery

我有一个选择框,当从另一个选择框中选择一个选项时,该框将被填充。现在我希望在单击选项时发送AJAX调用。当点击事件被绑定到选择框时,即使没有点击选项,它也会发送ajax,即使我检查了所有选项。

$('#supname').click(function() {
    $('#gsm,#width,#type,#weight').empty();
    if($('#supname option').is(':selected')) { 
        $.post('<?php echo base_url()."index.php/inventory/getreeldata4supplier"; ?>'
            ,{supcode:$('#supname :selected').val(),reelno:$('#reelno').val(),date:$('#gidate').val()}
            , function(data){   
                if(data[0].count==0) {
                    alert('No reel entered on or before issue date');
                }
                else {
                    $.each(data,function(k,v){ 
                        $('#gsm').val(v.gsm);
                        $('#width').val(v.width);
                        $('#type').val(v.type);
                        $('#weight').val(v.weight);
                    })
                }
        },'json'  );
    }
 });

supname是选择框的ID。如果没有明确点击选项,即如果我查看选项,我不希望发送AJAX。谢谢您的一切努力。

2 个答案:

答案 0 :(得分:1)

正如我评论的那样,我建议您尝试使用on("change"

您需要第一个选项:

<select id="supname">
  <option value="">Please select</option>
  <option value="xxxx">supcode 1</option>

您还可以缩短测试和访问值:

$('#supname').on("change",function() {
  $('#gsm,#width,#type,#weight').empty();
  var supcode = $(this).val();
  if (supcode) {
    $.post('<?php echo base_url()."index.php/inventory/getreeldata4supplier"; ?>'
      ,{"supcode":supcode,"reelno":$('#reelno').val(),"date":$('#gidate').val()}
      ,  function(data){   
           if(data[0].count==0) {
              alert('No reel entered on or before issue date');
           }
           else {
             $.each(data,function(k,v){ 
                 $('#gsm').val(v.gsm);
                 $('#width').val(v.width);
                 $('#type').val(v.type);
                 $('#weight').val(v.weight); })
          }
    },'json');
  }
 });

答案 1 :(得分:0)

请尝试change事件。选择其他选项时会触发Change事件。
它的语法类似于click:

$('#supname').change(function() {
    //functionality
}