I'm using jQuery. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute?
My HTML looks like this:
<ul class="nav nav-pills">
<li class="onselectedCategory" data-id="12">12</li>
<li class="onselectedCategory" data-id="23">23</li>
<li class="onselectedCategory" data-id="34">34</li>
<li class="onselectedCategory" data-id="45">45</li>
<li class="onselectedCategory" data-id="56">56</li>
</ul>
And my JavaScript looks like this:
events{
"click li.onselectedCategory": "selectCategory"
}
selectCategory: function(event){
event.preventDefault();
var _selectedValue = $(this).data('id');
alert("Selected Value : "+_selectedValue);
},
Try this:
$(".onselectedCategory").click(function(){
alert($(this).data("id"));
});
onselectedCategory is a class, therefor you need to reference it with a . and not with the # which is used for ids.
change #data-id to data-id
$(".onselectedCategory").click(function(){
alert($(this).attr("data-id"));
})
Edit for backbone
selectCategory: function(event){
event.preventDefault();
var selectedValue = "";
if($(e.target).is('li')) {
selectedValue =$(e.target).attr('data-id');
} else {
selectedValue =$(e.target).parent().attr('data-id');
}
alert("Selected Value : "+ selectedValue);
},
The onselectedCategory class must be within the label <a>
<li><a class="onselectedCategory" data-id="12" bla,bla,bla...</li>
$(".onselectedCategory").click(function(){ alert($(this).data("id")); });
Related
Friends have a problem.
When clicking a link from a menu, I need to generate below the selected sub-menu item.
So far I can send the request via ajax, and generate a sub-menu, but this sub-menu always appears in the first position:
HTML CODE (simple menu)
<ul>
<li>Item 1
<ul id="city"></ul>
</li>
<li>Item 2
<ul id="city"></ul>
</li>
<li>Item 3
<ul id="city"></ul>
</li>
<li>Item 4
<ul id="city"></ul>
</li>
<li>Item 5
<ul id="city"></ul>
</li>
</ul>
JS CODE:
$('.region_id').on('click', function(event) {
event.preventDefault();
$.get('{!! url("filter_city") !!}', {id : $(this).attr('data-id'), token: $('input[name="_token"]').val() }, function(data) {
var cities = $('#city');
cities.empty();
$.each(data, function(key, value) {
cities.append($("<li></li>").text(value));
});
});
});
Result I get when clicking any option
As I can achieve what I want? Greetings from Chile
Identifier in HTML must be unique. You can use a common class and then traverse DOM using various methods.
Here's an example, I have used city as CSS class instead of ID. then the relevant element can be identified using any of these methods.
var cities = $(this).next('.city');
//var cities = $(this).siblings('.city');
//var cities = $(this).closest('li').find('.city');
HTML
<ul>
<li>
Item 1
<ul class="city"></ul>
</li>
</ul>
Script
$('.region_id').on('click', function(event) {
event.preventDefault();
var cities = $(this).next('.city');
$.get('{!! url("filter_city") !!}',
{
id : $(this).data('id'),
token: $('input[name="_token"]').val()
},
function(data) {
cities.empty();
$.each(data, function(key, value) {
cities.append($("<li></li>").text(value));
});
}
);
});
I would recommend you to use .data() instead of attr() to fetch data-* custom attribute value.
var id = $(this).data('id');
<div class="container-fluid">
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg">
<ul class="nav pull-right">
<li>
<li>
Contact Club
</li>
<li>
<li class="dropdown">
</ul>
</div>
I want to change the href value "/ContactClub" to "somethingelse". How is this done please?
Two ways ;)
jQuery style:
// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');
Pure-js solution (untested)
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (element[i].href === '/ContactClub') {
if (element.setAttribute !== 'function') {
element[i].href = 'newhref';
} else {
element[i].setAttribute('href', 'newhref');
}
}
}
I would add an id to the a tag:
<a id="contact_link" href="/ContactClub">Contact Club</a>
And then do either,
$('#contact_link').attr('href', 'new url');
or,
document.getElementById('contact_link').href = 'new url';
Note: You can also use the jQuery prop method in the same fashion as attr above. This is somewhat a matter of preference. As href is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr. Other attributes like value will depend on what you're trying to retrieve. Do a bit of research on the differences.
You can use either prop() or attr():
$('a[href="/ContactClub"]').attr('href', 'New Href here');
or:
$('a[href="/ContactClub"]').prop('href', 'New Href here');
Fiddle Demo
try
$("li a").attr("href","new value");
I have used Lists within a list and I intend to send the id's using jquery to another php file(updateDB.php).
I tried serializing the list but couldn't get the data. I'm not sure if i've got it right, tried looking around every place but couldn't figure out what's wrong with the code.
<ul>
<li id="recordsArray_<?some number?>"><?php echo content?>`
<ul>
<?php
while (some condition) {
?>
<div>
<li id="subArray_<another number?>"><?php echo content?></li>
</div>
<?php
//conditions - increment within the loop
}
?>
</ul>
</li></ul>
the jquery code is something like this,
$(document).ready(function() {
$(function() {
$("#contentLeft ul").sortable({opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable('serialize') + '&action=updateMenuListings';
$.post("updateDB.php", order, function(theResponse) {
$("#contentRight").html(theResponse);
});
}});
});
$(function() {
$("#contentLeft ul li ul").sortable({opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable('serialize') + '&action=updateSubListings';
$.post("updateDB.php", order, function(theResponse) {
$("#contentRight").html(theResponse);
});
}});
});
});
the id's contentLeft are just the id's for before the lists.
I intend to make it draggable hence used sortable.
On debugging, i'm unable to get any id's of the lists in the variable 'order'.
Please do check out the code and help out.
Thanks
Below you'll find some HTML that is structure like yours along with the JavaScript and jQuery to do what you want. This allows you to move the top level items, with all their respective subitems or just rearrange the subitems. Both options generate a body that you can use in the commented out post line.
You can see it in action here: http://jsfiddle.net/WTjsG/
HTML:
<div id="ContentLeft">Sortable With Update
<ul id="Nav" class="sortable navLevel1">
<li id="Nav_1">Nav1
<!-- NOTE: format id's for UL and LI items as <name>_<int> for serialize to work properly -->
<ul id="NavRecords_1" class="sortable navLevel2">
<li id="Nav1_1">Nav1 Item1</li>
<li id="Nav1_2">Nav1 Item2</li>
<li id="Nav1_3">Nav1 Item3</li>
<li id="Nav1_4">Nav1 Item4</li>
</ul>
</li>
<li id="Nav_2">Nav2
<ul id="NavRecords_2" class="sortable navLevel2">
<li id="Nav2_1">Nav2 Item1</li>
<li id="Nav2_2">Nav2 Item2</li>
<li id="Nav2_3">Nav2 Item3</li>
<li id="Nav2_4">Nav2 Item4</li>
</ul>
</li>
</ul>
</div>
JavaScript w/ jQuery:
$(document).ready(function () {
var isDebugMode = true;
//Set common sort settings for all lists
$(".sortable").sortable({
opacity: 0.6,
cursor: 'move'
});
//Function used to configure update calls for each sort
function setSortAction(selector, updatePage, updateAction, itemLabel) {
$(selector).sortable({
update: function () {
var itemList = $(this).sortable(
"serialize", {
attribute: "id",
key: itemLabel
});
//Create POST request to persist the update
var bodyContent = "action=" + updateAction + "&" + itemList;
if (isDebugMode) { alert("DEBUG: bodyContent = \n" + bodyContent); }
//$.post(updatePage, bodyContent, function (postResult) { alert(postResult); });
}
});
}
//Set sort update action for top level and second level
setSortAction(".navLevel1", "updateDB.php", "updateMenuListings", "record");
setSortAction(".navLevel2", "updateDB.php", "updateMenuItemListings", "record");
});
Say I have a list like so:
<ul id="my-list">
<li class="list-item" data-role="collapsible">List Item</li>
<li class="list-item" data-role="collapsible">List Item</li>
<li class="list-item" data-role="collapsible">List Item</li>
</ul>
I want to be able to add another li element with the class list-item and maybe the data-role collapsible at the end of the list. But, I want to pass the contents of a variable to the inside of the new li tag. Say the variable is var myVariable = "Contents of Variable"; Is there a way to do this using jQuery and/or JavaScript?
You could clone one of the existing tags:
$('#my-list li').first().clone().text(myVariable).appendTo('#my-list');
And with plain JavaScript:
var list = document.getElementById('my-list');
var elem = list.firstChild.cloneNode();
elem.textContent = myVariable;
list.appendChild(elem);
Try this:
var myVariable = "Contents of Variable";
$("#my-list").append("<li class='list-item' data-role='collapsible'>" + myVariable + "</li>");
Are you trying to do this FIDDLE ?
var myVariable = "Contents of Variable";
x(myVariable);
function x(obj) {
$('#my-list').append('<li class="list-item" data-role="collapsible">' + obj + '</li>');
}
Also
function create(content){
$('<li />', {
class: 'list-item',
'data-role': 'collapsible'
}).html(content).appendTo('#my-list')
}
create('my content')
Demo: Fiddle
You can use
$('#my-list').append('<li class="list-item" data-role="collapsible">' + myVariable + '</li>');
I use jquery draggble function for unorderd list (ul) and face a problem of getting the order of items after it changed and setting the order ofter page is loaded.Suppose we have the following code :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$('.secondblock').sortable({axis:'y'});
$(".block").sortable({
axis: 'y',
update: function(event, ui) {// order changed
var order = jQuery(this).sortable('toArray');
// set this order to .secondblock
}
});
});
</script>
</head>
<body>
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
</body>
Are there any possible solutions?
First, you shouldn't have the same id appear twice in a document. That will cause all kinds of problems.
Instead, set a data-attribute on the items in the second list to reflect corresponding items in the first list:
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li data-block-id = "one">1</li>
<li data-block-id = "two">2</li>
<li data-block-id = "three">3</li>
<li data-block-id = "four">4</li>
<li data-block-id = "five">5</li>
</ul>
Then reflecting the sort of the first list in the second list is simple:
$('.block').sortable({update: sortOtherList});
function sortOtherList(){
$('.block li').each(function(){
$('.secondblock [data-block-id=' + $(this).attr('id') + ']')
.remove()
.appendTo($('.secondblock'));
});
}
See it working here: http://jsfiddle.net/6HKZG/2/
Faust's looks better to me. Mark it if it's what you wanted.
Yes. I feel like I need more information, but I had to do almost the exact same thing recently.
First, you want to extend the javascript array object with a sorting algorithm. Here is what I use:
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
source Move an array element from one array position to another
Then, what I would do is use this along with an OldPosition/NewPosition function to get the index of the element before and after the sort, and use this method to move the object in the array.
I think JQuery sort let's you get information about the array before and after the sort
ex:
$('li').presort(function() {
window.oldindex = $(this).index();
});
$('li').postsort(function() {
window.newindex = $(this).index();
array.move(oldindex,newindex);
});
If you're just looking to make .secondblock match .block after sort, you can do this:
source: http://jqueryui.com/demos/sortable/#events
$( ".selector" ).sortable({
start: function(event, ui) { //Get the order of the .block list items before dragging }
});
$( ".selector" ).sortable({
stop: function(event, ui) { //Get the new order of the list items after dragging. Compare the two orders and sort .secondblock to match block }
});