Get the data-url correctly using javascript function - javascript

I am creating a delete comment function and
this are the pieces of html for a delete comment functionality.
<div id="comment-area">
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/12/6">
x
</small>
</div>
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/13/6">
x
</small>
</div>
</div>
And this is the function for delete a comment, which is automatically loaded when document is ready,
function delete_comment () {
$('.delete-comment').click( function (e) {
var url = $('.delete-comment').attr('data-url');
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (data) {
$('#comment-area').html(data.comments);
delete_comment();
},
error: function () {
alert('error');
}
});
});
}
The problem with this function from the given html above, if I'm going to click on .delete-comment with
data-url="http://myproject.com/comment_controller/delete_comment/13/6" take note on this "13/6", the javascript function delete_comment(),
in this line
var url = $('.delete-comment').attr('data-url');
chose to get the data-url="http://myproject.com/comment_controller/delete_comment/12/6" take note also this "12/6", to see the difference, instead of the data-url of .delete-comment I clicked.
In short, this function always chose the first-child div small, whatever small.delete-comment I'm going to click.
What was the best solution for this?

Try
var url = $(this).attr('data-url');
You are getting the attribue value by className and multiple elements have same class so the attribute value for first element found in dom is being returned.
So you need to get the value of element which is clicked and you can use this to get the value of clicked element.

A more robust way to approach this would be to use the jQuery .data() function.
var url = $(this).data('url');
This will pick up any dynamically added/updated url that may have changed via JavaScript, but not updated in the DOM attribute.

Related

Dynamically created elements all return the same index

I'm dynamically creating dropdowns in a table, and I'm trying to grab the index of the dropdown that triggered the event, like so:
$(".template").on('change', '.dataTypes', function () {
var selectedDatatype = $(this).find(":selected").val();
var ix = $(this).index(); // get this index
$.ajax({
type: "GET",
url: "http://localhost...",
contentType: "application/json; charset=utf-8",
success: function (result) {
populateListDropdown("gs", ix, result.Result);
},
error: function () { },
timeout: 120000
});
});
This code, regardless of the dropdown I interact with always returns a 0 for the index and I'm not sure why.
HTML if it's helpful. The page has a single row loaded at startup, and additional are added via button click.
<table class="tblColumns">
<tr>
<td>
<div class="column">
Select DataType :
<select class="dataTypes"></select>
</td>
</tr>
</table>
index() method returns index based on its siblings. Your all dropdowns are in seperate td. So all have same index.
You are looking for tr index not select. Try
$(this).closest('tr').index();
For further reading, check out https://api.jquery.com/index/
"If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements."
In your HTML the is the only element, hence always returning '0'.
As #Azim pointed out, if you use , it might work.

How to display item from server once a link is clicked

student here! So I created a function that runs an $.ajax request, and for each item, I output html to the DOM. Well, check it out:
function getLinks (){
let blogLinks;
$.ajax(settings).then(function(data, status, xhr){
data.forEach(function(item, i, arr){
let id = item._id;
if (item.title){
blogLinks = `<li><a class="link" href=#${item.title}>${item.title}</a></li>`
$($findUl).append(blogLinks);
}
})
})
}
this var might be useful info as well:
let $blogViewAll =
$(`<div class="blog-view">
<h3>Check Out These Blogs</h3>
<div class="column-1">
<ul class="link-list"></ul>
</div>
<div class="column-2"></div>
</div>`);
let $findUl = $($blogViewAll).find('.link-list');
It's doing exactly what I want it to do and appending the links to the page. Now I want to click on the link and have the message body display on the page. So I'm trying this:
$findUl.on('click', function(e){
$.ajax(settings).then(function(data, status, xhr){
data.forEach(function(item, i, arr){
//since you clicked on that link
//I should look at what you clicked
//match it to the corresponding obj{item.body}
//and display it, but I don't know how to match and grab :(
})
})
});
And that's where I'm stuck! Any suggestions? Thanks!!!
(i'm using the tiny-za server btw)
You can access the current link the user clicked on in your initial argument e, via the property e.currentTarget:
$findUl.on('click', function(e){
// this gives you the DOM node that was clicked:
console.log(e.currentTarget);
}
A little shortcut to get the title using jQuery:
$findUl.on('click', function(e){
var title = $(e.currentTarget).text();
}
Another note, you should really only be loading the data from the server in that ajax call once, not every time something is clicked (which is sloooow).
I'd recommend loading the data into an object when the page loads, then using the obejct properties to append to the DOM. You'll be able to access that same object in future click handlers

If div text equals certain text do something?

Cannot for the life of me get this to work. Even when removing the AJAX POST function, it still doesn't work. There is no alert or anything. Here is the JSFiddle and code:
HTML
<div class="notification">
<div class="title gooddog">test</div>
<div class="reason helvetica"></div>
</div>
<script>
var interval = setInterval(function(){
var Winner = $(".notification .title gooddog").text();
if(Winner == "test") {
$.ajax({
url: "Won.php",
type: "POST",
data: { Winner : Winner }
})
.success(function(data) {
console.log('foo', data);
});
}
},1000);
</script>
It is meant to trigger/check the div text for changes every 1 seconds, but as you can see, it's doing nothing..
var Winner = $(".notification .title gooddog").text();
should be
var Winner = $(".notification .title.gooddog").text();
jsfiddle http://jsfiddle.net/abwp5u21/8/
You've got several issues...
You are using jQuery syntax but you are not including the jQuery plugin...at least not in the fiddle
Not an issue in this case, but if you want to get whatever is inside a div use the html function rather than the text function
As #Cattla pointed out in her answer to the proper "multi-class" selector is .title.gooddog
I wouldn't be surprised if you had more issues on the server-side as well. Here's an updated JS Fiddler

knockout js observe global variable

I am setting a variable
var extQty;
Then a user inputs some data and submits, I return a json string with extQty. On success I am updating the variable:
success: function (result) {
window.extQty = result.extQty;
}
I need to hide a button if the extQty surpasses the row count of a grid. How can I do this? I tried the below but it is not seeing the variable change as this has already loaded before extQty gets updated.
<!-- ko if: pagedList().length < extQty -->
If I change extQty in the above to say 3 it works...
Make your variable a ko.observable and make it part of your view model.
function viewModel() {
this.extQty = ko.observable(0);
this.pagedList = ko.observableArray();
//....
}
var myViewModel = new viewModel();
ko.applyBindings(myViewModel);
Then in your AJAX success:
success: function (result) {
myViewModel.extQty(result.extQty);
}
Tried updating your fiddle:-
Your Fiddle Updated
<div data-bind="style: { display: (pagedList().length < extQty()) ? 'block' : 'none' }">
<p class="pull-right">
<a class="btn btn-primary" data-bind="click: $root.add" href="#" title="edit"><i class="icon-plus"></i>Add Extension</a>
</p>
</div>
Correct me if i am wrong, when your use if binding, it allows the markup to appear or dissapear from your document based on condition as true or false. When your condition is false, the element would be commented out code when you see in html. Which cannot be changed unless you refresh the page. So, use visible binding, the markup stays in dom and you can play with the Visible binding to hide it or show it...
Have a look at Knockout If Binding documentation

jquery problem?

i have this jquery problems i have had for days, im so new to this, so excuse my dumbness in this subject. thanks :))
html code:
<ul class="statuses">
<li id="set_23" class="message">
// this is meant to increase everytime you click the vote_up just like stackoverflow
<span class="vote_count">27</span>
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
</li>
</ul>
this is my jquery code:
$(document).ready(function() {
$('#statuses').delegate('.vote_up', 'click', function() {
//get the id
var the_id = $(this).closest('.message').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// fade in the new vote_count
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrowActive.png");
}
});
});
});
EDIT: also the jquery fade.in and change of image src is not working, am i referencing the right span or class(the ajax request is working now)
First thing to jump-out:
<ul class="statuses">
and
$('#statuses')
... the # symbol in jQuery is the id-selector (same as CSS). Since your <ul> is set to class="statuses" then you'll need to use the class-selector:
$('.statuses')
That alone will break all your jQuery
From the jQuery docs:
The beforeSend, error, dataFilter,
success and complete options all take
callback functions that are invoked at
the appropriate times. The this object
for all of them will be the object in
the context property passed to $.ajax
in the settings; if that was not
specified it will be a reference to
the Ajax settings themselves.
So, try adding context: this to your ajax request options.
Change this
var the_id = $(this).closest('.message').attr('id').split('_').pop();
to this
var the_id = $(this).parents('.message').attr('id').replace('set_', '');
or alternatively
var the_id = $(this).parent().attr('id').replace('set_', '');
if you know that your link's parent element will always be ul.message.

Categories