Ways to display an additional field depending on the data in a number input field using jQuery

https://i.sstatic.net/xfNCt.png

When working with Woocommerce, I am attempting to dynamically display a certain number of child age fields based on the data entered in the initial child field. By default, these child age boxes are hidden using CSS. How can I achieve this functionality using jQuery? Any insights or suggestions would be greatly appreciated.

1) Code snippet for the child field:

<div class="yith-wcbk-form-section yith-wcbk-form-section-person-types">
<label for="yith-wcbk-booking-persons-type-390">
    Child</label>
<input id="yith-wcbk-booking-persons-type-390" name="person_types[390]" class="yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="0" max="4" data-person-type-id="390" value="" type="number">
</div>

2) Code snippet for the first age field:

<div class="yith-wcbk-form-section yith-wcbk-form-section-person-types">
<label for="yith-wcbk-booking-persons-type-450">
    1st age</label>
<input id="yith-wcbk-booking-persons-type-450" name="person_types[450]" class="yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="0" max="12" data-person-type-id="450" value="" type="number">
</div>

3) Although I tried implementing the following JavaScript code, it did not work as expected:

jQuery('#yith-wcbk-booking-persons-type-390').change(function(){
    if(jQuery(this).val() === '1') {
        jQuery('#yith-wcbk-booking-persons-type-450').show();
    }
    // Additional conditions and show functions omitted for brevity
});

This JSFiddle example works perfectly, but encounters issues when incorporated into a Wordpress environment.

Answer №1

<script type="text/javascript" language="javascript">
    $(function() {
        $('.small-age').val("4");
        $('.medium-age').val("12");
    });
</script> 
<div class="yith-wcbk-form-section yith-wcbk-form-section-person-types">
<label for="yith-wcbk-booking-persons-type-450">
    1st age</label>
<input id="yith-wcbk-booking-persons-type-450" name="person_types[450]" class="yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="0" max="12" data-person-type-id="450" value="" type="number">
</div>
<div class="medium-age yith-wcbk-form-section yith-wcbk-form-section-person-types">
<label for="yith-wcbk-booking-persons-type-390">
    Child</label>
<input id="yith-wcbk-booking-persons-type-390" name="person_types[390]" class="small-age yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="0" max="4" data-person-type-id="390" value="" type="number">
</div>

Answer №2

Hey there! Check out the updated code below, it should work perfectly:

You can find the link to the code here

HTML Section:

Make sure the main input field has the following value:

value="0"

Here's an example of how it should look like in your HTML structure:

<input id="yith-wcbk-booking-persons-type-389" name="person_types[389]" class="yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="1" max="4" data-person-type-id="389" value="0" type="number">

CSS Styling:

#yith-wcbk-booking-persons-type-450{
    display: none;
    }
#yith-wcbk-booking-persons-type-451{
    display: none;
    }
#yith-wcbk-booking-persons-type-452{
    display: none;
    }
#yith-wcbk-booking-persons-type-453{
    display: none;
    }

JQuery Functionality:

$(function() {

$('#yith-wcbk-booking-persons-type-389').change(function() {

var input = $('#yith-wcbk-booking-persons-type-389').val();

        if (input == "1") {
                    $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').hide();
        $('#yith-wcbk-booking-persons-type-452').hide();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if (input == "2"){
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').hide();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if (input == "3"){
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').show();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if (input == "4"){
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').show();
        $('#yith-wcbk-booking-persons-type-453').show();
    }

});
});

You can view an image for reference here

Answer №3

Creating Boxes Using Pure JavaScript

document.getElementById("create").onclick = createBoxes;

function createBoxes() {
  let childNums = document.getElementById("childNum").value;
  console.log("childNums",childNums)
  for(i=1; i<=childNums ; i++) {
     let inputEl = document.createElement("input");
     inputEl.setAttribute('type', 'number');
     inputEl.setAttribute('placeholder', 'Set Age for Child'+i);
     inputEl.setAttribute('id', 'child'+i);
     let label = document.createElement("label");
     let labelTxt = document.createTextNode("Age of child"+i);
     label.setAttribute("for","child"+i);
     label.appendChild(labelTxt);
     document.getElementById('boxes').appendChild(inputEl)
     inputEl.parentNode.insertBefore(label, inputEl.nextSibling);
     let linebreak = document.createElement('br');
     inputEl.parentNode.insertBefore(linebreak, label.nextSibling);
  }
}
<input type="number" id="childNum" placeholder = "enter number of children" />
<button id="create"> Create age boxes</button>
<div id="boxes">
</div>

Answer №4

One method is as follows :--

$('#industry').on('change',function(){
  var selection = $(this).val(); 
  console.log("Detected change..." + selection);
  $("#SaaSMeetings").toggle($(this).val()=="age");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label for="">child</label>
     <select id="industry">
        <option value="Telesales">Select</option>
        <option value="age">1</option>
    </select>
<!-- Show Metric Input based on Industry Selection -->
<input id="SaaSMeetings" name="person_types[450]" class="yith-wcbk-booking-person-types yith-wcbk-number-minifield" step="1" min="0" max="12" data-person-type-id="450" value="" type="number" style="display:none">

To see if JavaScript offers any solutions, you can visit this link.

<script type="text/javascript>
   $('#attribute_369').change(function(){
       if($(this).val() == '435'){
          $('.productView-options .form-field:nth-child(2)').hide(); 
          $('.productView-options .form-field:nth-child(3)').show();
       }else if($(this).val() == '436'){
             $('.productView-options .form-field:nth-child(3)').hide();
             $('.productView-options .form-field:nth-child(2)').show();
       }else if($(this).val() == '434'){
             $('.productView-options .form-field:nth-child(3)').hide();
             $('.productView-options .form-field:nth-child(2)').hide();
       }

   });
</script>

<style>


.productView-options .form-field:nth-child(2) {
    display: none;
}

 .productView-options .form-field:nth-child(3) {
    display: none;
}   
</style>

Answer №5

Would you like to test out this jQuery code snippet? I believe it should be effective:

Note: Instead of constantly using jQuery, you can simply declare it as a variable.

var $ = jQuery

$('#yith-wcbk-booking-persons-type-390').change(function(){

    var tVal = parseInt($(this).val());
    if(tVal == '1') {
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').hide();
        $('#yith-wcbk-booking-persons-type-452').hide();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if(tVal == '2') {
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').hide();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if(tVal == '3') {
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').show();
        $('#yith-wcbk-booking-persons-type-453').hide();
    }else if(tVal == '4') {
        $('#yith-wcbk-booking-persons-type-450').show();
        $('#yith-wcbk-booking-persons-type-451').show();
        $('#yith-wcbk-booking-persons-type-452').show();
        $('#yith-wcbk-booking-persons-type-453').show();
    }
});

I hope you find this solution beneficial.

Answer №6

To enhance the functionality, consider creating a new CSS class called "active" with the property display set to block. Here's an example of how the code should look:

.active{
            display: block;
        }
#yith-wcbk-booking-persons-type-450{
    display: none;
    }
#yith-wcbk-booking-persons-type-451{
    display: none;
    }
#yith-wcbk-booking-persons-type-452{
    display: none;
    }
#yith-wcbk-booking-persons-type-453{
    display: none;
    }

Instead of using show() in JQuery, it's recommended to use addClass('active') for better results.

The updated code would be like this:

jQuery('#yith-wcbk-booking-persons-type-390').change(function(){
    if(jQuery(this).val() === '1') {
        jQuery('#yith-wcbk-booking-persons-type-450').addClass('active');
    }
    if(jQuery(this).val() === '2') {
        jQuery('#yith-wcbk-booking-persons-type-450').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-451').addClass('active');
    }
    if(jQuery(this).val() === '3') {
        jQuery('#yith-wcbk-booking-persons-type-450').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-451').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-452').addClass('active');
    }
    if(jQuery(this).val() === '4') {
        jQuery('#yith-wcbk-booking-persons-type-450').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-451').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-452').addClass('active');
        jQuery('#yith-wcbk-booking-persons-type-453').addClass('active');
    }
});

Answer №7

Hey @Abhee, here's a super simple jQuery solution that I came up with. Take a look and let me know what you think!

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Testing Script</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div>
    <label>
        Child</label>
    <input value="1" type="number" onchange="update_child(this);">
  </div>

  <div id="childs">
    <label>1 child</label>
    <input value="" type="number">
  </div>

  <script type="text/javascript">
    function update_child(me){
      var num_child = $(me)[0].value;
      var child = "";
      for(var i=0;i<num_child;i++){
        child += '<label>'+(i+1)+' child</label><input value="" type="number"><br>';
      }
      $("#childs")[0].innerHTML = child;
    }
  </script>
</body>
</html>

I hope this solution is helpful to you! Happy coding :D

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

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Facing difficulty observing Content-Disposition header in create-react-app project

I am using a create-react-app that is being served by express. Express is acting as a proxy for the app and all the application logic resides in CRA. My issue lies in calling an API to download a file. The API sends back a "Content-Disposition" header wit ...

Printing a Page Using Angular 5

Is there a way to print a specific section of my website with Angular 5? I've searched online for a solution, but it seems like most options are tailored for Angular. Any advice? ...

Exploring Relative Rotations in Three.js

I currently have a scenario where I have a THREE.Scene containing two meshes, namely meshA and meshB. Both of these meshes have been rotated differently. My objective is to take meshB out of the scene and attach it as a child of meshA, while maintaining it ...

What is the best way to manage the retrieved data in a situation where I am utilizing async-await along with the useEffect hook?

I need to retrieve a player's statistics based on the input provided by the user, and then show it. I am facing challenges in storing the retrieved data using the useEffect hook. Any suggestions for a more efficient approach? import React, { useEf ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Is it better to use one large CSS file for Angular 2 or opt for separate files per component

When working with Angular 2, the choice of how to style your application is an important decision. Should you create one large minified .css file using a task runner like Gulp, or use Angular 2's styleUrls: ['myfile.css'] for each component? ...

Update the information in the table with jQuery using AJAX

I have found a solution to refresh my table after deleting a row from it. The refreshing functionality works perfectly, however, the style and other associated JavaScript functions are not working as expected. before https://i.sstatic.net/dPUK0.jpg after ...

Looking for answers to a question about Handlebars in Node.js? Click on the following link to explore more

After successfully parsing my Shopify product items into a MongoDB database using a model, I am attempting to display them to the user using the express-handlebars package. However, I've encountered a small issue. I'm utilizing <td><a ...

Utilizing onmouseover and onmouseoff events with images to dynamically alter text content

I have 6 images and I want to dynamically change the text next to them based on which image is being hovered over with the mouse. Even though I attempted to achieve this using JavaScript with the onmouseover and onmouseout events, my code doesn't see ...

What is the method for utilizing the value component as the key for the second component?

In my JSON data below: [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text": ...

A guide on how to stop the loading animation and transition to a different slide using HTML and CSS

Check out this CSS code snippet @import url(https://fonts.googleapis.com/css?family=Quattrocento+Sans); @import url(https://fonts.googleapis.com/css?family=Quattrocento+Sans); .loading { position: fixed; top: 0; left: 0; width: 100%; height: ...

Issue with Sequelize failing to update a row within a database table

This is my first experience using sequelize. Within my database, I have a table named feed containing columns such as ID, caption, and url. In my controller, there is a straightforward function aimed at updating a row within this table: router.patch(' ...

How can PHP be used to access every element within an array that has been passed through an AJAX call?

I am having trouble accessing elements within an array from my PHP file after passing the array through an ajax call. Here is the code for the ajax call: var data = ['test1', 'test2', 'test3']; $(document).ready(function () { ...

The issue of bidirectional binding not functioning properly has been identified in AngularJS version 1.x

I have a directive that I want to make accessible across multiple pages. The requirement is that when any key is held down, the password should be displayed. The password details are passed from the controller and need to be updated in the directive. For ...

Utilizing Gulp for optimizing JavaScript files for web browsers, including import statements

Creating Isomorphic React Components I am looking to transpile my React components server-side into a single bundle.min.js file. However, I am encountering an issue where the import statements are not being resolved in the resulting file. The specific fi ...

Having difficulty with redirecting through angular's routeprovider

Hi there, I'm new to Angular and I'm running into an issue where I can't redirect to the signup.html page when I hit localhost:port/projectname/ Even though I have specified the template URL for signup in app.js, I keep getting a 404 error. ...

Is there a way to properly align an image within this script format?

I've experimented with different methods, I'm at a loss on how to proceed without ruining the script or rewriting it completely. Check out this page: To fix it, click on the edit button located at the top left corner and insert 2 picture URLs l ...

Loading a page with a subtle fade-in effect using jQuery

Looking to add some jQuery functionality to my navigation menu in order to have the page wrapper fade in and out when a main nav link is clicked. While the code itself is functioning properly, I am encountering a couple of issues: There is a brief flash ...

Is it possible to showcase CSS and JavaScript code exactly as it appears when the files are saved in their respective formats, but embedded within an HTML

Recently, I've been working with notepad++ and have come across an interesting challenge. In my index.html file, I have embedded css and javascript code. Is there a way to display this code as it appears when saved in their respective files, but maint ...