简体   繁体   中英

change background-color of radio buttons if not checked

As soon as the user submits without having checked all radio buttons, the unanswered buttons should appear in a different background-color than the ones checked. The way I tried to implement this was:

  1. create an empty array - "store"
  2. loop over each radio button and push the number 1 (true) in the array "store" if the item has been checked and 0(false) otherwise.
  3. Then I wanna loop over this array and add a Class to those items which have the value zero in "store".

     $(document).ready(function(){ $('#form').submit(function(){ var isValid = true; var store = new Array(); $("input:radio").each(function() { if($(this).prop('checked',true)){ store.push(1);} else{ store.push(0); isValid = false;} }); //.each if(!isValid){ for(var i=0;i < store.length;i++){ if(store[i]===0){ $('input[name=item' + i +']').addClass("not_answered");} }//end of for-loop return false;} else{ return true;} }); //submit });//document ready 

What am I doing wrong?

My fiddle:

FIDDLE

I think you can simplify this a little DEMO :

$('form').on('submit', function(e){
   var radios = $(this).find('input:radio').removeClass('notChecked');
   radios.filter(':not(:checked)').addClass('notChecked');
   if(radios.hasClass('notChecked')) return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM