JS: can't open links other than first - javascript

I'm Looping through rows, generating links with each their identical value, in this case.
Shown here:
#foreach (var article in Model.Articles)
{
<tr class="etc">
#if (Model.Order.Status == Model.Orders.Status.Blocked)
{
<td id="buttonDeleteOrderLine" description="#article.Description" name="#Model.Order.FullName" value="#article.LineId" >Delete Line</td>
}
Value="value" is unique in this case!
My JS:
$('#buttonDeleteOrderLine').on('click', function () {
var DOL = $(this);
var orderDescription = DOL.attr("description");
var customerName = DOL.attr("name");
var lineID = DOL.attr("value");
I'm getting links for each row, and they're also clickable. However, only the first one actually works (shows a modal, not included in JS Code)
So I need a way, to search the class 'buttonDeleteOrderLine' (because the ID changes), and yet get the info from the clicked link.

You can only have one element per ID, where you can have any number of elements per Class.

It was quite simple actually,
Set
id="buttonDeleteOrderLine" to class="buttonDeleteOrderLine"
and I've changed:
$('#buttonDeleteOrderLine').on('click', function () {
to:
$('.buttonDeleteOrderLine').on('click', function () {
It now works and gets the correct information of each link, including the sub-information.

Related

Showing Hidden Row in Table

I am using some code based on the following JSFiddle. The intention is to show more information when the user clicks the "Show Extra" link.
The problem that I'm having is that when the link is clicked on all but the bottom row of the table the hidden element is shown briefly and then closes.
I am populating my table using template strings in javascript. Here is the code that I use to add rows to the table:
this.addRecordToTable = function(bet, index, id){
console.log(index);
console.log($.data(bet));
var butId = id.toString();
if (bet.bookies == null){
bet.bookies = "";
}
if (bet.bet == null){
bet.bet = "";
}
var newRow = `
<tr>
<td>${bet.date}</td>
<td>${bet.bookies}</td>
<td>${bet.profit}</td>
<td><button id=${butId}>Delete</button></td>
<td>Show Extra</td>
</tr>
<tr>
<td colspan=\"5\">
<div id=\"extra_${index}\" style=\"display: none;\">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
`
console.log(newRow);
console.log("#"+butId);
$(newRow).appendTo($("#betTable"));
$("#"+butId).click(
function()
{
if (window.confirm("Are you sure you want to delete this record?"))
{
var rec = new Records();
rec.removeRecordAt(index);
$("#betTable tbody").remove();
var c = new Controller();
c.init();
}
});
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
}
EDIT:
I had to change $("a[id^=show_]").click to $("a[id=show_"+index).click..., as the event handler was being added to each element every time I added a new element. Thanks to #freedomn-m.
This code:
$("a[id^=show_]")
adds a new event handler to every existing link as well as the new one as it's not ID/context specific so all the show a's match the selector.
You need to add the context (newRow) or use the existing variable(s) as part of the loop that are already defined, eg:
$("a[id^=show_]", newRow)
$("a#show_" + index)
(or any other variation that works).
An alternative would be to use even delegation for the dynamically added elements, eg:
$(document).on("click", "a[id^=show_]", function...
in which case you'd only need to define/call the event once and it would be fired for new elements (ie put that outside the new row loop).

Bootstrap form group checkboxes doesn't get checked in between nav pills

Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/
I use Bootstrap nav-pills to show all products and categorized too like this:
And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes
I count the number of products checked in between the tabs like this:
jQuery(document).ready(function($) {
jQuery(".select-product").change(function() {
jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);
});
});
But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.
I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.
Ideas, anyone?
Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.
Before we try and resolve this issues, we should break it down and see what the actual problem is.
First, let's check if we remove the content from tab 1b is the issue still present?
Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.
Fiddle #1
What if we change the id of the checkboxes (remember ids should be unique).
Notice how Book #1 now works if we change the first checkbox's id to 1a.
Fiddle #2
So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:
How do we check multiple checkboxes if one is checked
(or something like that)
Here's what I would do:
assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison
Working Example
EDIT
Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.
var productIDs = <?php echo json_encode($products_id_array) ?>;
and then creating the snippet of jQuery code on the fiddle like this
productIDs.forEach(function(val, key) {
jQuery('.' + val).on('change', function(){
jQuery('.' + val).prop('checked',this.checked);
});
})
Try this JS, This will work
jQuery(".select-product").change(function() {
var checkValue = jQuery(this).prop('checked');
$('.select-product#' + jQuery(this)[0].id).each(function() {
if (checkValue == true) {
jQuery(this).prop('checked', true)
} else {
jQuery(this).prop('checked', false);
}
});
var uniqueId = [];
jQuery("[type='checkbox']:checked").each(function() {
uniqueId.push(jQuery(this)[0].id);
});
Array.prototype.getUnique = function() {
var u = {},
a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
jQuery(".counter").text(uniqueId.getUnique().length);
});

Trying to remove a child html element with javascript

I have 3 tables in my boostrap tab. Each tab as a table. The rows of this table is dynamically generated with csharp asp.net code. Right I Want a scenario were if a user click on the row of the first table, the clicked role of the first table get remove from the first table and is added to the rows of the second table.
My challenge as been getting to remove the row after the onClick process.
<tbody>
<tr id="kayode#yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515"
data-parentid="kayode#yahoo.com"
href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com"
operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Active</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>02:52:55</td>
<td>271.0.0.1</td>
</tr>
</tbody>
My javascript code which I am trying to use to remove the row after the Click event.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
//alert(parentid);
//we are going to remove the role from this field
var element = document.getElementById(parentid);
element.parentNode.removeChild(element); //This line is a problem says
//document.querySelector("tablebody4 first").appendChild(element);
console.log(element);
}
This is untested, but I imagine jQuery will greatly reduce your headache here:
function updateWaitingState(sender) {
var parentId = $(sender).attr("data-parentid");
$('#' + parentId).appendTo('.tablebody4:first');
}
You may need to adjust the selector in the appendTo function, as it was a guess on my part.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
var element = document.getElementById(parentid);
$(element).appendTo('.tablebody2:first');
}

jquery selection attributes

Let's say I have a sample table like this :
http://jsfiddle.net/65BkH/
Now what i want is, if there is this <button id="invite">Invite</button>. I want this button to select the "invite url" of the selected contact. If you see the jsfiddle, if you click the checkbox, it will crop all the others contacts. How could i do that?
I've tried to target the contact, but i can only get the top contact.
$('#linkedin_match tbody .match .m a').attr('href');
what i want is to target the currently selected.
FURTHER PROBLEM :
This button I'm talking about is not the table per say.
$('#btn_save').click(function(e) {
var hrefVar = $('#linkedin_match tbody .match .m').find('a').attr('href');
alert(hrefVar);
});
Now if i used that, it still searches for the first link, even though i've selected the others. So, any changes?.
You can use this:
$('#invite').on('click',function(){
var url = $this.closest('tr').find('a').prop('href');
});
To get all the checked href related with the checked inputs in a array use this:
$('#invite').on('click', function () {
var all_url = [];
$('input:checked').each(function () {
var url = $(this).closest('tr').find(' td.m a').prop('href');
all_url.push(url);
});
});
Demo here
$('.m').click(function(e){
var hrefVar = $(this).find('a').attr('href');
alert(hrefVar);
});
fiddle

JS: Click one div, change another div value

I have a vote button I created that is contained within a .vote_div. 2 parts: .vote_num for the vote total, and .vote for the vote button. The page has a list of items so I need to make sure when the user clicks .vote, it changes the corresponding .vote_num + 1.
My JS function worked when the .vote actually was the total votes, but now I am seperating the two. How do I grab the right .vote_num on the .vote click?
Thanks!
<script>
$(".vote").click( function() {
var votes = $(this).attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
$(this).text(parseInt(votes) + 1);
return false;
});
</script>
<div class="vote_div">
<span class="vote_num" votes='{{host.num_votes}}'>{{host.num_votes}}</span>
<span class="vote" id="{{host.user.id}}">Vote</span>
</div>
EDIT & SOLUTION:
Got it working using $(this).parent() :
<script>
$(".vote").click( function() {
var votes = $(this).parent().find('.vote_num').attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
votes = parseInt(votes) + 1;
$(this).parent().find('.vote_num').text(votes);
return false;
});
</script>
try:
var votes = $(this).parent().find('.vote_num').attr('votes');
It goes to the parent of the clicked div then looks for an element with class vote_num then grabs the votes attributes.
#James answer should work, but this should give you a little more freedom to rearrange the two divs and add other elements so long as they share the parent.
To be even more robust you could do (note the 's' on "parents")
var votes = $(this).parents('.vote_div').find('.vote_num').attr('votes');
This will allow the elements to be nested arbitrarily deep as long as they only have a single parent with a class of `vote_div'.
See: http://api.jquery.com/parent/ , http://api.jquery.com/parents/ , and http://api.jquery.com/find/
if you have multiple class with vote, maybe you should use each()
$(".vote").each(function () {
var current = $(this);
current.click = function () {
// the rest of your function
}
})
Assuming I've understood the question correctly, and also assuming that your vote_num element is always the first element in the vote_div element:
var votes = $(this).siblings().eq(0).attr("votes");
Put this inside your click event handler will get the votes attribute from the first sibling element of the clicked element.
You can make this simpler if you are sure the element in question will always be directly before the clicked element:
var votes = $(this).prev().attr("votes");
var votes = $(this).attr('votes');
'votes' does not belong to class 'vote', it belongs to class 'vote_num'
so the line should be
var votes = $(".vote_num").attr('votes');
$('.vote').click(function(){
var $vote_num_obj = $(this).parent().find('.vote_num');
var new_vote_num = parseInt($vote_num_obj.attr('votes'))+1;
$vote_num_obj.attr('votes', new_vote_num);
$vote_num_obj.html(new_vote_num);
});
Put this script inside $('document').ready(function(){ ..here.. });
I suggest to change votes attribute of your span.vote_num to data-votes and change also the jquery attribute selector, this way it will be standard compliant.

Categories