I know this question has been asked before, but all the other answers I found are way too complicated for me to understand.
When you click a button, I need one section to disappear and another to show in its place.
How can I do this with jQuery?
Here's the outline of my code:
<div class="container">
<div class="hide">
<button class="btn btn-block btn-primary rounded-0 mb-2">Button</button>
<button class="btn btn-block btn-primary rounded-0 btn-hide">Button</button>
</div>
<div class="show mt-3">
<form>
<div class="form-group mb-2">
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<button class="btn btn-block btn-primary rounded-0">Button</button></div>
</form>
</div>
</div>
What do I need to do CSS and jQuery-wise to make this work? So the second section (.show) appears exactly where the first one was?
You need to bind a click event to the button, .show() the section you want to show and .hide() the one you want to hide.
$('.btn').on('click', function() {
$('div-to-show').show();
$('div-to-hide').hide();
});
Example below:
$('#btn').on('click', function() {
$('.hide').hide();
$('.show').show();
});
.hide {
display: block;
}
.show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click Me</button>
<div class="hide">
<button class="btn btn-block btn-primary rounded-0 mb-2">Button</button>
<button class="btn btn-block btn-primary rounded-0 btn-hide">Button</button>
</div>
<div class="show mt-3">
<form>
<div class="form-group mb-2">
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</form>
</div>
First, your HTML has an error in it. You have an extra closing div just before your closing form.
One of your div elements will default to be hidden and the other to be shown. Then upon your trigger (button click) we swap the display of both.
// Get references to the two areas
var divs = $("#div1, #div2");
// When the "trigger" button is clicked, toggle the hidden class on both elements
$("#btnShowHide").on("click", function(){
divs.toggleClass("hidden");
});
.hidden { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="hidden" id="div1">
<button class="btn btn-block btn-primary rounded-0 mb-2">Button</button>
<button class="btn btn-block btn-primary rounded-0 btn-hide">Button</button>
</div>
<div class="show mt-3" id="div2">
<form>
<div class="form-group mb-2">
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<button class="btn btn-block btn-primary rounded-0">Button</button>
</form>
</div>
<button id="btnShowHide" type="button">Click to toggle display</button>
</div>
Related
I have a textarea that I want to show/hide when ever I click a button
and also I need it to target this way because ill be using it in an undefined number of times
SAMPLE IMAGE HERE
SAMPLE IMAGE HERE
here is the HTML that I want to
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2"><i class="bi bi-plus-circle"></i></button>
</div>
<textarea class="form-control" id="multipleNameReq"></textarea>
and here is the script I try to use hiding/Showing it
$('body').on('click', '.buttonMultipleNameReq',function(){
const element1 = $(this);
const target1 = element1.parent().parent().find("#multipleNameReq");
console.log(target1);
if (target1.style.display === "none") {
target1.style.display = "block";
} else {
target1.style.display = "none";
}
})
the accepted answer will work fine for nonduplicate id of textarea or any other elements, but as you have shown in your image if you want to work this for multiple textarea or any elements I suggest you use the class attribute instead of the id attribute, here is the explanation for why to not use same id multiple times,
Duplicate IDs are common validation errors that may break the accessibility of labels, e.g., form fields, and table header cells.
To fix the problem, change an ID value if it is used more than once to be sure each is unique.
here below is some piece of code that may help you to get what are you looking for
$('body').on('click', '.buttonMultipleNameReq',function(e){
let textArea = $(e.target).parent().parent().find('textarea');
if(textArea.css('display') == "block"){
textArea.hide()
}else{
textArea.show()
}
})
.multipleNameReq{
display:block
}
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Using toggle function
here below is simpler code using jquery toggle, here you can read about toggle
$('body').on('click', '.buttonMultipleNameReq',function(e){
$(e.target).parent().parent().find('textarea').toggle();
})
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<div>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">hide/show</button>
</div>
<textarea class="form-control multipleNameReq"></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Since you're using jQuery you could use it's syntax:
To get element:
$('#multipleNameReq');
To Check if element is visible and not hidden:
$('#multipleNameReq').is(":visible");
To Show:
$('#multipleNameReq').show();
To Hide:
$('#multipleNameReq').hide();
A solution to add into your click function would look like:
if ($('#multipleNameReq').is(":visible")) {
$('#multipleNameReq').hide();
} else {
$('#multipleNameReq').show();
}
To access and change the style of an element you need to use the css function.
$('body').on('click', '.buttonMultipleNameReq', function() {
const element1 = $(this);
const target1 = element1.parent().parent().find("#multipleNameReq");
if (target1.css('display') === "none") {
target1.css('display', "block");
} else {
target1.css('display', "none");
}
})
<div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group mb-3">
<input type="text" name="tname[]" class="form-control" required placeholder="req. for">
<button class="btn btn-outline-secondary buttonMultipleNameReq" type="button" id="button-addon2">Click<i class="bi bi-plus-circle"></i></button>
</div>
<textarea class="form-control" id="multipleNameReq" style="display: block;"></textarea>
</div>
I have multiple groups of DIV´s with each their button, in these groups I have 2 DIVS that should toggle between them on click on that button, and also switch the content on the buttons, but each group and button have their own unique ID.
The button ID´s are defined with EditButton<%=DataCon("ID")%> (Which gives EditButton1, EditButton2, EditButton3 .. etc) and the 2 DIVS in each group is called EditData<%=DataCon("ID")%> and TextData<%=DataCon("ID")%> (I.e EditData1 and TextData)
The button serverside:
<button id="EditButton<%=DataCon("ID")%>" class="btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
Which result in:
<button id="EditButton1" class="btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
The Severside JavaScript (ASP) I have:
$(function(){
$('div.EditData<%=DataCon("ID")%>').hide();// hide it initially
$('button').on('click', function(){
$('div.EditData<%=DataCon("ID")%>, div.TextData<%=DataCon("ID")%>').toggle();
});
});
$("button.EditButton<%=DataCon("ID")%>").on("click", function() {
var el = $(this);
if (el.text() == el.data("text-swap")) {
el.text(el.data("text-original"));
} else {
el.data("text-original", el.text());
el.text(el.data("text-swap"));
}
});
Which results in :
$(function(){
$('div.EditData1').hide();// hide it initially
$('button').on('click', function(){
$('div.EditData1, div.TextData1').toggle();
});
});
$("button.EditButton1").on("click", function() {
var el = $(this);
if (el.text() == el.data("text-swap")) {
el.text(el.data("text-original"));
} else {
el.data("text-original", el.text());
el.text(el.data("text-swap"));
}
});
The Severside DIVS in HTML :
<div class="EditData<%=DataCon("ID")%>" style="display:none">
<div class="input-group">
<input type="text" class="form-control" placeholder="<%=DataCon("FullName")%>" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData<%=DataCon("ID")%>">
<%=DataCon("FullName")%>
</div>
Which results in:
<div class="EditData1" style="display:none">
<div class="input-group">
<input type="text" class="form-control" placeholder="Some Name" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData1">
Some Name
</div>
The above script is obviously not working because I am not calling the DIVS and Buttons correctly, but how do I fix this?
Best Regards
Stig :-)
I think #Rory McCrossan's idea to use closest() would work, the only issue is that if you have display none on the container with the button in it, then the button won't be visible to begin with.
You could adjust your markup a bit so that the Edit button and the form are both siblings of a common parent. That would allow you to use nextSibling() in vanilla JS, or next() in jQuery
$('.toggle').on('click', function(event) {
$(this).next('.EditData').toggleClass('invisible');
let text = $(this).parent().find('.TextData').toggleClass('invisible');
let newText = $(this).text() === 'Åben Redigering >>' ? '<< Luk Redigering' : 'Åben Redigering >>';
$(this).text(newText);
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="EditButton1" class="toggle btn btn-success" data-text-swap="<< Luk Redigering">Åben Redigering >></button>
<div class="EditData invisible">
<div class="input-group">
<input type="text" class="form-control" placeholder="Some Name" aria-label="Recipient's username" aria-describedby="basic-addon2" style="width: 100px;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button"><i class="far fa-save"></i></button>
</div>
</div>
</div>
<div class="TextData">
Some more info should appear here below
</div>
</div>
If you do it this way, you're relying on the structure of your template. You don't need to use a dynamic id to do a query each time as long as you put your button that triggers the toggle in the same position relative to one another with the same class names, this should work. Let me know if I misunderstood what you were trying to do there and I can edit my answer :)
I'm trying to toggle the class of this on click, I tried this but it doesn't seem to work. Any ideas? I have included some HTML now so that it is more easily understood what is going on.
$('.play-with-friends').on('click', function(){
$('.flipper', this).toggleClass('flipped');
});
HTML:
<div class="flipper">
<div class="row game-cards">
<div class="container col-lg-6">
<canvas id="game-circles"></canvas>
</div>
<div class="col-lg-6 game-info">
<h6 class="text-center">{{AwayTeam}} # {{HomeTeam}}</h6>
<p class="text-center">{{MatchTime}}</p>
<form>
<div class="form-group text-center">
<label for="home-team">{{HomeTeam}} -2.5</label>
<input type="number" class="form-control text-center" placeholder="Home Team Bet">
</div>
<div class="form-group text-center">
<label for="away-team">{{AwayTeam}}</label>
<input type="number" class="form-control text-center" placeholder="Away Team Bet">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
<button type="button" class="btn btn-secondary btn-block play-with-friends">Play With Friends</button>
</form>
</div>
</div>
</div>
So please change your code to select .flipper:
$('.play-with-friends').on('click', function(){
$('.flipper').toggleClass('flipped');
});
When you do $('.some-class', elem) you're saying you want to target .some-class that's a child of elem. That's not what your HTML is showing – you actually have .flipper way above at the top level. How about using a different method, like closest, which will find an ancestor with the selector you specify:
$('.play-with-friends').on('click', function() {
$(this).closest('.flipper').toggleClass('flipped');
});
I have a piece of HTML that looks like this
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
Above that I have a button that looks like this
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
Once that button is pressed I run a function to get the #imageContent div and append a new row with the same as before.
<script type="text/javascript">
function add_fields() {
var div = document.getElementById("imageContent");
div.insertAdjacentHTML('afterend','<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
</script>
This works as expected and adds a new row into the imageContent div.
See picture. If I click Select Image, it launches a modal window with all of my images, and when I select one, it runs this piece of js.
onInsertCallback: function (obj){
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
}
The problem I am having is that it does not get the correct input area to insert the value into, and instead always updates the first element. The full js code looks like this.
$(document).ready(function() {
jQuery(document).ready(function() {
/** Keep track of which modal button was clicked. **/
var currentModalBtn;
jQuery('.modal-btn').click(function() {
currentModalBtn = jQuery(this);
});
jQuery('.laradrop').laradrop({
onInsertCallback: function(obj) {
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
},
onErrorCallback: function(jqXHR, textStatus, errorThrown) {
// if you need an error status indicator, implement here
//Swal here
swal({
title: 'Error!',
text: 'An Error Occurred',
type: 'error',
showConfirmButton: false,
showCancelButton: true
});
},
onSuccessCallback: function(serverData) {
//
}
});
});
});
My question is, how can I ensure that I get the right input field that the button was clicked on to update that fields value and make sure the others stay as they were.
move var currentModalBtn; outside the ready so it is available to the callback(s)
Also have only one
$(document).ready(function() {
jQuery(document).ready(function() {
you have a mess of jQuery/$ and so on - this will likely work better:
function add_fields() {
var $div = $("#imageContent");
$div.append('<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
var currentModalBtn;
$(function() {
/** Keep track of which modal button was clicked. **/
$("#imageContent").on("click",".modal-btn", function() {
currentModalBtn = $(this);
});
$("#test").on("click",function() {
currentModalBtn.closest('.input-group').find('input.file-src').val("hello");
$('#myModal').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
<button type="button" id="test">
click
</button>
I making a "to do list" of task to be done. I have some buttons that will move the tasks up and down on the list.
I go the up and down buttons going. My only issue is that the task divs are able to move up and down the entire page. How can I keep the task divs to only moving up and down on on each other?
Thank you!
Here's my code:
$(document).ready(function(){
$('.up_button').click(function(){
$(this).parents('.task').insertBefore($(this).parents('.task').prev());
});
$('.down_button').click(function(){
$(this).parents('.task').insertAfter($(this).parents('.task').next());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="task col-sm-12">
<div class="col-md-6">
<div class="input-group">
<span class="input-group-addon"><input type="checkbox" name="task1" value="taskID1" /></span> <input type="text" class="form-control" value="Write HTML" readonly>
</div>
</div>
<div class="col-md-6">
<button type="button" class="btn btn-default up_button"><span class="glyphicon glyphicon-arrow-up"></span> Move Up</button>
<button type="button" class="btn btn-default down_button"><span class="glyphicon glyphicon-arrow-down"></span> Move Down</button>
</div>
</div>
<div class="task col-sm-12">
<div class="col-md-6">
<div class="input-group">
<span class="input-group-addon"><input type="checkbox" name="task1" value="taskID1" /></span> <input type="text" class="form-control" value="Write XML" readonly>
</div>
</div>
<div class="col-md-6">
<button type="button" class="btn btn-default up_button"><span class="glyphicon glyphicon-arrow-up"></span> Move Up</button>
<button type="button" class="btn btn-default down_button"><span class="glyphicon glyphicon-arrow-down"></span> Move Down</button>
</div>
</div>
1st: I think you need to define $(this) before going to insertAfter or insertBefore
2nd: you can use .closest()
$(document).ready(function(){
$('.up_button').click(function(){
var ThisIt = $(this);
$(this).closest('.task').insertBefore(ThisIt.closest('.task').prev('.task'));
});
$('.down_button').click(function(){
var ThisIt = $(this);
ThisIt.closest('.task').insertAfter(ThisIt.closest('.task').next('.task'));
});
});
Demo Here