2012-04-16 49 views
2

我想做一個複選框的形式,有鼠標懸停在圖像和檢查圖像功能與jQuery。圖像複選框與jQuery的形式

我成功地做了這個功能,但是工作不夠好。

這裏是我的html表單。

<label for="w_interest"> 
    <img src="/images/account/w_select.png_img"/ style='cursor:pointer;'> 
    <input name="w_interest" type="checkbox" id="w_interest" style="display:none"> 
</label> 

這裏是jQuery的

$(document).ready(function() { 
    $('#img').hover(
    function() { 
     $(this).attr('src', '/images/account/ws_145_hover.png'); 
     }, 
    function() { 
     $(this).attr('src', '/images/account/ws_145.png'); 
     } 
); 

    $("#img").click(function() { 
    if(1) { 
     $(this).attr("src", "/images/account/ws_145_checked.png"); 
     $("#w_interest").val("0"); 
    } else { 
     $(this).attr("src", "/images/account/ws_145.png"); 
     $("#w_interest").val("1"); 
    } 
    }); 
}); 
  1. 當我點擊圖像,它將改爲檢查到的圖像。但是,當我將鼠標移出時,它會更改爲原始圖像。我想確保它保持在檢查圖像。

  2. 我想確保它檢查複選框的輸入。

  3. 如果用戶再次單擊選中的圖像,它將取消選擇複選框輸入。

你能幫我解決jquery問題嗎?

回答

2

進行比較見下面的例子:http://jsfiddle.net/tErvQ/

代碼:

$('.imag_box img').hover(
    function() { 
     if($(this).next().val() !== "1") { 
      $(this).attr('src', 'http://placehold.it/150/000000/fbaf5d'); 
     } 
     }, 
    function() { 
     if($(this).next().val() !== "1") { 
      $(this).attr('src', 'http://placehold.it/150/000000/ffffff'); 
     } 
    } 
); 


$(".imag_box img").click(function() { 
    if($(this).next().val() !== "1") { 
     $(this).attr("src", "http://placehold.it/150/000000/00ff18"); 
     $(this).next().val("1"); 
    } else { 
     $(this).attr("src", "http://placehold.it/150/000000/ffffff"); 
     $(this).next().val("0"); 
    } 
}); 

希望這就是你需要:)

使用被檢查的屬性可能是一個更好的主意,因爲如果您提交表單,可能會在後處理中處理得更好。

+0

真棒!謝謝!! – james 2012-04-16 08:22:01

0

是錯字,如果(1){

我想你應該與

if($("#w_interest").val() == 1) 
0

試試這個:

$(document).ready(function() { 
    var images = [ 
     '/images/account/ws_145.png', 
     '/images/account/ws_145_hover.png' 
    ]; 
    var $w_interest = $("#w_interest"); 
    var $img = $('#img'); 
    $img.hover(function() { 
     $img.attr('src', images[1]); 
    }, function() { 
     if($w_interest.val() == "0") { 
      $img.attr("src", images[0]); 
     } 
    }); 

    $img.click(function() { 
     if($w_interest.val() == "1") { 
      $img.attr("src", images[0]); 
      $w_interest.val("0"); 
     } else { 
      $img.attr("src", images[1]); 
      $w_interest.val("1"); 
     } 
    }); 
});