Home>

I want to implement a button that becomes valid once I check and input it in JavaScript.

I created a form with one check box and one text box.

I want to make it valid only when the check box is selected and a character is entered in the text box, and the button is disabled when one or both are selected or not entered.

I want to enable/disable the button in real time both when I click the check box and when I enter text.

If possible, I would like to use one form with conditional branching etc. to switch between valid and invalid.

Thank you.

Error message

No error message.
However, when you move it, the behavior is strange, you can press the button even if only one is enabled, or the button is disabled even though you enter a check box.

Applicable source code

checkbox: Check box
Number: Text box
linkBtn: Button

$(function () {
    $(". linkBtn"). prop ("disabled", true);
    $("[name = 'checkbox']"). on ('click', function () {
        if ($("[name = 'checkbox']"). prop ('checked')) {
            $(". linkBtn"). prop ("disabled", false);
                        $(". btn"). removeClass ("disabled");
        } else {
            $(". linkBtn"). prop ("disabled", true);
                        $(". btn"). addClass ("disabled");
        }
    });
    $("[name = 'Number']"). on ('keydown keyup keypress change', function () {
        if ($("[name = 'checkbox']"). val (). length>0) {
            if ($("[name = 'checkbox']"). prop ('checked')) {
                $(". linkBtn"). prop ("disabled", false);
                                $(". btn"). removeClass ("disabled");
            } else {
                $(". linkBtn"). prop ("disabled", true);
                                $(". btn"). addClass ("disabled");
            }
        }
        else {
            if ($("[name = 'checkbox']"). prop ('checked')) {
                $(". linkBtn"). prop ("disabled", false);
                                $(". btn"). removeClass ("disabled");
            } else {
                $(". linkBtn"). prop ("disabled", true);
                $(". btn"). addClass ("disabled");
            }
        }
    });
});
<form: form action = "/ exercise/ex6 /" method = "post" modelAttribute = "entry">

<label>
<input type = "checkbox" name = "checkbox"><b>Welcome</b>
<p>Welcome</p>
</label>


<label for = "inputId">Number</label>
<form: input maxlength = "5" path = "Number" />

<button type = "submit" name = "reception">Next</button>
</form: form>
Supplemental information (FW/tool version etc.)
  • Answer # 1

    https://StackOverflow.com/questions/142525?link=qa_related_pc

    With reference to this, I was able to implement by adding an initial value to the process.
    Thank you very much.

  • Answer # 2

    
    
    
    
    
    
    
    
    
    
    

Related articles