Using JavaScript to toggle the visibility of an HTML div element

I'm looking to enhance the functionality of this show/hide HTML div using JavaScript.

HTML

<a href="#" class="clickme">Menu 1</a>
<div class="box">
   <span><span class="labelText"><span></span>Number 1</span></span>
    <input type="text" value="" maxlength="50"><br/>
    <span><span class="labelText"><span></span>Number 2</span></span>
    <input type="text" class="inputclmsize1"  value="" maxlength="50"  aria-invalid="false"><br>
    <a href="">Submit</a>                                                                                     
</div>

<a href="#" class="clickme">Menu 2</a>
<div class="box">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,
</div>

CSS code

body {
font: 12px/16px sans-serif;
margin: 10px;
padding: 0;}

.clickme {
background-color: #eee;
border-radius: 4px;
color: #666;
display: block;
margin-bottom: 5px;
padding: 5px 10px;
text-decoration: none;}

.clickme:hover {
text-decoration: underline;}

.box {
background-color: #ccc;
border-radius: 4px;
color: #333;
margin: 5px 0;
padding: 5px 10px;
width: auto;}

Javascript code

$('.box').hide();
// Make sure all the elements with a class of "clickme" are visible and bound
// with a click event to toggle the "box" state
$('.clickme').each(function() {
    $(this).show(0).on('click', function(e) {
        // This is only needed if your using an anchor to target the "box" elements
        e.preventDefault();

        // Find the next "box" element in the DOM
        $(this).next('.box').slideToggle('fast');
    });

});

When I click on the Menu1 link, two text columns appear with a submit link. I wish that when I click the submit button, Menu 1 closes and Menu 2 description opens automatically. How can I achieve this? Can anyone help with a solution? :( Fiddle link provided here: http://jsfiddle.net/rn4qdyue/2/

Answer №1

To enhance user interaction, you can implement a click event on the submission button and then alternate between displaying each box.

$("#submit").click(function(e){
    e.preventDefault();
    $("#box1").slideToggle('fast');
    $("#box2").slideToggle('fast');
});

I have assigned unique IDs to the submit button as well as both box DIV elements for easier reference.

Check out the interactive demo here: http://jsfiddle.net/5jxnpvkq/

Answer №2

Implement a click handler for when the submit button is clicked.

<a href="" id="submit">Submit</a>

$('#submit').click(function(e){
    e.preventDefault();
    var $parent = $(this).closest('.box');

    $parent.slideToggle('fast');
    $parent.next('.clickme').click();
});

Check out the updated Fiddle here

Answer №3

Here is the solution you requested.

$('#submit').on('click', function(e) {
    e.preventDefault();
    var $element = $(this).parent('.box');

    $element.slideUp('fast');
    $element.next().next('.box').slideDown('fast')
});

View Updated Fiddle

Answer №4

If you want to include an id in your submission form, you can do so easily.

<a id="submit" href="">Submit</a>  

To make it functional with JavaScript:

$('#submit').click(function(e){
    e.preventDefault();
  $('.box').slideToggle('fast');
})

Check out this example on Fiddle.

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

Struggling with jquery's addClass method when trying to apply a class to

Below is a sample tr: <tr> <td><input type="text" class="ingredient required" name="ingredient"></td> <td><input type="number" class="amount required" name="amount" ></td> <td><input type="number" c ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

Adjusting Window Size Causes White Space to Appear Above Div

I currently have two inline-block div in my post page that showcase my latest book reviews. Typically, these sections align perfectly and occupy the same amount of space on the screen. However, for certain window sizes, one of the inline-block elements end ...

Exploring Angular 5: Unleashing the Potential of Component Tags

I have created a unique custom modal for my Angular 5 application, and now I am looking for a way to customize the content within it. For example, here is a snippet of code I have used: <app-modal> <p>Some Text!</p> </app-modal> ...

Accessing firebase using a connection to HTML5 through codeanywhere's devbox

Recently, I added Firebase to my CodeAnywhere HTML5 connection. However, when I tried to execute the shell command firebase login, I was directed to a URL to log in. Despite successfully logging in and granting the necessary permissions, I encountered an e ...

Executing multiple JQuery post requests simultaneously

I am currently working with three functions, each of which posts to a specific PHP page to retrieve data. However, since each PHP script requires some processing time, there is a delay in fetching the data. function nb1() { $.post("p1.php", { ...

SVG fails to render in the browser upon page initialization

I am experiencing difficulties with rendering SVG icons in Google Chrome and other browsers when added through CSS on my website, specifically in a custom dropdown background. Here is a sample of the SVG code: background: #fff url("data:image/svg+xml ...

Animating content with Jquery Waypoints for a seamless and elegant user experience

Currently tackling a project that requires some jQuery functions beyond my current skill set. Hoping to find some solutions here! The project in question is a one page scroll site, with existing jquery and waypoints functions implemented. Check out the c ...

Automatically populate a div with content from a file

As I am completely new to the world of HTML, I find myself in need of quickly putting together something for work just as a proof of concept. I apologize if this question has been answered previously, but honestly, I wouldn't even know how to start se ...

Utilize Vue: Bring in the router within a helper class and navigate to a specific

I'm new to utilizing Vue, and I am currently attempting to import my existing router instance into a JavaScript class where I manage the Authentication. This is the content of my router file: import Vue from 'vue'; import Router from &apos ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Avoid having gulp's uglify plugin remove es6 code

I've encountered an issue while using gulp babel to compile es6. It seems that uglify is stripping out my es6 code completely. Strangely, I'm not receiving any errors in my command line during the process. Have you faced this problem before? Any ...

The importance of safeguarding WordPress data attribute values

I am encountering an issue with my client-side HTML form that sends data to my server using AJAX. The problem is that anyone can easily manipulate the input values by inspecting the element using Chrome, leading to inaccurate data being received on the ser ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Is AJAX.call functioning properly in every browser except for Firefox?

I encountered an issue with an ajax load in Firefox. Every time I try to load, I keep receiving a message that says 'unreachable code after return statement'. Despite my efforts to find a solution, I have not been successful in resolving it. Inte ...

Acquiring information from a variable via an HTTP request

I am new to making http requests and using PHP. I have a code snippet that makes an AJAX call: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc( ...

Regex tips: Matching multiple words in regex

I am struggling with creating a simple regex. My challenge is to write a regex that ensures a string contains all 3 specific words, instead of just any one of them: /advancebrain|com_ixxocart|p\=completed/ I need the regex to match only if all thre ...

Issue observed with alignment not being corrected when the browser is resized on a responsive webpage

Utilizing Bootstrap3 for my responsive page design. In the banner content, I am including a box with text inside: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <s ...

The slash character is escaped by the RegExp constructor, but the dot character is

Consider the following code: console.log(new RegExp('.git')); console.log(new RegExp('scripts/npm')); which produces the following output: /.git/ /scripts\/npm/ The puzzling question here is - why does it escape the slash in &a ...