I fetch posts from database with php while loop, Here is the e.g of HTML code->
<div id="1"> content <button class="btn-primary" data-id="1">button</button></div>
<div id="2">content 2 <button class="btn-primary" data-id="2">button</button></div>
if someone click on first button then div with id=1 should be removed
Here is the jquery code
$(function() {
$("body").on("click", ".btn-primary", function() {
var ids = $(this).data('id'); // get data-id atrribute
var elements = this;
$('#id').remove(); // How can i remove the div by showing each id here
$.ajax({
type: "POST",
url: "https://www.example.com/ajax,
data: "ids=" + ids,
success: function(data) {
setTimeout(function() {
$('.conner').append(data).fadeIn('slow');
}, 2000);
}
});
});
});
How can Get div id dynamically and remove the div on click
Unless data-id holds several values you can:
var ids = $(this).data('id'); // get data-id atrribute
$('#' + ids).remove();
More simple way - is to remove a button parent:
$( this ).parent().remove();
Either use the variable like :
$('#'+ids).remove();
Or you can simply go with
$(this).parent().remove();
If your container is always div you don't need to use ids you could just use :
$(this).closest('div').remove();
Hope this helps.
sometimes it happend that if id of an element contains only number and we try to access that element with that id its creating problem soe better to use
$(this).parent().remove();
If div which you want to delete is immediate parent of button than you can use,
$(this).parent().remove();
If you have hierarchy than you can add .parent() multiple time like
$(this).parent().parent().parent().remove();
Is it something like this ??
Codepen example
$(".button1").click(function() {
$(this).closest('.div1').fadeOut(500);
});
HTML
<div class="div1">content1
<button class="btn-primary button1">button for div 1</button>
</div>
<div class="div1">content2
<button class="btn-primary button1">button for div 2</button>
</div>
<div class="div1">content3
<button class="btn-primary button1">button for div 3</button>
</div>
<div class="div1">content4
<button class="btn-primary button1">button for div 4</button>
</div>
<div class="div1">content5
<button class="btn-primary button1">button for div 5</button>
</div>
Related
I am trying to hide all elements when one button is clicked and only the menu belonging to that specific button should appear.
If I do like this that will be too long if more buttons and menus are there.
Are there any methods that can shorten this and get the desired result?
$(document).ready(function(){
$("#steps").click(function(){
$("#calculateMenu").hide();
$("#stepsMenu").show();
});
$("#calculate").click(function(){
$("#stepsMenu").hide();
$("#calculateMenu").show();
});
});
You could do it like this:
$("#steps,#calculate").click(function() {
var id = $(this).attr("id");
$("[id*=Menu]").hide();
$("#" + id + "Menu").show();
});
All element where id contains Menu will be hidden, and then we will show the "correct" element
Demo
$("#steps,#calculate").click(function() {
var id = $(this).attr("id");
$("[id*=Menu]").hide();
$("#" + id + "Menu").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="steps">steps</button>
<button id="calculate">calculate</button>
<div id="stepsMenu">stepsMenu</div>
<div id="calculateMenu">calculateMenu</div>
When one button is clicked and the only menu belonging to that specific
button should appear
As #freedomn-m 's comment,
You can use data-attributes to link between button and menu combined with class selector like below:
$(".Mybutton").click(function() {
var activeMenu = $(this).data('buttonname');
$(".menu").hide();
$("#" + activeMenu).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='Mybutton' data-buttonname='steps'>steps</button>
<button class='Mybutton' data-buttonname='calculate'>calculate</button>
<button class='Mybutton' data-buttonname='finish'>finish</button>
<div class='menu' id="steps">stepsMenu</div>
<div class='menu' id="calculate">calculateMenu</div>
<div class='menu' id="finish">finishMenu</div>
I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});
I need some help. As you will see in my fiddle, I am attempting to use buttons to populate a single container div with content from multiple hidden divs, depending on which button is clicked. The problem I am having is, I don't know how to access the actual content in the hidden divs to populate the container div. As of now, I am using the id attributes for the hidden divs to demonstrate which div content I would like to display in the container.
I've seen a few other posts with link <a> attributes referencing hidden content, but none so far using a button element with click functionality to change div content.
jQuery(function ($) {
$('#button1').click(function () {
$('#info').empty();
$('#info').prepend('#option1');
});
$('#button2').click(function () {
$('#info').empty();
$('#info').prepend('#option2');
});
$('#button3').click(function () {
$('#info').empty();
$('#info').prepend('#option3');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1">Button 1</button></li>
<li class="buttons"><button id="button2">Button 2</button></li>
<li class="buttons"><button id="button3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
Here is my fiddle
Here's a version that uses jquery data attributes. It reduces the redundancy and complexity and can be configured easily.
<body>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1" data-link="option1">Button 1</button></li>
<li class="buttons"><button id="button2" data-link="option2">Button 2</button></li>
<li class="buttons"><button id="button3" data-link="option3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info">
</div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
</body>
<script>
$('.buttons button').click(function (){
$('#info').empty();
$('#info').html($("#" + $(this).data('link')).html());
});
</script>
Example : https://jsfiddle.net/yvsu6qfw/3/
It sounds like maybe you were looking for using the button itself to populate data built into the button with a data attribute or something? If so you can do something like this:
HTML
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button data-info="Box">Button 1</button></li>
<li class="buttons"><button data-info="Google Drive">Button 2</button></li>
<li class="buttons"><button data-info="Box">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
jQuery
$(document).ready(function (){
$('#button-column button').click(function (){
$('#info').html($(this).attr('data-info'));
});
});
If you want the first button to load the content from the first hidden div etc. without relying upon using the id attributes, you can use the .index() method. When you pass this as an argument it will return the index value of the click event target in the collection $("#button-column .buttons :button"). Afterwards you can pass the index value to the .get() method to retrieve the corresponding element from the collection of hidden divs $("#hiddenDivs .info").
$().ready(function(){
$("#button-column .buttons :button").on("click", function(){
$('#info').empty();
var clickedIndex = $("#button-column .buttons :button").index(this);
var hiddenInfo = $("#hiddenDivs .info").get(clickedIndex);
$('#info').prepend( $(hiddenInfo).text() );
});
});
you can use html function, without parameter gets the content of the element
with parameter replaces the content with the string parameter
$(document).ready(function (){
$('#button1').click(function (){
$('#info').html( $('#option1').html() );
});
$('#button2').click(function (){
$('#info').html( $('#option2').html() );
});
$('#button3').click(function (){
$('#info').html( $('#option3').html() );
});
});
In your code example, you do for example:
$('#info').prepend('#option1');
What you instruct to do here, is adding a text string '#option1' to an element with ID info.
What you intend to do is prepending the content of ID option1 to the element with ID info. You could do something like this instead:
$('#info').prepend($('#option1').html());
Another approach could be (but I don't know if that's relevant for you) to not clone content (since it costs you repaints) but toggle the specific elements instead. For example:
$('#option1,#option2').hide();
$('#option3').hide();
And yet another one: use data-attributes on your buttons:
Button 1
Button 2
<div id="info">
</div>
And the JS:
$('.button').on('click', function(event) {
event.preventDefault();
$('#info').html($(event.currentTarget).attr('data-text'));
});
Don't repeat yourself! To get the number out of an ID replace with "" all that is not a number using RegExp \D.
Using number from ID
Than, to get the actual content you can use $("#option"+ num).html() or $("#option"+ num).text() methods:
jsFiddle demo
jQuery(function ($) {
$('.buttons button').click(function () {
var num = this.id.replace(/\D/g,"");
$("#info").html( $("#option"+ num).html() );
});
});
Target element using data-* attribute
Alternatively you can store inside a data-* attribute the desired target selector ID:
<button data-content="#option1" id="button1">Button 1</button>
and than simply:
jsFiddle demo
jQuery(function ($) {
$("[data-content]").click(function () {
$("#info").html( $(this.dataset.content).html() );
});
});
http://api.jquery.com/html/
http://api.jquery.com/text/
If the expectation is to get same indexed hidden div content, Then the below code should work.
$(document).ready(function (){
$('.buttons button').click(function (){
$('#info').empty();
var index = $('.buttons button').index($(this));
$('#info').html($('.info:eq('+index+')').html());
});
});
Let's say I have a template and I want to loop and create div's. I want to listen to clicks on the buttons contained in each of these divs:
<div class="repeatedDiv">
<button class="reply-button">
</div>
$('.reply-button').on('click',function(e)...)
I want to make the reply button function specific to the div that it was selected on. Would it be bad to have something like:
<div class="repeatedDiv">
<button class="reply-button" id="reply-{{this.id}}">
</div>
Don't make it more complicated than it really is
$(document).on('click', '.reply-button', function(e){
var divClicked = $(e.target).closest('.repeatedDiv');
// do something with clicked div
// var divClicked is the div elmt that contains the button that was clicked
// doing it this way you might not even need an id at all
console.log(divClicked.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="repeatedDiv">
<button class="reply-button">div1</button>
</div>
<div id="div2" class="repeatedDiv">
<button class="reply-button">div2</button>
</div>
<div id="div3" class="repeatedDiv">
<button class="reply-button">div3</button>
</div>
And if you do need an id when creating a new div create it dynamically with e.g.
var newID = "id-" + Date.now();
console.log(newID);
I am trying to convert a lot of JavaScript to jQuery and I have a task that I believe has a simple jQuery shortcut, but I don't know what it is and I haven't been able to find an example.
I have a page with many toggled divs. They are in the form that follows where ### is a unique integer for each pair.
<button class='togglebutton' onclick="toggle('div###');">+</button>
<div id='div###'>...some text...</div>
I'd assume the shortcut is something like:
$('.togglebutton').onclick(function() {
var divid = '#div'+?????;
$(divid).toggle();
});
My theory... if I give each button an id, such as 'button###', then I can use substring to get the value after the word 'button', something like:
$(this).id().substring(6,3);
Obviously, that didn't work. So, I figured that I should ask if there is a simple shortcut in jQuery to pair a showhide button with a separate div.
You may want to do this no matter where your div locates http://jsfiddle.net/tg5op333/25/
HTML
<button class='togglebutton' data-id="1">+</button>
<div id='1' style="display:none">...some text...</div>
<button class='togglebutton' data-id="2">+</button>
<div id='2' style="display:none">...some text...</div>
<button class='togglebutton' data-id="3">+</button>
<div id='3' style="display:none">...some text...</div>
<button class='togglebutton' data-id="4">+</button>
<div id='4' style="display:none">...some text...</div>
JS:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
If the HTML is ordered like you show in your question, then use:
$('.togglebutton').click(function() {
$(this).next().toggle();
});
$('.togglebutton').click(function() {
$(this).next().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class='togglebutton'>+</button>
<div id='div1'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div2'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div3'>...some text...</div>
Two ways:
1) You can use some common class attribute to all dives and select all using that.
Or
2) Or else you can use this wildcard selector :
$("[id^=div]")
It gives you all divs whose id starts with div.