2016-09-30 179 views
0

我有一個複選框,需要保持檢查,一旦用戶點擊輸入框。Jquery複選框仍然檢查點擊

期:在第一次點擊複選框被選中,這工作正常。當再次點擊輸入時,複選框變爲未選中狀態。

輸出需要:

我想要的複選框保持選中狀態,因爲這會觸發change事件。

我搜索了很多例子來找到這個解決方案,但是找不到它。

任何幫助表示讚賞。

請參見小提琴:

http://jsfiddle.net/nrYec/194/

JS:

$('input').click(function() { 
    $('#x').text(this.checked ? "is checked" : "is not checked"); 
}); 
$('.b2').click(function() { 
     $('.trigger').click(); 
}); 
+0

你是說,點擊進入任何一個文本框中應該設置複選框,如果它檢查還沒有,但點擊複選框本身應該允許取消選中? – nnnnnn

+0

所以當你點擊文本框時,你爲什麼要切換複選框狀態?這裏應該發生什麼。 – epascarello

+0

@nnnnnn這是正確的單擊文本框應該只在一個方向工作,保持複選框選中。除非它被用戶手動取消選中。 – Seansa

回答

2

試試這個:

$('.b2').click(function() { 
 
    if (!$('.trigger').prop('checked')) { 
 
     $('.trigger').prop('checked', 'true'); 
 
    }; 
 
}); 
 

 
$('input').click(function() { 
 
    $('#x').text($('.trigger').prop('checked') ? "is checked" : "is not checked"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input class='trigger' type='checkbox'> 
 
<input class='b2' type='text' name='something'> 
 
<input class='b2' type='text' name='something'> 
 
<div id='x'></div>

+0

感謝這工作。 – Seansa

0
$('input').click(function() { 
    if ($(this).attr('type') !== "checkbox") 
    $('input[type="checkbox"]').prop('checked', true) 
}); 

這將迫使點擊任何其他輸入時,要檢查的複選框,但仍能正常運行時它被點擊。

+0

做到這一點,但是這會阻止你取消選中複選框。 – epascarello

1

一種選擇是將其包裝在if聲明:

JS Fiddle

$('.b2').click(function() { 
    var trigger = $('.trigger'); 
    if (!$('.trigger').is(':checked')) { 
    trigger.click(); 
    } 
}); 

$('input').click(function() { 
    // And need to check if the checkbox (not any input) is checked here 
    $('#x').text($('.trigger').is(':checked') ? "is checked" : "is not checked"); 
}); 
3

您在您要點擊到文本框中選中該複選框的意見明確,但點擊次數複選框本身正常工作。所以不會觸發點擊事件,只是直接設置複選框的checked屬性:

$('.b2').click(function() { 
 
    $('.trigger').prop("checked", true); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input class='trigger' type='checkbox'> 
 
<input class='b2' type='text' name='something'> 
 
<input class='b2' type='text' name='something'> 
 
<div id='x'></div>

0

以最好的方式保持你的複選框檢查是在你的ch上添加一個處理器onchange監聽器eckbox,只是設置javascript屬性檢查=真

$('.trigger').on('change', function() { 
$('.trigger')[0].checked = true; 
}) 
0

參考文獻:prop

$('.b2').on('click',function() { 
 
    $('.trigger').prop("checked", true); 
 
}).on('blur',function(){ 
 
    if($(this).val().trim().length === 0){ 
 
    $('.trigger').prop("checked", false); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class='trigger' type='checkbox'> 
 
<input class='b2' type='text' name='something'> 
 
<input class='b2' type='text' name='something'> 
 
<div id='x'></div>