I'm struggling to make the jquery parentsUntil function work properly

Would appreciate some help with using the jquery parentsUntil method to hide a button until a radio box is selected. I've been struggling with this for a few days now and can't seem to figure out what I'm doing wrong. Any insights would be greatly appreciated.

 (function($) {
 $(function(){
   $('.last-item').change(function() {
     if( $(this).val() != '' ) {
       $(this).parentsUntil('.step').find('.button-next').removeClass('hide');   
       $(this).parentsUntil('.step').find('.button-next').addClass('show');   
       console.log("changing the last item");
     }

   });

 });
})(jQuery);
.hide {
    display: none;
}

.show {
    display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 <div class="step">
 <h1>Step 3 - Personal</h1>                    
   <div class="input-wrapper radio no-feedback">
     <div class="row no-gutter content-position-outer">
       <div class="col-md-6 content-center-inner">
         <label for="gender">What gender are you? <sup>*</sup></label>
       </div>
       <div class="col-md-6 content-center-inner">
         <div class="row">
           <div class="col-md-5 col-md-offset-2">
             <label class="radio-sex" for="gender_male">
               <input class="sr-only last-item" type="radio" placeholder="Male" name="gender" value="Male" id="gender_male" required="required" />
               <div class="radio-img radio-img-sex-male"></div>
                                            Male
                                        </label>
           </div>
           <div class="col-md-5">
             <label class="radio-sex" for="gender_female">
               <input class="sr-only last-item" type="radio" placeholder="Female" name="gender" value="Female" id="gender_female" required="required" />
               <div class="radio-img radio-img-sex-female"></div>
                                            Female
             </label>
           </div> 
         </div>
       </div>
     </div>
   </div>
   <div class="row">
     <div class="col-md-3">
       <a href="" class="button-prev" data-progress="2" data-step="step-2">Previous</a>
     </div>
     <div class="col-md-3 col-md-push-6">
       <a href="" class="button-next hide" data-progress="4" data-step="step-4">Next</a>
     </div>
   </div>            
</div>

JS Fiddle

Answer №1

.parentsUntil() retrieves "the ancestors of each element within the selected elements, excluding the element that matches the specified selector,".

Consider using .closest() as an alternative

Answer №2

Is this what you were looking for?

You don't have to hide anything if the value is empty because a radio button cannot be deselected.

If you wish to hide something when a specific value is empty, you can use .toggle($(this).val()!="")

(function($) {
  $(function() {
    $('.last-item').on("click",function() { // Assuming the last item is a radio button
      $(this).closest("div.step").find('.button-next').show(); 
    });
  });
})(jQuery);
.button-next { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="step">
  <h1>Step 3 - Personal</h1> 
  <div class="input-wrapper radio no-feedback">
    <div class="row no-gutter content-position-outer">
      <div class="col-md-6 content-center-inner">
        <label for="gender">What is your gender? <sup>*</sup>
        </label>
      </div>
      <div class="col-md-6 content-center-inner">
        <div class="row">
          <div class="col-md-5 col-md-offset-2">
            <label class="radio-sex" for="gender_male">
              <input class="sr-only last-item" type="radio" placeholder="Male" name="gender" value="Male" id="gender_male" required="required" />
              <div class="radio-img radio-img-sex-male"></div>
              Male
            </label>
          </div>
          <div class="col-md-5">
            <label class="radio-sex" for="gender_female">
              <input class="sr-only last-item" type="radio" placeholder="Female" name="gender" value="Female" id="gender_female" required="required" />
              <div class="radio-img radio-img-sex-female"></div>
              Female
            </label>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-3">
      <a href="" class="button-prev" data-progress="2" data-step="step-2">Previous</a>
    </div>
    <div class="col-md-3 col-md-push-6">
      <a href="" class="button-next hide" data-progress="4" data-step="step-4">Next</a>
    </div>
  </div>
</div>

Answer №3

Give this code snippet a shot and see if it does the trick

Remember: Don't forget to take out the hide class from -> class="button-next hide"

 $(document).ready(function(){ 
   $('.button-next').hide();
   
   $('input[type="radio"]').click(function() {
       if($(this).prop('checked')) {
            $('.button-next').show();           
       } else {
            $('.button-next').hide();   
       }
   });

 });

Answer №4

After trying all the suggestions provided by everyone, none seemed to do the trick for my situation. Ultimately, I resorted to

$(this).closest('.step-3').find('.button-next').css('display','block');

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

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

Adding dropdown values to text area

I'm encountering a simple issue. My goal is to allow users to select values from a dropdown menu and have those values added to a text area. Additionally, users should be able to input extra content in the text area. Here's what I want: the user ...

Looking to center a title in React Navigation without interference from headerLeft?

I am using react navigation and trying to center the title in the header bar. However, it seems to be affected by the presence of headerLeft. When I disable headerLeft, the title centers perfectly. How can I achieve this without interference from other lef ...

Limit the text input area in HTML to a fixed size, preventing any text from exceeding the specified boundary

Is there a way to create a fixed line text area that limits the user from typing beyond a certain number of lines and maximum width? My current CSS styling for this is as follows: .area-style { resize: none; width: 324px; height: 200px; m ...

Ensure that the content inside the centrally aligned div is also aligned at the

Looking for a way to center a box on a website I'm designing? Instead of aligning it based on existing centering, use the following HTML / CSS code to ensure that the white box is perfectly centered on the page. .loading { position: fixed; z-in ...

Updating page content on JQuery for real-time viewing by multiple users simultaneously

I need to make updates to the content changes for all users on the page. Here is my jquery code snippet: When a user clicks the "assign button", it causes the table row to fade out! $('#check').find('input:checkbox:checked').closest( ...

Space in the middle of a body and a div

After extensively searching for a solution to the issue plaguing my website, I found that there was always an annoying gap at the top of the page. Despite trying various solutions, none seemed to work. Upon inspecting the website in Firefox, I discovered t ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Place the bottom element of the top parent element in position

Creating a simple tooltip with bottom positioning at the top of the parent element involves setting a negative height for the tooltip element. However, when checking the height of the tooltip element upon hovering, it returns 0 according to console.log(). ...

Attempting to relocate various containers

My task involves handling a group of randomly placed boxes on a webpage, each painted in random colors. I am currently attempting to enable their movement from one location to another. Despite being a seemingly simple task, my lack of familiarity with mous ...

Sending HTML data using jQuery's post method

TestData = { Test: function (eventId) { var obj = new Object(); obj.Content = 'Hello<br>world.'; var data = $.toJSON(obj); alert(data); $.post(SvConstant.GetBaseUrl() + "/Services/PageHandler/Tes ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...

Data bindings encapsulated within nested curly braces

I am currently utilizing Angular2 in my application. Within my html file, I have a *ngFor loop set up like so: <div *ngFor="let element of array"> {{element.id}} </div> Next, I have an array containing objects structured as follows: some ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Sending an array from the server to the client using Node and Express during page loading?

I am utilizing Node and Express in my project. The application fetches data from a remote database on page load and sends it to a handlebars template server-side. However, I would like this JSON data to also be accessible for client-side interactions. How ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...