简体   繁体   中英

jQuery: Make all fields required only if one input has a value

This is my code:

$('form').submit(function(){

            if ( $('#base_agrad').val() === '' && $('#req_agrad').val() === '' && $('#req_agrad1').val() === '' && $('#req_agrad2').val() === ''){
                return true;
            }else if ( $('#base_agrad').val() === '' || $('#req_agrad').val() === '' || $('#req_agrad1').val() === '' || $('#req_agrad2').val() === ''){
                $('#error_agrad').html('*Completa tu agradecimiento!');
                return false;
            }           

    });

What I want is, letting the user submit the form if all the inputs are empty, but if one of them has a value he needs to complete all the form. The inputs are select tags and the application is in RoR. jQuery is working but it doesn't allow me to submit the form if everything is empty. The default value of all the options is nul.

This is the html form:

            <%= f.select :base_agradecimiento, options_for_select(@paquete[:base][:tipo].each do |x| [x] end),{}, {:id => 'base'} %>            
            <p>Seleccione el color de la Base:</p>
            <%= f.select :base_agradecimiento_color, options_for_select(@paquete[:base][:color].each do |x| [x] end),{}, {:id => 'req_agrad'} %>
            <p>Seleccione el tamaño de la Base:</p>         
            <%= f.select :base_agradecimiento_tamaño, options_for_select(@paquete[:base][:tamaño].each do |x| [x] end),{}, {:id => 'req_agrad1'} %>
            <p>Seleccione el fondo de la Base:</p>
            <%= f.select :base_agradecimiento_fondo, options_for_select(@paquete[:base][:fondo].each do |x| [x] end),{}, {:id => 'req_agrad2'}%>

And the hash from where im getting the options is this:

@paquete = {
        base: {
            color: [nil,'blue', 'black', 'perl'],
            fondo: [nil,'F/Yute', 'F/Beige', 'F/Negro', 'F/Cristal'],
            tipo: [nil,'Jirafa', 'Petatillo', 'Estrella'],
            tamaño: [nil,'Doble', 'Triple'],
            placa: {
                tipo: [nil,'Normal', 'Con Corte'],
                color: [nil,'Chocolate', 'Marfin']  
                }
            },
        anillo: {
            nombre: [nil,'alianza rectangular', 'rombos dorado'],
            tamaño: [nil,1,2,3,4,5,6,7,8,9,10,11,12]
            }
        }

A cleaner way would be to use filter() to return collection of elements that have values and then check length of that collection

$('form').submit(function(){
   // could simplify selector by using a common class
   var $inputs =  $('#base_agrad, #req_agrad, #req_agrad1, #req_agrad2');

   // filter the inputs that have value and get length of result
   var hasValueCount = $inputs.filter(function(){
          return $(this).val();
       }).length;

   // only valid if none selected or all selected
   var isValid = !hasValueCount || hasValueCount === $inputs.length;

   if(!isValid){
      // display error message    
   } 
   return isValid; 

});

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