Edgars Rozenfelds Edgars Rozenfelds - 1 year ago 70
jQuery Question

Enable button when 2 conditions are fulfilled

I am trying to figure out a solution to this problem:

I would like to have a function that checks if a text field is filled with text and checkbox is checked. When these conditions are fulfilled "Submit" button is enabled. If shortly after "Submit" button was enabled, user clears text field or unchecks checkbox, the "Submit" button should be disabled again.

My code:

<%= f.text_field :humanizer_answer ,:class=> "form-control",:required => true, :id=>"answer_humanizer_profile"%>
<%= f.check_box :not_a_robot, :id=>"vbbbb",:required => true,:type=> "input" %>

<%= button_to t('confirm'), registration_path(@user), data: { confirm: t('confirm_big') }, method: :delete, :class=>"blue-button btn btn-default", :disabled =>:true,:id=>"hid-button" %>

At this moment I have tried this function:

$("#vbbbb").change(function() {
$value = $("#answer_humanizer_profile").val();

if(this.checked && $value > 0) {
$('#hid-button').prop('disabled', false);
} else {
$('#hid-button').prop('disabled', true);

This function does a little bit of what I need but not 100% of it.

Answer Source

Every time something is typed or changed in the input field or the checkbox is changed trigger a checking function. There evaluate the conditions to disable or enable the submit button. See well commented example below in the code-runner:

//cache dom elements into variables for performance
var textBox = $("#myTextBox");
var checkBox = $('#myCheckBox');
var submitButton = $("#mySubmitButton");

//trigger checking if anything changes in textbox or checkox
textBox.bind("keyup change", function(e) {
checkBox.change(function() {

//checker that evaluates conditions to disable or enable button
function checker() {
  var cond1 = checkBox.is(":checked");
  var cond2 = (textBox.val().length > 0);
  if (cond1 && cond2) {
    submitButton.prop('disabled', false);
  } else {
    submitButton.prop('disabled', true);
<!DOCTYPE html>

  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <input type="text" id="myTextBox">
    <input type="checkbox" name="vehicle" value="Bike" id="myCheckBox">I have a foobar
    <button type="submit" id="mySubmitButton" disabled>SUBMIT</button>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download