Get the title of a selectable item in jQuery - javascript

I have a list of selectable buttons, whose names are being dynamically generated by reading from a JSON file. Every time a button is clicked, I want the get its title, i.e. row["name"]. Here's my relevant code and the JSON:
<head>
<script>
$.getJSON("json-data.txt",function(data){
var items = [];
$.each(data['data'],function(i, row){
items.push("<li class = 'ui-widget-content'>" + row["name"] + "</li>");
});
$("<ol/>",{
"id" : "selectable",
html : items.join("")
}).appendTo("body");
});
var selectableObj = {
selected: function(event, ui){
}
}
$(function() {
$( "#selectable" ).selectable(selectableObj);
});
</script>
</head>
<body>
</body>
The JSON data:
{
"data": [
{
"name": "ABC",
"visited" : "Yes"
},
{
"name": "DEF",
"visited" : "Yes"
},
{
"name": "GHI",
"locked": "No"
},
],
}
This works, in that I get a list of selectables in the format:
<ol id="selectable">
<li class="ui-widget-content">ABC</li>
<li class="ui-widget-content">DEF</li>
<li class="ui-widget-content">GHI</li>
</ol>
When I click on, say, the first button, I want to get the value "ABC". I don't know how to do this. I read about .text(), but cannot understand to use it. Can anyone help please?
EDIT - Based on some comments, I changed my code like this, but it doesn't work:
<script>
$(function() {
$( "#selectable" ).selectable();
});
$.getJSON("json-data.txt",function(data){
var items = [];
$.each(data['data'],function(i, row){
items.push("<li class = 'ui-widget-content'>" + row["name"] + "</li>");
});
$("<ol/>",{
"id" : "selectable",
html : items.join("")
}).appendTo("body");
});
$('.ui-widget-content').click(function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});
</script>

I think this is what you looking for
selected: function() {
$( ".ui-selected", this ).each(function() {
alert($(this).text());
});
}
});
DEMO

$('#selectable').on('click', 'li', function(evt){
var text = $(this).text();
console.log(text);
});
The explanation is of how this works is that it attaches a click event to the parent of the list item, which is #selectable in the code you provided. Binding an event to the parent element attaches one event to the DOM in total instead of attaching an event for every list item, so it is very efficient. This concept is known as event delegation.
The function that appears inside of on() uses the $(this) selector, which makes sure you are getting the text of the item that has been clicked upon only.

You can do this:
$('.ui-widget-content').click(function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});
DEMO: https://jsfiddle.net/lmgonzalves/pqo1r96p/
EDIT:
Please try this way instead:
$('body').on('click', '.ui-widget-content', function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});
DEMO: https://jsfiddle.net/lmgonzalves/pqo1r96p/1/

Related

how change "live" to "on" in this script on jquery for the same functionality

I want to convert jQuery code from live() function to on() function with the same functionality.
If I click to a paragraph is create another one, when I click to span "Delete" the paragraph is removed.
If I change live() to on() the paragraph is created if I click to the first paragraph not each paragraph she was created before.
The demo code is here: http://jsfiddle.net/ny38cLba/6/
HTML code
<body>
<p>Paragraph 1</p>
</body>
JS code
$(document).ready(function() {
var i = 2;
$("p").live("click", function() {
$("<p>Paragraph " + i++ +" <span> Delete</span></p>").insertAfter(this);
});
$("span").live("click", function() {
$(this).parent().remove();
});
});
If I want to hide a paragraph smoothly I use the following code :
$(this).on("click", "span", function(){
$(this).parent().hide("slow",function(){
$(this).remove();
});
})
but after the paragraph is deleted appears instead of a new paragraph.
See in this code: http://jsfiddle.net/a8e9v2m5/2/
This is in doc: http://api.jquery.com/live/
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
so,
$(document).on("click", "p", function() {
$("<p>Paragraph " + i+++" <span> Delete</span></p>").insertAfter(this);
});
$(document).on("click", "span", function() {
$(this).parent().remove();
});
.on() uses a slightly different syntax. Instead of selecting the element you want to watch, select a parent, with a filter selector.
$(document).ready(function(){
var i=2;
$(document).on("click", "p", function(){
$("<p>Paragraph "+ i++ +" <span> Delete</span></p>").insertAfter(this);
})
$(document).on("click", "span", function(){
$(this).parent().remove();
})
})
See the documentation for .on() for more info.
You can use 'on' instead of 'live' but not in the exactly same way when using dynamically generated DOM elements. You will have to bind the selector as well -
See, if this works -
$(document).ready(function () {
var colori = ["AntiqueWhite", "Aquamarine", "BurlyWood", "Chartreuse", "Coral", "DarkSalmon", "DodgerBlue", "GreenYellow", "LightBlue"];
var i = 2;
$(this).on("click", "p", function () {
$("<p>Paragraph " + i++ + " <span> Sterge</span></p>").insertAfter(this);
$(this).next().css("background-color", colori[i])
});
$(this).on("click", "span", function () {
$(this).parent().remove();
});
});
To be more specific to the span that is directly under the p tag
$(document).on("click", 'p', function(){
$("<p>Paragraph "+ i++ +" <span> Delete</span></p>").insertAfter(this);
});
$(document).on("click", 'p span', function(){
$(this).parent().remove();
});

Jquery Selectable TD Return

I have a table that is connected to Jquery selectable, and Im trying to get it to grab the value of the selected table item and put it in a text box. I keep getting
[object object] as the table value
here is the script
<script>
$( "#drilldowntable" ).selectable(
{ filter:"td",
stop: function(){
$(".ui-selected", this).each(function(){
var index = $("#drilldowntable td").val(this);
$("#graphinfo").val(index);
}
)}
});
</script>
any ideas why this is happening?
You mean something like this? Here's a FIDDLE
$("#drilldowntable").selectable({
filter: "td",
selected: function() {
$(".ui-selected", this).each(function() {
$("#graphinfo").val($(this).text());
});
}
});
by the way to retrieve td content you must use .text() only inputs have values.

Select username everywhere with selector

I'm using selectable() from jQuery it works just the way i want it.
But i want to go to the next step, i want it to select the message too inside the main chat.
So the text of the selected nickname will highlight too in the main chat.
JsFiddle http://jsfiddle.net/56SkH/13/
UPDATE
What i wanna to do is that when Nickname is selected from users that the channelmessage automaticly is being selected from the users.
$(function() {
$('#users').selectable({
selected: function(event, ui) {
var user = ui.selected.id.toLowerCase();
$('.channelmessage.'+user).addClass('ui-selected');
},
unselected: function(event, ui) {
$('.channelmessage').removeClass('ui-selected');
},
});
});
DEMO: http://jsfiddle.net/56SkH/23/
Try this - On click of each name corresponding message also selected using 'stop' property of selectable().
$(function () {
$("#users").selectable({
stop: function () {
$("#users li").each(function (key) {
$("#Nickname" +(key+1)+ "_message").css({"background":"white","color":"black"});
});
$(".ui-selected", this).each(function (key) {
var index = $( "#users li" ).index( this );
$("#Nickname" +(index + 1)+ "_message").css({"background":"#F39814","color":"white"});
});
}
});
});
It's easy to add a dummy class to each chat message, and the selector will be more efficient than searching for a name string.
$(function() {
$( '#users').selectable({
filter: "li",
selecting: function( event, ui ) {
$(".ui-selected").removeClass("ui-selected");
$('.channelmessage span.message.' + ui.selecting.id).addClass("ui-selected");
}
});
});
Here you have a working JSFiddle sample:
http://jsfiddle.net/56SkH/21/
You can force the selection on the element by adding the class ui-selected and using the selected event:
$(function () {
$('#users').selectable({
selected: function (event, ui) {
$(".channelmessage span.nickname.ui-selected").removeClass("ui-selected");
$(".channelmessage span.nickname:contains('" + ui.selected.id + "')").addClass("ui-selected");
}
});
});
In the example I use the span content as contains selctor, by I have modified a bit the HTML markup like:
<p class="channelmessage"> <span class="nickname">Nickname2</span><span>:</span>
<span class="message">Message</span>
</p>
Demo: http://jsfiddle.net/IrvinDominin/LnnLT/

Combobox event is not geting invoked

On click of a button a Combo Box gets displayed and on select of a Combo Box .
The change event is not getting called .
Please let me know where i am making the mistake .
<html>
<head>
<script src="jquery17.js" type="text/javascript"></script>
<script>
$("select").change(function(){
alert(this.id);
});
$(document).ready(function(){
$("button").click(function(){
var s = $('<select />');
var data = {
'foo': 'bar',
'foo2': 'baz'
}
for(var val in data) {
$('<option />', {value: val, text: data[val]}).appendTo(s);
}
s.appendTo('body');
});
});
</script>
</head>
<body>
<div id="div1"></div>
<button>Get External Content</button>
</body>
</html>
$(document).on("change", "select", function(){
alert($(this).attr("id"));
});
As <select> tag is appended dynamically so, you have to delegate event on it.
$("select").change(function(){
alert(this.id);
});
The problem is that you don't do this inside your $(document).ready(function(){ block.
Move it into there, otherwise you are setting an event handler on DOM elements that do not yet exist.
You have to place that in the doc ready but after appending those to body and yes that is dynamic so delegate the event to closest parent element or document itself which is the parent of all.
<script>
$(document).ready(function(){
$("button").click(function(){
var s = $('<select />');
var data = {
'foo': 'bar',
'foo2': 'baz'
}
for(var val in data) {
$('<option />', {value: val, text: data[val]}).appendTo(s);
}
s.appendTo('body');
});
// you need to place that here.
$(document).on('change', 'select', function(){
alert(this.id);
});
});

Positioning Dynamically created Button

I have created four text boxes and when I click a delete button it adds another set of text boxes with a remove button like this:
This is My script
$(document).ready(function() {
$("#add").click(function () {
$('.main').append("<div><br />" + $('.append_list').html() + '<button class="rmv_btn" onclick="$(this.parentNode).remove()">Remove</button></div>');
});
});
How can I add this button next to the first text box which is created dynamically?
With reference to this Question
Output Image
Create a temporary container in which you insert your cloned input list. Then find the first input in that temp container:
$(document).ready(function() {
$("#add").click(function () {
var container = $('<div />').addClass('justadded').appendTo('.main');
$(container).append($('.append_list').html());
var input = $(container).find('input:first');
$('<button />').text("Remove").addClass('rmv_btn').attr('onclick', '$(this.parentNode).remove()').insertAfter(input);
$(container).removeClass('justadded');
});
});
See this : http://jsfiddle.net/MpEUZ/5/
$(document).ready(function() {
$("#add").click(function() {
$('.main > :first-child').clone().appendTo('.main').find('input[type=text]').val('');
$('.main .append_list:last').find('input[type=text]:first').after("<button class='rmv_btn' style='clear:both'> Remove </button>");
});
$('.main').on("click", ".rmv_btn", function() {
$(this).parent().remove();
});
});​
This one should works :
$(document).ready(function() {
$("#add").click(function () {
var html = $($('.append_list').html());
html.find('input').first().after('<button class="rmv_btn" onclick="$(this.parentNode).remove()">Remove</button></div>');
$('.main').append("<div><br />" + html);
});
});
I guess $('.append_list') is containing the good html for the inputs.

Categories

Resources