Unable to find the specific items value jQuery - javascript

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);
});

Related

Remove input by clicking times icon

I have the following code which adds divs within a container (#subtask_container) via clicking a link (similar to Google Tasks):
HTML:
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
JS (this successfully adds unique inputs within the subtask container div along with a clickable x after each input)
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted"></i><br>');
i++;
});
What logic do I need to add to the x class to remove it's associated input?
I've tried
$('.fa-times').click(function(){
$(this).prev('input').remove();
});
but it doesn't seem to work...
Thanks!
You can simply wrap your subtask append in a div and simply use .parent() and .remove() function on that. No need to use <br>
Also, do not use .fa-times as primary click event handler as you might have other fa-times on the same page as well Which might cause issues later on. Add a custom class to your fa item (.subtask_remove_icon)
Live Demo:
var i = 1
$("#add_subtask").click(function() {
$("#subtask_container").append('<div><input name="subtask' + i + '" class="mt-1" id="subtask' + i + '" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted subtask_remove_icon"></i></div>');
i++;
});
$(document).on('click', '.subtask_remove_icon', function() {
$(this).parent().remove(); //remove the input when X clicked
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
The event handler gets attached to all elements that are on the page load. Since the icons are appended, the right way to do this would be the following:
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<div><input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted removeIcon"></i><br></div>');
i++;
});
$(document).on('click', '.removeIcon', function(){
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>

How to select unique div id & remove it

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>

Hide/Show many elements on single click by jQuery

I've code few line of jQuery for Hide/Show many elements on single click and it's working. But problem is; i've many more image class items, so my script going to long, my question is how to simplify or make short my script, i mean any alternatives or any new idea? please suggest.
HTML:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- many many images -->
</span>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
JS: live demo >
$("button.red").click(function(){
$(".images-red").show();
$(".images-blue, .images-pink").hide();
});
$("button.blue").click(function(){
$(".images-red, .images-pink").hide();
$(".images-blue").show();
});
$("button.pink").click(function(){
$(".images-red, .images-blue").hide();
$(".images-pink").show();
});
Please suggest for short and simple code of my script. Thanks.
You can do it by adding just a common class to those buttons,
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().eq($(this).index("button.button")).show();
});
The concept behind the code is to bind click event for the buttons by using the common class. Now inside the event handler, hide all the i elements which has been cached already and show the one which has the same index as clicked button.
DEMO
For more details : .eq() and .index(selector)
And if your elements order are not same, both the i and button's. Then you can use the dataset feature of javascript to over come that issue.
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().filter(".images-" + this.dataset.class).show()
});
For implementing this you have to add data attribute to your buttons like,
<button data-class="red" class="button red">Red</button>
DEMO
This works
$("#choose-color button").click(function(){
var _class = $(this).attr('class');
$("#choose-color i").hide();
$(".images-"+_class).show();
});
https://jsfiddle.net/455k1hhh/5/
I know this might not be the prettiest solution, but it should do the job.
$("button").click(function(){
var classname = $(this).attr('class');
$("#choose-color span i").hide();
$(".images-"+classname).show();
});
You're making future extensibility a little difficult this way due to relying on class names but this would solve your immediate need:
<div id="myImages">
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</div>
<div id="myButtons">
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
$("#myButtons button").click(function(){
var color = $(this).attr("class");
var imageClass = ".images-"+color;
$('#myImages').children("i").each(function () {
$(this).hide();
});
$(imageClass).show();
});
Here's a JSFiddle
Edit: Note how I wrapped the buttons and images in parent divs to allow you to isolate just the buttons/images you want to work with.
You can do the following using data-* attributes, because when you have more elements of the same color, using index of the button won't work. And simply using the whole class attribute won't work if you have to add more classes to the button in future.
$("button").click(function() {
var color = $(this).data('color');
var targets = $('.images-' + color);
targets.show();
$("span i").not(targets).hide();
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<br/>
<div id="choose-color">
<span>
<i class="images-red">Red Image</i>
<i class="images-blue hidden">Blue Image</i>
<i class="images-pink hidden">Pink Image</i>
<!-- Many many image -->
</span>
<br/>
<br/>
<button data-color="red">Red</button>
<button data-color="blue">Blue</button>
<button data-color="pink">Pink</button>
</div>
It would make sense to have all images share a single class (.image for example). Then you just use a shared class for the button and the image; in this example I used the color name. Now, when any button is clicked, you can grab the class name of the image you want to show.
Give this a try:
$("button").click(function(){
$(".image").hide();
var className = $(this).attr("class");
$("." + className).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/><br/>
<div id="choose-color">
<span>
<i class="image red" style="">Red Image</i>
<i class="image blue" style="display: none;">Blue Image</i>
<i class="image pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</span>
<br/><br/>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
You may try this:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many image -->
</span>
<br/><br/>
<button class="colour red" onclick="myFunction(this)">Red</button>
<button class="colour blue" onclick="myFunction(this)">Blue</button>
<button class="colour pink" onclick="myFunction(this)">Pink</button>
</div>
JS: see here
$(".colour").click(function(){
var colors = ["red", "blue", "pink"];
for (i = 0; i < colors.length; i++) {
if($(this).hasClass(colors[i])){
$(".images-"+colors[i]).show();
}else{
$(".images-"+colors[i]).hide();
}
}
});

Get HTML DOM elements inside a javascript function

I am trying to implement something like this. IF you click the button it would get the HTML of the above elements and insert them in an alert :
<div id="0001">
<h5 class="title">Hello World </h5>
<h4 class="date">2014-07-19 </h4>
<button onclick="addCalendar('#0001. #title','#0001. #date')"> Add to Calendar </button>
</div>
<div id="0002">
<h5 class="title">Bye Bye</h5>
<h4 class="date">2014-07-22 </h4>
<button onclick="addCalendar('#0002. #title','#0002. #date')"> Add to Calendar </button>
</div>
<script>
function addCalendar(title,date){
alert(title + ": " + date);
}
</script>
This code should works..
If you want to get the value of that HTML:
$("button").click(function(){
var value = $(this).siblings("#title").text();
value += $(this).siblings("#date").text();
alert(value);
});
If you want to get the HTML tags too:
$("button").click(function(){
var value = $(this).siblings("#title").html();
value += $(this).siblings("#date").html();
alert(value);
});

How to add repetitive div with jQuery?

When I click on the new button with jQuery it adds the div, but it only adds one. When I check from DevTools it constantly creates the same place. But I want it to add another one after that. Can you help me?
HTML code
<div class="text-left" style="margin-bottom: 15px;">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone"></div>
Here are the sample js codes
$('.add-extra-email-button').click(function() {
var element = $('.clone');
element.html(
'<div class="clone_edilen_email">' +
'<li>' +
'<a href="javascript:;"> Test' +
'<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' +
'</a>' +
'</li>' +
'</div>'
);
$('.clone_edilen_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
$(document).on('click', '.remove-field-email', function(e) {
$(this).parent('.btn-delete-branch-email').parent('.remove-email').remove();
e.preventDefault();
});
If I understand correctly, you want to add the <div class="clone_edilen_email"> again and again, as soon somebody clicks on the .add-extra-email-button button.
In general, calling element.html('<some_wild_html></some_wild_html>') will always override the full inner content of element with <some_wild_html></some_wild_html>. Also, if the element already contains some other sub-elements, they will got lost. In your given code example, I assume, your intention was to extend the element's html and not replace it.
Here is my suggestion:
$('.add-extra-email-button').click(function() {
var newDiv = $('<div class="clone_edilen_mail"></div>');
newDiv.html('<li><a href="javascript:;"> Test<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></li>');
$('.clone').append(newDiv); // This is the important clue here!
// afterwards you may insert your residual class stuff
// $('.clone_edilen_email').addClass('single-email remove-email'); <- I would suggest you add these classes already at the begining, where I set the variable "newDiv"
// ...
// $('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
// $('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
// .. your other code may follow here ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clone">I am a clone-div!</div>
<button class="add-extra-email-button">Click Me!</button>
Hope that this might help you!
Try This Method, Append Duplicate Elements and Contents Using jQuery .clone() Method
<!doctype html>
<html>
<head>
<title>jQuery Clone() – Add Elements and its Contents</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
div {
margin:3px;
padding:3px;
border:solid 1px #999;
width:300px;
}
</style>
</head>
<body>
<p>Click the button to clone (make a duplicate) of the DIV element!</p>
<div id="Container">Hello, how was your day!</div>
<p><input type="button" id="Button1" value="Clone it" /></p>
</body>
<script>
$(document).ready(function () {
$('#Button1').on('click', function () {
$('#Container')
.clone()
.appendTo("body");
});
});
</script>
</html>
In your first click function you replace all the content of your div clone so even if you click again you are going to have only one. He is just replacing the old one.
I didn't get what you are trying to do with the second click function.

Categories