Simplified JavaScript code for generating concealed input forms

Seeking assistance to enhance the form I designed, despite my limited knowledge in JavaScript programming.

The objective is to develop a hotel search engine with the ability to specify the total number of rooms. Based on the selected number of rooms, additional hidden form fields will be displayed, providing further selection options.

To gain a clearer understanding of my concept, I have attached a screenshot.

https://i.sstatic.net/ZTGk7.jpg

I have utilized the following JavaScript code to display hidden fields corresponding to the chosen number of rooms, which is repeated 5 times (maximum room count).

function admSelectCheck(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("room1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("pax_room_1").style.display = "block";
    }
    else{
        document.getElementById("pax_room_1").style.display = "none";
    }
}
else{
    document.getElementById("pax_room_1").style.display = "none";
}

Similarly, I have employed JavaScript code to facilitate room selection options, with repetition based on the room count. For example: 1 room -> code entered once; 2 rooms -> code entered twice; and so forth.

function childSelect(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("child1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild1").style.display = "block";
    }
    else{
        document.getElementById("agechild1").style.display = "none";
    }
 }
 else{
    document.getElementById("agechild1").style.display = "none";
 }

 // ... Repeated similar logic for child selection based on room count

}

$(function(){
     $(':submit').click(function(){
          $('select').each(function(){
              if ( $(this).val() == '' )
              {
                  $(this).remove(); // or 
$(this).attr('disabled','disabled');
              }
          });
     });
});

Furthermore, I have repeated the same HTML structure for the hidden fields display.

<div class="container_hidden">

    // ... HTML code for room and child selections repeated for each room count

</div>

While this approach is functional, it appears cumbersome. Hence, I am inquiring if there is an alternate method to streamline the code.

Answer №1

You have the option to utilize the data-* attribute to dynamically select the relations in the html.

For example:

(function() {
  const hiders = document.getElementsByClassName('hider');
  
  for (let i = 0; i < hiders.length; ++i) {
    const hider = hiders[i];

    hider.onchange = function() {
      const hideTarget = hider.dataset.hideTarget;

      if (hideTarget == null)
        return;
        
      if (hider.value !== '')
        document.getElementById(hideTarget).style.display = "block";
      else
        document.getElementById(hideTarget).style.display = "none";
    };
  }
})()
<select id="adulti" name="nrAdult" class="hider" data-hide-target="hideme1">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>        
</select>

<div id="hideme1" style="display: none;">
  Hide me 1
</div>

<select id="adulti2" name="nrAdult" class="hider" data-hide-target="hideme2">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>        
</select>

<div id="hideme2" style="display: none;">
  Hide me 2
</div>

If you need further clarification on this snippet, feel free to ask.


Also, you can use this approach for convenience in this scenario:

(function(){
  function makeOption(val) {
    const option = document.createElement('option');
    option.value = val;
    option.innerText = val;
    return option;
  }

  const simpleSelects = document.getElementsByClassName('simpleSelect');
  for(let i = 0; i < simpleSelects.length; ++i){
    const simpleSelect = simpleSelects[i];
    const min = simpleSelect.dataset.from;
    const max = simpleSelect.dataset.to;
    
    if(min == null || max == null)
      return;
      
    simpleSelect.appendChild(makeOption('-'));
    
    for (let j = min; j <= max; ++j) {
      simpleSelect.appendChild(makeOption(j));
    }
  }
})()
<select name="nrAdult" class="simpleSelect" data-from="0" data-to="5"></select>
<select name="nrChildren" class="simpleSelect" data-from="0" data-to="10"></select>


It's worth noting that using the same id multiple times is not allowed and will not work as intended.

(While this may not directly align with your needs, the underlying principle remains the same, offering a more customized solution.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Using the HTMLTextAreaElement object in Vue.js

I'm utilizing the Laravel package "laracasts/utilities" to transmit Laravel variables to JavaScript files. Below is the code snippet from my controller: JavaScript::put([ 'description' => $room->description ]); He ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

Prevent scrolling in AngularJS model popups

When loading data for the first time in a model popup, the scroll bar is not displayed inside the popup. However, after performing a search function and filtering the data, the scroll bar appears inside the model popup. How can this issue be fixed? this ...

Display table rows that are hidden in an HTML/Angular toggle function

I am relatively new to Angular and I have a task of setting up a table. The dataset that I have is as follows:- data = [{rollno: 1,name: 'abc',subject: 'maths'}, {rollno: 4,name: 'xyz',subject: 'history'}, ...

The function react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_4__.jsxDEV(...) is not recognized

For my react-redux project, I utilized json-server as the server for managing orders. The status of each order is saved in the state within UiReducer and is then accessed in the "OrderStatusPage". The current NODE_ENV configuration is set to "development". ...

Ensuring Form Field Validation in Angular JS Prior to Submission

I am currently in the process of developing an Angular JS application that features a 2-step form. This form essentially consists of one form, but utilizes JavaScript to hide the initial panel and reveal the second panel when the user clicks the 'next ...

What is the best way to share information among Vue3 single file component instances?

I am seeking a way to have certain data in my single file component shared among all instances on the page, similar to how static variables work in PHP/C. To achieve this, I understand that in single file components, we declare data as a function like so: ...

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

Unable to define a range for the hr element using the nth-of-type selector

Why isn't the hr element from the 1st to the 3rd hour red as specified in the CSS code below? hr:nth-of-type(n+1):nth-of-type(-n+3){ background:red; } <!DOCTYPE html> <html> <head> </head> <body> <hr /> <p>T ...

Bootstrap3 Remote Modal experiencing conflict due to Javascript

Utilizing a bootstrap modal to showcase various tasks with different content but the same format is my current goal. However, I am encountering an issue when attempting to make the textareas editable using JavaScript. The conflict arises when I open and cl ...

The background is obscured from view because of its current positioning

The issue I am facing is that the background color of the <ol> list is not showing correctly. This problem arose after I floated the label to the left and the input to the right. How can I resolve this? The desired outcome should be: My current resu ...

Determine which scroll bar is currently in use

I'm running into an issue with multiple scrollbars on my page - they just don't seem to be functioning correctly: <div class="dates-container" v-for="id in ids"> <overlay-scrollbars :ref="`datesHeader` ...

Is Python being used to track NBA.com stats?

Does anyone have any advice on how to extract NBA.com "tracking" stats using a python script and display them in a simple table? I'm particularly struggling with this specific section of stats on the site. Accessing stats directly from NBA.com can be ...

Having trouble displaying the Chrome context menu for a specific Chrome extension

I've read through several posts on this topic, but I'm still struggling to identify the issue with my implementation of the Chrome contextMenu API. I simply copied the code from a tutorial on Chrome APIs, and though there are no errors, the menu ...

With JQuery UI, a dialog can be easily created. Simply pressing the escape key will close the dialog

I have a Login dialog that triggers an alert dialog when the user fails to fill in all the required fields. Pressing escape closes the login dialog instead of the alert dialog. Libraries used: jquery-1.7.2.js jqueryui-1.8.18.js // Function to display ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Listening on TCP port for HTML5 Websocket communications

I have a desktop application that is communicating with my asp.net mvc app. The desktop application publishes data on port:10000 which I need to be able to listen to in the browser. Below is the code snippet: <html> <head> <s ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...