Jquery选择checkbix并构建要发送到数据库的URL

时间:2013-05-23 20:45:18

标签: jquery ajax

Jsfiddle:http://jsfiddle.net/Xytvg

每个复选框都有id和value,例如,如果我选中了限定复选框或不合格复选框。

我希望禁用该复选框取决于单击哪一个,我希望在成功回调函数上完成此操作。

以下是我的代码:

$( "input[type=checkbox]" ).on( "click",function( e ){

    var preview = $("#preview").html('');

    // ** just a loader a gif image
    preview .html('<img src="../images/loader.gif" alt="Uploading...."/>');

    // ** this is the value of the checkbox
    var input = $(this).val();

    // ** here i am pulling the id value
    var id    = $(this).attr('id'); 


   $.ajax({
       // here i am trying to build url to be send to the action.php
       // i will get the id and the value depends on which checkbox was clicked 
       // action.php?id=1&value=2

       url: 'action.php?id='+id+'&value='+input, 
       type: "POST",
       success: function( response )
      {
           // here i want to figure out which checkbox was clicked and disabled it
      }
  });

  e.preventDefault();

});



<div id="preview"></div><!--loader gif-->

<p>
   USA
   <input type="checkbox" id="1" value="2" />Qualified OR 
   <input type="checkbox" id="1" value="3" /> Unqualifed
</p>

<p>
   UK 
   <input type="checkbox" id="2" value="2" />Qualified OR 
   <input type="checkbox" id="2" value="3" /> Unqualifed
</p>

<p>
   EGY 
   <input type="checkbox" id="3" value="2" />Qualified OR 
   <input type="checkbox" id="3" value="3" /> Unqualifed
</p>

2 个答案:

答案 0 :(得分:0)

将复选框分配给点击处理程序中的变量,如下所示:

$( "input[type=checkbox]" ).on( "click",function( e ) {
    var $checkbox = $(this);
    // rest of click handler code

然后在成功回调中你可以像这样禁用它:

$.ajax({
   url: 'action.php?id='+id+'&value='+input, 
   type: "POST",
   success: function( response )
   {
       $checkbox.attr('disabled', true);
   }
});

答案 1 :(得分:0)

你走了:

$( "input[type=checkbox]" ).on( "click",function( e ){
  // You just need to localize the var here :)
  var $this = $(this);
  var preview = $("#preview").html('');

  preview.html('<img src="../images/loader.gif" alt="Uploading...."/>');

  var input = $(this).val();

  var id = $(this).attr('id'); 
  $.ajax({
    url: 'action.php?id='+id+'&value='+input, 
    type: "POST",
    success: function (response) {
      // We added the localized var up above so now it's accessible to this scope :)
      $this.attr("disabled", "disabled");
    }
  });

  e.preventDefault();
});