Pratik
Pratik

Reputation: 11745

How can I Write this in JQuery

if ( !document.getElementById('chkBoxView').checked
    &&!document.getElementById('chkBoxEdit').checked
    &&!document.getElementById('chkBoxAdd').checked
    &&!!document.getElementById('chkBoxDelete').checked )
{
    alert('Please select atleast one checkBox');
    return false;
}
else {
 // Atleast One Check Box Selected By User.
 return true
}

Above is JavaScript, What can be the Corresponding & Optimized code in JQuery ?

Upvotes: 1

Views: 149

Answers (4)

Guffa
Guffa

Reputation: 700422

You can use a multiple selector to get each of the checkboxes if it's checked, and then check that the length of the result is not zero:

if (!$('#chkBoxView:checked,#chkBoxEdit:checked,#chkBoxAdd:checked,#chkBoxDelete:checked').length) {
  alert('Please select at least one checkBox');
  return false;
} else {
  // At least One Check Box Selected By User.
  return true;
}

Upvotes: 1

XMen
XMen

Reputation: 30248

You can try this:

$("input:checked[id=yourid]").val()

This is good way

jQuery('#chkBoxView').is(':checked')

Upvotes: 1

karim79
karim79

Reputation: 342655

if (!$(":checkbox[id^=chkBox]:checked").length) {
    alert('Please select atleast one checkBox');
    return false;
}
alert('you filled at least one!');
return true;

Since all of your checkbox IDs start with 'chkBox' you can address them using the attribute Starts With selector. A truthy length of checked checkboxes means at least one has been checked.

Demo: http://jsfiddle.net/karim79/KSjSH/2/

Upvotes: 3

Kissaki
Kissaki

Reputation: 9227

if (
    !jQuery('#chkBoxView').is(':checked')
    &&!jQuery('#chkBoxEdit').is(':checked')
    &&!jQuery('#chkBoxAdd').is(':checked')
    &&!jQuery('#chkBoxDelete').is(':checked')
    ) {
    alert('Please select atleast one checkBox');
    return false;
}
else {
 // Atleast One Check Box Selected By User.
 return true
}

if you prefer $ over jQuery you can use that one as well ofc.

Upvotes: 2

Related Questions