Interacting with jQuery and HTML: Revealing sub dvi box content by clicking on the current div box ID

This is my unique jQuery and HTML code.

My objective is to display the corresponding sub_box when clicking on box1, box2, or box3.

For example: Clicking on box1 should reveal sub_box_1. I have attempted some jQuery code but haven't achieved the desired outcome.

Thank you!

$(document).ready(function() {
  $('.sub_box').hide();
  $('.box').click(function() {
    $(this).$('#sub_box_1').show();
  });
});
.box {
  width: 150px;
  height: 150px;
  float: left;
  margin-left: 20px;
  border: 1px solid #333;
  margin-top: 10px;
}
.sub_box {
  width: 150px;
  height: 150px;
  border: 1px solid #09c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>

<head>

</head>

<body>
  <div id="wrapp">

    <div id="1" class="box">
      <b>Box 1</b>

      <div id="sub_box_1" class="sub_box">
        <input type="text" name="user_name" placeholder='User Name' />
        <button>ADD</button>
      </div>
      <!--sub_box_1-->
    </div>
    <!--1-->

    <div id="2" class="box">
      <b>Box 2</b>
      <div id="sub_box_2" class="sub_box">
        <input type="text" name="user_email" placeholder='User Email' />
        <button>ADD</button>
      </div>
      <!--sub_box_2-->
    </div>
    <!--2-->

    <div id="3" class="box">
      <b>Box 3</b>
      <div id="sub_box_3" class="sub_box">
        <input type="text" name="user_phone" placeholder='User Phone' />
        <button>ADD</button>
      </div>
      <!--sub_box_3-->
    </div>
    <!--3-->

  </div>
  <!--wrapp-->
</body>

</html>

Answer №1

Give this a try:

$(document).ready(function() {
  $('.sub_box').hide();
  $('.box').click(function() {
    $(this).children('.sub_box').show();
  });
});

Here is an example on jsfiddle: https://jsfiddle.net/d6zf0n1b/

Answer №2

When attempting to use $(this).$('#sub_box_1'), you are essentially trying to call the $ function on the result of $(this), which does not exist. This is why an error is being thrown.

Another issue is that using the "#" selector in this context targets elements by their id, not their class.

This is why Andre's solution works - he starts from the clicked box and finds immediate children with the class "sub_box".

Keep in mind that the children method only searches one level deep from the parent element. If the desired element could be nested deeper, consider using the 'find' method instead.

Answer №3

If you want to locate elements within a specific element using jQuery, you can make use of the `find` method (view more at https://api.jquery.com/find/). Simply follow this example:

$(document).ready(function() {
  $('.sub_box').hide();
  $('.box').click(function() {
    $(this).find('.sub_box').show();
  });
});
.box {
  width: 150px;
  height: 150px;
  float: left;
  margin-left: 20px;
  border: 1px solid #333;
  margin-top: 10px;
}
.sub_box {
  width: 150px;
  height: 150px;
  border: 1px solid #09c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>

<head>

</head>

<body>
  <div id="wrapp">

    <div id="1" class="box">
      <b>Box 1</b>

      <div id="sub_box_1" class="sub_box">
        <input type="text" name="user_name" placeholder='User Name' />
        <button>ADD</button>
      </div>
      <!--sub_box_1-->
    </div>
    <!--1-->

    <div id="2" class="box">
      <b>Box 2</b>
      <div id="sub_box_2" class="sub_box">
        <input type="text" name="user_email" placeholder='User Email' />
        <button>ADD</button>
      </div>
      <!--sub_box_2-->
    </div>
    <!--2-->

    <div id="3" class="box">
      <b>Box 3</b>
      <div id="sub_box_3" class="sub_box">
        <input type="text" name="user_phone" placeholder='User Phone' />
        <button>ADD</button>
      </div>
      <!--sub_box_3-->
    </div>
    <!--3-->

  </div>
  <!--wrapp-->
</body>

</html>

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

"Upon applying overflow:hidden to the wrapper through jQuery, the window automatically scrolls to the

In my jQuery code, I don't want the window to scroll to the top when my wrapper is set to overflow:hidden. $('#shownav').click(function(event) { $('#wrapper').toggleClass('noscroll'); return false; }); Her ...

The div's style property now includes Tailwind Width set at 0px

Currently, I am developing a web application with Next.JS and Tailwind CSS for styling. In this project, I need to map over some "accords" related to perfumes and assign variable widths to each one based on the size property of the accord, which is a strin ...

Is server-side rendering necessary for `browserHistory` in React Router?

I am a beginner in the world of React and currently diving into the complexities of routing. While hashHistory (/#/paths/like/this) proves to be functional, browserHistory (/paths/like/this) appears much cleaner. However, I noticed that when reopening URLs ...

Data from AngularFire not displaying in my list application

While going through tutorials on the Angular website, I encountered a roadblock while attempting to create a list that utilizes Firebase for data storage. Strangely, everything seems to be functional on the Angular site, but clicking on the "Edit Me" link ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Comparison between setTimeout for this.state and useState

When working with a class component, the code looks like this: setTimeout(() => console.log(this.state.count), 5000); Whereas when using hooks: const [count, setCount] = useState(0); setTimeout(() => console.log(count), 5000); If the setTimeout fun ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

What is the best way to send checkbox values to ActionResult in MVC5?

I am working on an MVC5 application and within my view, I have the following code snippet: <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" }) <div c ...

Fetching data from jQuery and passing it to a Django view

What is the process for retrieving an object value and using it in Django Views? I am trying to use the result of an autocomplete search to filter views in Django. Below is my current search view code: def search_view(request): q = request.GET['term ...

I am having issues with my search form - it doesn't appear to be

I am trying to create a search form that will display users (username, firstname, or lastname) from my database as the user types, similar to how Facebook and Twitter do it. However, when I click on the search button, nothing happens. Below are two parts o ...

What is the process for transitioning from Ajax to Fetch API in JavaScript?

Currently, I am utilizing the JavaScript version of RiveScript which relies on ajax, and I have decided to move away from using jQuery. There is a single line of ajax code that I need to update to integrate the new Fetch API. **Note: The ajax code can be ...

Convert your website to AJAX with Internet Explorer versions 8 and 9 using the URL /#./profile

While Ajaxify performs well in modern browsers, I have encountered some strange URL behavior when using IE8 and 9. The URL ends up looking like http://domain.com/#./profile instead of http://domain.com/profile Is this a known issue or am I missing somethi ...

PHP API is returning the entire object, rather than just the message

I recently developed a REST API using PHP for data insertion. However, when I try to display the message in my AJAX success response, all I get is a series of objects instead. Here is my PHP code snippet: if(mysqli_query($connection , $ins)){ echo jso ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

How to Limit the Number of Rows in a Vue.js Bootstrap Table

Is there a way to display only the first row of a Bootstrap table initially, and then reveal the rest of the rows using a checkbox? Keep in mind that the Bootstrap table and checkbox are located in different components. <b-table hover small responsive b ...

Unique styling tricks for div widths in Chrome

I have created a navigation section with dropdown buttons. I want the width of the divs to adjust based on the text length. In Firefox, everything looks good and works as expected. However, when I checked the site in Chrome, the navigation section behave ...

Why does Javascript in Angular throw an exception when using value, match, and replace functions together?

I have a small JavaScript function that I would like to implement in an Angular service or controller. function cprCheck(frm) { var cpr = frm.cpr.value; if (cpr.match(/[0-9]{6}\-[0-9]{4}/)) { cpr = cpr.replace(/\-/g, ""); var chk = 0; ...

Having difficulty showcasing the JSON data within the dropdown list within an HTML table

In my HTML table, I have 4 rows with Order ID and Product Comments columns disabled. Users can enter data in other columns and submit it. Upon submission, I receive a JSON object which I iterate through and display in the table. I am facing two challenges ...

What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next(). However, I am looking for a way to push items into this array without having to assign a full copy ...