If the option is not chosen, remove the requirement for it

I am in the process of creating a form that offers 3 different payment options:

1 - Direct Deposit
2 - Credit Card
3 - Cash at Office

The issue I am facing is with the validation of input fields for Credit Cards. I want to make it so that these fields are not mandatory if the user does not select Credit Card as their payment method. This way, the form can be submitted without this information if it's not needed.

Any suggestions on how to achieve this? You can view my current setup on JSfiddle: http://jsfiddle.net/barmar/Kvg8M/2/

Here is the JavaScript code I have implemented:

$(document).ready(function () {
    $(".paymentmethod").click(function () {
        $(".paymentinfo").hide();
        switch ($(this).val()) {
          case "Direct Deposit":
              $("#pay0").show("slow");
              break;
          case "Credit Card Authorisation":
              $("#pay1").show("slow");
              break;
          case "Cash at FAA Office (In Person)":
              $("#pay2").show("slow");
               break;
         }
     });
});

I am also using Adobe Business Catalyst for this project. Any tips or advice related to this platform would be appreciated!

Answer №1

Key Point: The req class is essential for ensuring the required field values are met. When the req class is applied to any element, filling out that element becomes mandatory within your code.

Insight: Removing this class from an element makes it optional to fill out. Conversely, adding the class back will once again make it a required field.

Method for Adding or Removing Class using jQuery:

$('#CardName').addClass('req');
$('#CardName').removeClass('req');

If you do not use jQuery, refer to the following guide.

Remove CSS class from element with JavaScript (no jQuery)


$(document).ready(function () {

function setMend() {
   alert("Setting mend");
  $('#CardName').addClass('req');
  $('#CardNumber').addClass('req');
  $('#CardExpiryMonth').addClass('req');
}

function unsetMen(){
    alert("Unsetting mend");
    $('#CardName').removeClass('req');
    $('#CardNumber').removeClass('req');
    $('#CardExpiryMonth').removeClass('req');
 }

    $(".paymentmethod").click(function () {
        $(".paymentinfo").hide();
        switch ($(this).val()) {
            case "Direct Deposit":
                $("#pay0").show("slow"); 
                unsetMen();                
                break;
            case "Credit Card Authorisation":
                $("#pay1").show("slow");
                setMend();
                break;
            case "Cash at FAA Office (In Person)":
                $("#pay2").show("slow"); 
                unsetMen();
                break;
        }
    });
});

Answer №2

give this a shot

$(document).ready(function () {
        $(".paymentmethod").click(function () {
        $(".paymentinfo").hide();
        switch ($(this).val()) {
        case "Direct Deposit":
            $("#pay0").show("slow");
         $("#filedID").rules('remove', 'required');
            break;
        case "Credit Card Authorisation":
            $("#pay1").show("slow");
            break;
        case "Cash at FAA Office (In Person)":
            $("#pay2").show("slow");
            break;
            }
        });
    });

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

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

How come "display:none" is still occupying space on the page?

Trying to figure out how to make a specific cell in a table disappear when viewing an HTML page on mobile devices, while having a width of 20% for desktop. However, the issue is that even though the table cell is invisible on mobile, it still occupies sp ...

Is there a way to prevent Prettier from automatically inserting parentheses for a single argument in an arrow function?

Currently, I've integrated Prettier into my workflow, but I've encountered an issue with arrow functions in JavaScript. For example: arg => console.log(arg) However, Prettier automatically formats it as: (arg) => console.log(arg) This for ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

exchanging the positions of two animated flipdivs

Hey there! I'm facing a little challenge with my two divs (let's call them div1 and div2). One of them has a flip animation on hover, while the other flips on toggle click. My goal is to swap these two divs by dragging and dropping them. I' ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the ...

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

Obtaining Asynchronous JavaScript responses with Selenium Webdriver

We recently integrated an asynchronous JavaScript call into our website. I am currently working on configuring Selenium Webdriver to pause and wait for a response from this particular call. The event listener code snippet is as follows: $(document).on("a ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

Place two divs side by side with the second div filling up the remaining space on the line

Hello there, can anyone lend a hand with this problem? This is the code I have been working with: <html> <body> <div style="width=100%"> <div style="float:left; background-color:Red; height:100px">Red</div> <div st ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Save user input data into an Excel file using PHPExcel

Could someone assist me with storing values from my form inputs to Excel using PHPExcel? I have successfully stored data from my table to Excel, but now I want to store the values from my inputs. Can anyone help me, please? Example of the form inputs: ent ...

"Utilizing React.js to implement white-space styling on numeric values for

I am a beginner in Reactjs and eager to learn and improve. Here is some code I have been working on: there's an <h1> element with the text "test", and beneath it, I want to display numbers vertically like this: 1:1, 1:2, 1:3. However, the CSS do ...

Avoid refreshing the page when adding an item to the cart

I am in the process of creating a online shopping cart and I'm looking for ways to avoid the page from reloading when adding a product to the cart. At the moment, my approach involves using the GET method to add products to the cart. <a href="car ...

Preserving chosen options in a dropdown menu using PHP and HTML

I'm facing an issue with my code where the selected values in a dropdown menu revert back to default every time the page refreshes. How can I ensure that the selected values remain unchanged? Unfortunately, I am unable to utilize AJAX as per the user ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Problem encountered when utilizing dat.GUI in a three.js demonstration

I recently experimented with using dat.GUI in a specific three.js example. To integrate a GUI for adjusting mesh opacity, I made the following code modifications. var loader=new THREE.VTKLoader(); loader.load ("models/vtk/bunny.vtk", function(geom){ var ...

Encountering difficulties connecting to the database within Vue data tables

My php script was working fine with vuetify data, but now every page is showing the error message: Your search for "{{ search }}" found no results. It seems like this issue occurs when the script cannot fetch data from the database. Here is my d ...

How to handle an unexpected token error when using a function within another function in

I'm encountering an issue where the function below is placed above my render function. It doesn't seem to allow me to nest a function within another function. Can you help me identify what's causing this problem? onSelected(i){ this.st ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...