简体   繁体   中英

how to make all input fields to be filled before submitting

I want to make all input field to be filled before the user submit it. I tried to disable the submit button until my input fields have been filled in. I also tried to validate on client side but could not make it work, the code passes but the button is still not enabled even when all fields are filled out. The button continues to be disabled for some reason.

My _form.html.haml looks like:

= simple_form_for @post, html: { multipart: true } do |f|
    - if @post.errors.any?
        #errors
            %h2
                = pluralize(@post.errors.count, "error")
                prevented this Post from saving
            %ul
                - @post.errors.full_messages.each do |msg|
                    %li= msg

    .form-group
        = f.input :title,:label => "Project Name", input_html: { class: 'form-control', :type => "text", :required => "required", :autofocus => true}
        %small#titleHelp.form-text.text-muted 

    .form-group
        = f.input :image,:label => "Image", input_html: { class: 'form-group',"aria-describedby" => "fileHelp", :required => "required", :type => "file",:autofocus => true }

    .form-group
        = f.input :link,:label => "Project Link", input_html: { class: 'form-control', :type => "url", :value => "https://", :required => "required" , :autofocus => true, id:'url-input'}


    .form-group
        = f.input :description,:label => "Description", input_html: { class: 'form-control', :rows => "3", :required => "required" , :autofocus => true, id: 'description'}
        %small#descriptionHelp.form-text.text-muted 


    %button.btn.btn-info{:type => "submit", :disabled => "disabled" } Add Project

I have tried this in application.js

$('#url-input, #description').on('blur keypress', function() {
  var urlInputLength = $('#url-input').val().length;
  var descriptionInputLength = $('#description').val().length;
  if (urlInputLength == 0 || descriptionInputLength == 0) {
    $('button').prop('disabled',true);
  } else {
    $('button').prop('disabled',false);
  }
});

I feel that my js is not connecting to my html code for some reason. Also, I am wondering if there is any other way to make it work without JS.

Thank you in advance!

validates :attribute, presence: true for each one of the attributes that correspond with one of your fields in the form. The button will still be able to be clicked without all fields filled in, but it will just redirect them to the same page until they fill in all the fields. You can add custom messages too so if they submit without filling the fields, it will tell them what they still need to fill in. Then they can only move on once all fields are filled out.

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