0
\$\begingroup\$

I've written this JavaScript code, which disables textboxes if the previous textbox is empty. This is so people enter the text in order — write first in the first textbox, only then the second textbox enables, write in the second, enable the third, etc. It also clears and disables any textboxes below the one that had its text deleted.

The code works as intended, but I'm afraid if my colleagues see it they will laugh at how it is written and the more textboxes it has the more spammy it gets. Please tell me how I can optimize this?

$q.find(".row1 :text, .row2 :text, .row3 :text").on("keyup", function(){
 var userRow1 = $q.find(".row1 :text")
 var userRow2 = $q.find(".row2 :text")
 var userRow3 = $q.find(".row3 :text")
 var userRow4 = $q.find(".row4 :text")
 
 if (userRow1.val().trim().length > 0) {
 userRow2.enable(); 
 } else {
 userRow2.val("").disable().fclear;
 userRow3.val("").disable().fclear;
 userRow4.val("").disable().fclear;
 };
 
 if (userRow2.val().trim().length > 0) {
 userRow3.enable(); 
 } else {
 userRow3.val("").disable().fclear;
 userRow4.val("").disable().fclear;
 };
 
 if (userRow3.val().trim().length > 0) {
 userRow4.enable(); 
 } else {
 userRow4.val("").disable().fclear;
 };
 
}).trigger("keyup");
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Mar 8, 2023 at 20:22
\$\endgroup\$
4
  • \$\begingroup\$ Can you also post your html ? \$\endgroup\$ Commented Mar 8, 2023 at 20:46
  • 1
    \$\begingroup\$ Welcome to Code Review! Does $q come from jQuery or a similar library? What is fclear? \$\endgroup\$ Commented Mar 8, 2023 at 21:46
  • \$\begingroup\$ Sorry, Alex HTML is not available. ".row1" ".row2" etc. just stand for the row classes while :text selects the textbox on that row. \$\endgroup\$ Commented Mar 8, 2023 at 22:08
  • \$\begingroup\$ Hi Sam, $q does come form jQuery, in the code I just use to to specify the current page/question. while the fclear function will just clear any text in the specified textbox. \$\endgroup\$ Commented Mar 8, 2023 at 22:13

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.