Finding child from parent of clicked element - javascript

I'm currently building an event table that will feature a "share" button. Once the user clicks on the share button I want to find text value from that particular table and store them in a variable so that I can use them in my next step. Basicly when I click the share button I want to find the parent element that wraps the particular table and then find text values from each particular cell and store that in a variable. In my JSFiddle I have setup to display the results in the resultbox. http://jsfiddle.net/Ak84L/5/
$("#shareButt").click(function(){
var date = $(this).parent('.even_table').find('date').text();
$(".resultbox").text("date"+date);
});

First change shareButt and date to values of class attribute instead of id, because IDs have to be unique.
And use this code:
$(".shareButt").click(function () {
var date = $(this).closest('.event_table').find('.date').text();
$(".resultbox").text("date" + date);
});
DEMO

First DON'T use same id. Use class instead. Go this way:
js
$(".shareButt").click(function(){
var date = $(this).parents(".event_table").find(".date").text();
$(".resultbox").text("date"+date);
});
fiddle

it would be much simpler to append a custom data tag to the element than to muck around with artsy fartsy jquery calls.
If its good enough for major web frameworks like angular.js, jade, bootstrap, etc. why do many people continue to attempt to reinvent the wheel to create the most complicated solution.
JS FIDDLE EXAMPLE
HTML
<div class="shareButt" date-data="12.5.2014">SHARE</div></td>
jQuery
$(".shareButt").click(function(){
$('.resultbox').text('date' + $(this).attr('date-data'));
});

Related

Button not disappearing on multiple views using common div id in jQuery

I am working on a .NET MVC application. I have added a button using jQuery using the following code:
var button_to_add = '<div id = "csv_button"><nav>CSV</nav></div>'
$("#titleDiv").append(button_to_add);
The problem is multiple views are using the "titleDiv" and each view is rendered through javascript. As a result, the button is appearing on all the views. The view slides in when another link is clicked. I could remove the button using:
$("#csv_button").remove();
But I am not sure how and when to call it so that the button disappears when the view slides off.
Edit: I am looking for a javascript call that will detect when the view starts sliding so that the button can be removed at that moment.
As you are saying titleDiv is use for multiple view then use it as a class rather than an id.
And you should have unique id's for each element if at all you are using id's.
so your expression will become:
var button_to_add = '<div id = "csv_button"><nav>CSV</nav></div>'
$(".titleDiv").append(button_to_add);
IDs in HTML cannot be reused. The browsers will accept it, but you jQuery will only look at the first one.
Use a distinct ID to allow for clean, single append.

Creating an ID for a Form Variable (or Changing it) Using Javascript or JQuery

I am receiving an XML data form result and using the Strophe library to convert it into html.
This gives me a chunk of HTML (form) as a variable, which I can then append to a page:
var iqHtml = iqForm.toHTML();
$("#form-result-div").append(iqHtml);
The issue is that the form which it attaches has no id, action, or anything to identify it:
<form data-type="result">
...
I have two possibilities here.
Option 1. (preferred method)
Is it possible to change the variable iqHtml, which is just raw HTML, and an ID to it? Ideally this would be done before it is appended to the page.
I've tried multiple ways to find the form tag and add the attribute using .find() and .attr() but with no success.
Option 2. (less preferable)
I can edit the library to add a random ID (say id="some-id") which I will then need to EDIT rather than creating new.
This editing will have the questions as Option 1 - how do I search the variable and then change the form's ID.
Thank you.
Kind Regards,
Gary Shergill
You could assign an id before appending it
$(iqHtml).attr('id', 'someid').appendTo("#form-result-div");
Edited: id needs to be in ''
This should work:
var iqHtml = "<form><input type='text' /></form>";
$("#form-result-div").append(iqHtml).find("form").attr("id", "myForm");
Demo: http://jsfiddle.net/AA8Cf/
You can also play with one of the child selectors to pick up a specific one, if there is more than one form.
http://api.jquery.com/category/selectors/child-filter-selectors/

check if jquery ui accordion exists?

is there an easy way to tell if a jquery accordion exists on the page...i am trying to dynamically build accordion based on selection that runs through $ajax, reads values from xml, and depending on the xml file selected builds strings the make up the accordion, and finally appends it.
I think that if the accordion already exists on the page, and the user selects another file, I am having trouble destroying the accordion, clearing the html, append the new string, then creating a new accordion...
like
$("#accordion").accordion('destory').html('').append(string).accordion();
seems like if there is not already an accordion this idea breaks....thinking maybe i can just check?? thanks for any help to beginner!
I suspect that you could try checking .data().
var isAccordion = !!$("#accordion").data("ui-accordion");
Or, by checking the ui-accordion classname using .hasClass() which is added upon initialization.
var isAccordion = $("#accordion").hasClass("ui-accordion");
You could try with .length
Count the element using .length
Or something like this
if($('#accordion').length > 0) {
// do something
}

create a new instance of group of elements

I am beginner in jQuery and asp.net. I created a simple chat application using SignalR, the design of which you can find here fiddle
How can I create a new instance of that chat design whenever a user has been call by other user while he/she were in chat from before with other user. Here I think I can convert it to User Control. but I dont want to have same Id's which I am using for other chat design and those generated instances should work differently, I mean if userA calls userB and at the same time userC calls userB then they must be created in such a way that they must be unique in handling there own calls (just like FB Chat).
The another issue may arise after successfully creating a new instance is that they might not be get attached to the jQuery functions and server side code automatically. If so, anyway to solve this too?
Before asking here I searched alot (maybe I dont know the exact keyword to search for).
EDIT: Many jQuery developers suggested me to go with Knockout.js or Backbone.js or simple jQuery. But I think there is some simple way to achieve this using ASP.NET functions like User Control or HTTP Handlers (or something else). About which I dont know anything. So, please suggest me which concept to opt for ? and please give detailed explanation(if possible with simple example).
jquery related answers are also welcome.
Single Instance
Multiple Instances
Use JQuery to populate or popup new instance of chat but change your ids using jquery. I would suggest have all your styling and ids done according to a parent container so you can easily grap the parent, duplicate it and change the IDs or content.
I would keep a non filled chat window with ID's like "updateme1" updateme2 etc and then once i get it as a template i will replace all ids one by one with relevant content.
You are doing it right and i dont think its signalR that you need to look into. SignalR would be able to help you pass on specific parameters like "requirechatwindow=true or false" based on if this person is in chat with current person but you can always do this on client as well by going through current open chat sessions. If current chat session does not contain a chat between A and B then open new window with new ID and put a data-from= A and data-to=B as a palceholder so you know this chat is between A and B etc
Hope this helps
UPDATED Fiddle and technique
Here is the fix on Your fiddle edited to show creation and multiple ids I had to adjust some of your css to view the boxes in different location
Updated the code with some comments
The technique is simple:
You create a html template on your page might be in a hidden region
You then use that to create new element in a container and have a handle to pickup this element for example in my code the currentid is my handle but i know the container name so i will only pickup template populated within the actual container to avoid conflict with template itself.
Assign a new id and then you can use any events or any speacial objects on there.
You can then pickup new elements from the new id or any other handle you might have inside them. For example i have just added a click even on it with confirm to hide it.
$('#doubleme').click(function(){
var currentid = $("#chattemplate .chat-outline").attr('data-tid');
var newid = parseInt(currentid,10) + 1;
$("#chatcontainers").append($("#chattemplate").html());
$("#chatcontainers .chat-outline").attr('id',"id"+newid);
$("#chattemplate .chat-outline").attr('data-tid',newid);
});
You only need these five lines of code actually and if you go to fiddle i have commented all of them but they are easy to understand. I am using selectors used in fiddle but these can be further optimised with attributes like data-handle-for or whatever name you can give.
If you are considering this for SignalR then within your hub response of new request you can call the intiate chat window which can setup everything on the client. Any subsequent messages using that data handle can be updated within this new chat window.
For example i assume you create a new group called "chatwindow7" and "chatwindow8" which makes its round trip in your send method and so on get broadcast to only user with this group. Then each user might have multiple windows open but you only need to pickup chatwindow7 for messages with that data handle and update it and so on.
If you are using one-to-one chat users only then you can use connection id as well which means all messages broadcasted will have both sender and reciever (by deafault) connection ID and you only need to pickup the window with connection id handle and update its list of messages or whatever.
The simplest way to do this is to replace the id attributes with class attributes.
<div id="chat-outline">
...
</div>
becomes
<div class="chat-outline">
...
</div>
And update your CSS appropriately.
.chat-outline
{
background-color: gray;
....
}
Then use a text/template tag to make it available to jQuery.
<script type="text/template" id="chat-template">
<div class="chat-outline">
...
</div>
</script>
Note that because browsers ignore script types they don't recognise, this will be ignored by the html rendering engine, but as it has an id, it will be visible to jQuery, and can be accessed thus:
<div id="container">
</div>
<script type="text/javascript">
$(function() {
var chatTemplate = $('#chat-template').html();
$('#container').append(chatTemplate); // First instance
$('#container').append(chatTemplate); // Second instance
$('#container').append(chatTemplate); // Third instance
});
</script>
Of course, if your code needs an id attribute as a handle for a chat instance, you can create a function that creates the chat-instance html given an id. In this case I'll use underscore to provide random-id, template, and iteration functions, but it is easy to use another library, or write your own.
<div id="container">
</div>
<script type="text/template" id="chat-template">
<div class="chat-outline" id="<%= id %>">
...
</div>
</script>
<script type="text/javascript">
var createChatInstance(idstring) {
return _.template($('#chat-template').html(), { id: idstring });
}
$(function() {
var chatTemplate = $('#chat-template').html();
// Create an array of 3 unique ids by which chat instances will be accessed.
var chatIds = [_.uniqueId('chat-outline'),
_.uniqueId('chat-outline'),
_.uniqueId('chat-outline')];
_.each(chatIds, function(chatId) {
$('#container').append(createChatInstance(chatId));
});
// You now have an array of 3 unique ids matching 3 divs.
// You can access individual sub-divs via descendent class matching from the id
// thus: $('#' + chatIds[n] + ' .chat-message').keyup(...code handling event...);
});
</script>
At this point, if you want to take the architecture further, you really do need to consider investigating something like backbone.js.
Hope this helps.

Whats make different in below Jquery code?

I'm working with on developing one of the social networking site and its having some notification features in left panel.
Whenever any user have played a game it will automatically change the number of notification count.
For that i have using below code line.
jQuery('#count_id').load('mypage.php');
But it will retrieve me whole site content with header,footer and content area in the response text, which is wrong as per my requirements.
but if i used below code of line
jQuery('#count_id').load('mypage.php #count_id');
then it will retrieve me a real count but add another div in between the original,
Original html:
<div id="count_id" class="notify">2</div>
and Code after retrieving response:
<div id="count_id" class="notify">
<div id="count_id" class="notify">1</div>
</div>
which is also not as expected. count are right but i don't want to add new div inside a original one.
What should i need to change in my code?
Thanks.
jQuery('#count_id').load('mypage.php #count_id > *');
That would bring only the DOM childs (the content)
Because this is how it works. Also it enables you to attach events to the element you load and delegate them inside this element (so new elements can also benefit from attached JavaScript events) - see .delegate().
If you want to replace the element, you can try the following:
jQuery.get('mypage.php', function(data){
jQuery('#count_id').replace(jQuery(data).find('#count_id'));
}, 'html');
I did not test it, but it should work.
Ivan Castellanos is however right. According to the documentation, you can provide any selector after the first space in the .load()'s parameter.
To retrieve count_id, you can directly get the html value in the div like this:
<script type='text/javascript'>
jQuery(document).ready(function()
{
countVal = $("#count_id").html(); //returns the html content inside the div, which is the count value
countVal = parseInt(countVal); //This will convert the string to type integer
});
</script>
Note:
If you want increase the count and update the div value, you can add the following lines:
countVal++;
$("#count_id").html(countVal);

Categories