Toggle the visibility of elements (such as a form) with a click of a link - Utilize ajax to

I'm attempting to use jQuery to toggle the visibility of a form. This functionality is triggered by clicking on a specific link...

The goal is to hide all links with data-action="edit" and only display the form that follows the clicked link, as there are multiple boxes on the page.

My objective is to show the form associated with the first box where the link is clicked.

Additionally, I require the ID of the div with the class "box box-primary" in which the anchor (data-action="save") is located.

$(document).ready(function() {
  $('a[data-action=edit').on('click', function() {
    $('div .box-tools').addClass('hide');
    $(this).next('div .spinner').removeClass('hide');
    $(this).next('dl.view-data').addClass('hide');
    $(this).next('form.form-data').removeClass('hide');
  });

  $('a[data-action=cancel').on('click', function() {
    $('div .box-tools').removeClass('hide');
    $('div .spinner').first().addClass('hide');
    $('dl.view-data').first().removeClass('hide');
    $('form.form-data').first().addClass('hide');
  });

  $('a[data-action=save').on('click', function() {
    alert($(this).closest('form.form-data').serialize());
  });
});
.box.box-primary {
  border-top-color: #00acd6;
}

.box {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.25);
  border-top: 3px solid #dddddd;
}

.box {
  position: relative;
  background: #ffffff;
  border-top: 2px solid #c1c1c1;
  margin-bottom: 20px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  width: 100%;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
}

.hide {
  visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

<div class="box box-primary" id="basic-info">
  <div class="box-header">
    <h3 class="box-title">Info</h3>
    <div class="box-tools block-action permanent pull-right">
      <a href="javascript:void(0)" class="btn btn-default" data-action="edit">
EDIT
</a>
    </div>
  </div>
  <div class="box-body">

    <div class="text-center">
      <div class="small spinner hide">
        <div>Loading…</div>
      </div>
    </div>

    <dl class="dl-horizontal view-data">
      <dt>First Name</dt>
      <dd>Test</dd>
      <dt>Last Name</dt>
      <dd>Test</dd>
    </dl>
    <form class="form-horizontal form-data hide" role="form">
      <input type="hidden" name="_token" value="kY4Xjk1GcbLSVYVEwkpy92xeE9ugvPRftPfLVTZF">

      <div class="form-group">
        <label for="first_name" class="col-sm-3 control-label">First Name</label>
        <div class="col-sm-8">
          <input type="text" value="Test" name="first_name" class="form-control" id="first_name" placeholder="First Name">
        </div>
      </div>

      <div class="form-group">
        <label for="last_name" class="col-sm-3 control-label">Last Name</label>
        <div class="col-sm-8">
          <input type="text" value="Test" name="last_name" class="form-control" id="last_name" placeholder="Last Name">
        </div>
      </div>

      <div class="form-group">
        <div class="col-sm-offset-3 col-sm-8">
          <a href="javascript:void(0)" class="btn btn-primary" data-action="save">Save</a>
          <a href="javascript:void(0)" class="btn btn-default" data-action="cancel">Cancel</a>
        </div>
      </div>
    </form>
  </div>
</div>

<div class="box box-primary" id="basic-info2">
  <div class="box-header">
    <h3 class="box-title">Info</h3>
    <div class="box-tools block-action permanent pull-right">
      <a href="javascript:void(0)" class="btn btn-default" data-action="edit">
EDIT
</a>
    </div>
  </div>
  <div class="box-body">

    <div class="text-center">
      <div class="small spinner hide">
        <div>Loading…</div>
      </div>
    </div>

    <dl class="dl-horizontal view-data">
      <dt>First Name</dt>
      <dd>Test</dd>
      <dt>Last Name</dt>
      <dd>Test</dd>
    </dl>
    <form class="form-horizontal form-data hide" role="form">
      <input type="hidden" name="_token" value="kY4Xjk1GcbLSVYVEwkpy92xeE9ugvPRftPfLVTZF">

      <div class="form-group">
        <label for="first_name" class="col-sm-3 control-label">First Name</label>
        <div class="col-sm-8">
          <input type="text" value="Test" name="first_name" class="form-control" id="first_name" placeholder="First Name">
        </div>
      </div>

      <div class="form-group">
        <label for="last_name" class="col-sm-3 control-label">Last Name</label>
        <div class="col-sm-8">
          <input type="text" value="Test" name="last_name" class="form-control" id="last_name" placeholder="Last Name">
        </div>
      </div>

      <div class="form-group">
        <div class="col-sm-offset-3 col-sm-8">
          <a href="javascript:void(0)" class="btn btn-primary" data-action="save">Save</a>
          <a href="javascript:void(0)" class="btn btn-default" data-action="cancel">Cancel</a>
        </div>
      </div>
    </form>
  </div>
</div>

Answer №1

It is important to familiarize yourself with the functionality of .next(),

Here's a functional example based on your code:

$(document).ready(function() {
  $('a[data-action=edit').on('click', function() {
    $(this).closest(".box-primary").find('dl.view-data, .box-tools').addClass('hide');
    $(this).closest(".box-primary").find('.spinner, form.form-data').removeClass('hide');
  });

  $('a[data-action=cancel').on('click', function() {
    $(this).closest(".box-primary").find('.box-tools, dl.view-data').removeClass('hide');
    $(this).closest(".box-primary").find('.spinner, form.form-data').addClass('hide');
  });

  $('a[data-action=save').on('click', function() {
    alert($(this).closest('form.form-data').serialize());
  });
});

Your edit button lacks a $(this).next('div .spinner') due to the absence of sibling elements in your HTML structure, rendering next() ineffective in this scenario.

Demo

$(document).ready(function() {
  $('a[data-action=edit').on('click', function() {
    $(this).closest(".box-primary").find('dl.view-data, .box-tools').addClass('hide');
    $(this).closest(".box-primary").find('.spinner, form.form-data').removeClass('hide');
  });

  $('a[data-action=cancel').on('click', function() {
    $(this).closest(".box-primary").find('.box-tools, dl.view-data').removeClass('hide');
    $(this).closest(".box-primary").find('.spinner, form.form-data').addClass('hide');
  });

  $('a[data-action=save').on('click', function() {
    alert($(this).closest('form.form-data').serialize());
  });
});
.box.box-primary {
  border-top-color: #00acd6;
}

.box {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.25);
  border-top: 3px solid #dddddd;
}

.box {
  position: relative;
  background: #ffffff;
  border-top: 2px solid #c1c1c1;
  margin-bottom: 20px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  width: 100%;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
}

.hide {
  visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

...

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

Troubleshooting: Style sheets not loading on a page rendered by node

Today was my first attempt at learning Node.js and creating a basic server to display a single page with a header tag. However, I encountered an error stating that the CSS file could not be loaded. This is the code I used: const express = require('ex ...

Which is more efficient: Editing the image 'src' or replacing the 'img' tag within a Div?

var currentImage = 0; var totalImages = 8; $(document).ready(function(){ $("#next-img").click(function(){ currentImage = currentImage + 1; if (currentImage > totalImages) {currentImage = 1;}; $(".img-class").attr('src',"http://examp ...

Learn the process of developing a web client application using Node.js and NPM similar to the AngularJS tutorial

I am new to nodejs, npm and angularjs. I recently explored the angularjs tutorial project available at https://github.com/angular/angular-phonecat.git. This project has been really interesting for me as it demonstrates how easy it is to manage modules wi ...

Problem with Scroll Listener on Image in Angular 4: Window Scroll Functioning Properly

Hello, I am a newcomer who is currently working on creating a small application that allows users to zoom in on an image using the mouse scroll. <img (window:scroll)="onScroll($event) .....></img> The code above works well, however, it detec ...

Steps to implement button disabling in React: Once the button is clicked, deactivate it using a React state. Upon receiving a response from the backend code,

1). I have a form that includes a "Save" button. 2). The desired functionality is for the "Save" button to become disabled after being clicked until the backend code confirms that the form has been saved successfully. 3). Once the response from the backend ...

Exploring the wonders of jQuery Ajax within Yii

I am developing a custom shop application and I have a query. In my project, the implementation of Ajax in Yii involves: <?php echo CHtml::ajaxLink( '', array("cart/add/id/$item->id"), array( ' ...

Dreamweaver restricts my ability to utilize JavaScript for coding

My JavaScript isn't working in Dreamweaver. I have linked the script file correctly using the given code: <script src="file:///C:/Users/Matthew/Desktop/Untitled-2.js" type="text/script"></script> However, when I try to call it with scrip ...

Make the active navigation bar item bold and change its font color when clicked

I'm currently working on creating a navigation bar that changes font weight to bold and color to teal when a link is clicked. The issue I'm facing is that when the links are clicked, they turn blue instead of teal and lose their bold formatting, ...

Issue with Next.js hook: Uncaught TypeError - Unable to define properties of undefined (setting 'type')

Encountered an error while attempting to build my nextjs app. Strangely, this error wasn't present in the previous version of the app. I didn't make any changes to the config files, just added a few animation libraries and that's all, along ...

Setting a scope variable in an isolate scope from a link function can be achieved by accessing the

In my attempt to assign a variable within an isolate scope, I am encountering difficulties accessing the variable set in the linked function. Surprisingly, I can access the controller's variable without any issues. app.directive('myDir', fu ...

Create a consistent number based on quantity

Looking to generate a sequence of numbers equal to the count in PHP or JavaScript for my application. For example, if my total count is 7: <?php $total = 7; I would like to generate seven 1's like this: $split_one = [1,1,1,1,1,1,1]; If my count ...

Retrieve the URL of the image from an XML document

Figuring out how to extract the image URL from XML files in Android Studio can be challenging. After analyzing 30 RSS Feed XMLs, I discovered that 95% of them contain ".jpg" images with links starting with "http," not "www." Therefore, I am working on a co ...

Wrap HTML attributes with double quotes using JavaScript

My goal is to add " around attributes that are missing them, using JavaScript. For example: <a class=external title=Title href="http://www.google.com" rel=external>My link</a> Should become: <a class="external" title="Title" href="http:/ ...

Storing multiple textbox values in a single column in PHP

I am using JavaScript to show multiple text boxes when the add button is clicked, but I am unsure of how to store the values of these text boxes in a single column of a database table. Below is my form input code and JavaScript for adding a number of text ...

What is the best way to turn off the jQuery Kladr plugin?

Currently, I'm incorporating the jquery kladr plugin to facilitate address autocompletion specifically for Russia. I am wondering how to deactivate this plugin should a different country be selected? ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Is it possible to invoke Bootstrap modal functions without using jQuery?

I'm in the process of removing jQuery dependencies from my app, but I still rely on Bootstrap. Is there a way to trigger modal functions like $('#myModal').modal('show') without using jQuery now? ...

Uploading Files Using Ajax to a PHP Class

Having some trouble with my file upload using AJAX to post to an object-oriented PHP class. Here's the AJAX code: var handleUpload = function(event) { event.preventDefault(); event.stopPropagation(); var fileInput = document.getElement ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...