Hiding input fields based on radio button selection can be accomplished by using JavaScript to

There are four radio buttons (fixed, percentage, monthly, yearly), with two buttons sharing common fields and the other two having different common fields. To address this, I created two divs, one for fixed and percentage, and the other for monthly and yearly, each with an "add more" button. However, when entering data for the monthly div (with multiple rows), the zeroth position appears blank in the database as 0. The solution I propose is to have only one div and dynamically hide/show fields based on the selected radio button.

Here is the HTML Code for labels:

<label class="col-sm-2 control-label" for="radioo">Commission type <b style="color:red;">*</b></label>
             <div class="col-lg-10" required>
               <label class="custom-control custom-control-primary custom-radio">
                 <input class="custom-control-input" type="radio" name="comission_type" value="0" checked="checked">
                 <span class="custom-control-indicator"></span>
                 <span class="custom-control-label">Fixed price</span>
               </label>
              <!-- Remaining code for labels -->
         </div>

HTML code for fixed/percentage div

<div id="fixPerDiv" style="display:block;">
          <!-- Code for fixed/percentage division -->
</code></pre>

<p>Html for monthly/fixed div </p>

<pre><code><div id="monYearDiv" style="display:none;">
        <!-- Code for monthly/yearly division -->
       </div>

Jquery code:

<script>
$(document).ready(function() {
   $('input[type=radio][name=comission_type]').change(function() {
       if (this.value == '0' || this.value == '1') {

         $("#fixPerDiv").css("display","block");
         $("#monYearDiv").css("display","none");

       }
       else if (this.value == '2' || this.value == '3') {

           $("#fixPerDiv").css("display","none");
           $("#monYearDiv").css("display","block");
       }
   });
});
</script>

Answer №1

Are you attempting to toggle using the value? Instead of using this.value, I've switched it to use jQuery's $(this).val()

Furthermore, instead of your current if statements, I opted for a switch case -- much easier on my eyes.

If these modifications don't quite meet your requirements, please let me know. I can adjust the JavaScript based on your feedback.

Upon reviewing your issue, it seems I overlooked the root cause. It might be beneficial to treat each form as its own entity -- the problem arises when multiple fields have the same name (like start_date and end_date in either form).

In the updated demo, each toggled element is now its own form. When you click 'add more', the serialized form data is logged to the console to demonstrate that empty form data isn't included in the stream.

I hope this clarifies things!

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

Using jQuery's $.getScript to run legacy functions and variables from an external script

When using jQuery's $.getScript to execute a JavaScript, I'm finding that the executed script doesn't have access to the functions and variables in my source file. Is there any way to solve this issue? ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

Display an Array from a PHP File in HTML Using jQuery

Here is an example of my PHP script used to retrieve and display JSON data: $get_chat = "SELECT * FROM chat WHERE u_id1='$u_id' && u_id2=2 ORDER BY data DESC"; $run_chat = $conn->query($get_chat); if ($run_chat->num_rows > 0) { ...

php reload page with included content

I am currently in the process of building a website using php, jquery, Sass, Bootstrap, and more. The setup I have in place involves one main index page that contains all the necessary includes for the header, CSS files, and JavaScript files. Different pa ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...

Customization disrupts the uniformity of button dimensions

When localizing a web application, we encountered an issue with browsers using different fonts for different languages. This led to the height of certain HTML objects changing, especially noticeable with input buttons. While this behavior is expected, how ...

Searching with Regex, excluding the initial character from the match

It's been a while since I last wrote JavaScript, so any mistakes are probably very obvious. I'm currently facing an issue with using RegExp.match(..) in JavaScript. It seems to be skipping the first character in the strings that are being search ...

Obtaining DOM element generated through jQuery's .load() method

I am striving to fetch an array of data from a MySQL database using PHP for the purpose of utilizing it in a JavaScript function; graph() as illustrated below. My approach involves loading the required data into a DOM element. Although the query is succes ...

Embed the i18n language into the request

Currently, I am utilizing the i18next library in conjunction with React on my frontend. My goal is to transmit my current language information to my API with each request. I have an axios client encapsulated within a constant that is utilized throughout m ...

Data stored in an array on one screen does not appear on another screen

I am facing an issue in a React project where I have two screens, and on one screen, an array is created and passed as props to the other screen. However, the data from the array is not displaying on the second screen. Here is the relevant code snippet: H ...

Setting the z-index for data points in a scatter plot on HighCharts

Utilizing HighCharts to display a large number of points on a plot. Each point has an opacity setting and changes to red when selected. However, some points are difficult to distinguish due to overlapping. I would like the selected point to be easily visi ...

Show real-time data from mongodb on an HTML webpage

Currently, I am developing a Python project and I am looking to retrieve and showcase real-time data from MongoDB. Specifically, I want to exhibit new data in an HTML table page immediately after it's added to the database, while the rest of the data ...

Adjusting the color of a cell based on its value

Currently, I am in the process of converting a CSV file to an HTML table by utilizing a tool available at . However, I am facing a challenge in modifying the background color of cells based on their values. I would greatly appreciate any help or guidance w ...

Align Image According to Dimensions of the Browser

I'm looking for a way to dynamically position an image based on the width and height of the browser within an HTML file. I know that adjusting an image's width/height is possible through code like this: <script> ...

What is the process for canceling an href="javascript:void(null)"?

Lately, I've encountered a frustrating issue with the javascript:void(null); bug when using it in my hrefs for images. In my specific version of Safari (4.0.3 on Leopard PPC), applying an href of javascript:void(null); to an image causes the image to ...

Is there a way to trigger both the link and the div element simultaneously?

Is there a way to make both the button and the link light up simultaneously when hovering over the div element, instead of just the button lighting up first? <div id="b1"; class = b> <a href="test.html">BUY</a> < ...

Dynamic generation causing Bootstrap tabs to malfunction

I have incorporated a bootstrap tab on my website, which is generated dynamically through ajax requests. While testing the static version of these tabs, everything was functioning perfectly. However, now that I am generating all tabs and panes dynamically ...

Struggling to Traverse a nested object in a node.js environment

I've been attempting to iterate over a nested object and save the data to my cloud firestore database, but unfortunately it's not working as expected. Below is the structure of the object retrieved from an API call: { "count": 133, ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...