jQuery bind click not adding elements - javascript

I have a button that when I click it more than once it is adding elements from the previous click. It works fine the first time through. We are using jQuery 1.11.1.
$(function() {
$('a[name="generateReport"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?est=' + est.value + '&prodcd=' + prodcd.value + '&startDate=' + startDate.value + '&endDate=' + endDate.value + '&tracking=' + tracking.value);
})
})
What I am seeing is that the URL past to the server is adding the fields from the prior click. This of course causes issues when it gets to the server. Does this need to be cleared out after each click?
This is the code that calls it from our Grails app(2.4.3)
<g:link class="btn btn-primary" name="generateReport" controller="generateTTLReport" action="renderOutput">
<i class="icon-print icon-white"></i>
Generate Report
</g:link>
Thanks,
Tom

Split the current href at the "?" to remove the query string parameters. Also, let jQuery build your new query string parameter string.
$(function() {
$('a[name="generateReport"]').on('click', function() {
var $this = $(this),
path = $this.attr('href').split('?')[0],
params = {
est: est.value,
prodcd: prodcd.value,
startDate: startDate.value,
endDate: endDate.value,
tracking: tracking.value
},
href = [path, $.param(params)].join('?');
$this.attr('href', href);
});
});

The problem with your code is, every time you click on that button, bind callback is invoked. So the first time you clicked, it got the href attribute added some parameters and replaced it. Again when you clicked on that for the second time, it does the same thing. It gets the href attribute which now contains parameters from previous update and then replace the existing. If you keep the href as it is, and only update the query parameters, you can define that as a global variable and use that in your event handler
You can hard code that link as a variable within in your script like this
$(function() {
// define your variable within document.ready but outside your event handler
var reportURL = '/LSRTIS/generateTTLReport/renderOutput';
$('a[name="generateReport"]').bind('click', function() {
var urlWithParams = reportURL + '?est=' + est.value + '&prodcd=' + prodcd.value + '&startDate=' + startDate.value + '&endDate=' + endDate.value + '&tracking=' + tracking.value;
$(this).attr('href', urlWithParams );
});
});
Hope this helps :)

Related

on click fires outside of hyperlink

I am creating a dynamic delete link that as such:
<a id=\"removeAtt__" + i + "\" class=\"remove_button\" style=\"color:#aaa;\"><i class=\"fa fa-times-circle\"></i> remove</a>
I am using the following code once the link is clicked:
$(document).on("click", $('[id*=removeAtt__]'), function () {
var id = event.target.id;
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
What I am finding is that even when I click outside of the hyperlink at times, it fires the delete. Is there a better way to do this so it fires on click of the hyperlink all the time.
You need to pass a selector, like
$(document).on("click", '.remove-button', function () {
var id = this.id;
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
And oldschool solution is to define a function to be executed when the button is clicked and call it in the onclick attribute of the tag.
You're selector is not correct so it's actually executing on $(document). This is my preference on writing jQuery selectors:
$('[id*=removeAtt__]').on("click", function () {
var id = $(this).attr('id);
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
The reason is if my selector is off I don't get a false sense that code is actually working.

Jquery .replaceWith not working proper

i have a jquery code that is preventing a link to go to that link but executing it. The problem i have is that after it executs the script and script is returning data i want to replace it with a new one but with the same class. The replace is doing inside the dom but next time i press that link is not prevening going to that link but the class is the same, here is my code:
<script>
$(".recomanda").click(function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomandat</a> ');
}
if(data.recom==0)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});
</script>
html
<a class="recomanda" href="app/recomanda_produs.php?id='.$row['ID_Produs'].'&recom=0">Recomanda</a>
yeah, I ran into that problem too before, it's because when you attach click to recomanda on ready(), but when ajax load, everything in ready() won't fire again, that why you need to attach the event to non-dynamic elements, and let it find it's child selector.
$('body').on('click', '.recomanda', function() {});
When you call a replaceWith actually you are removing elements that are bound to onclick handler:
.replaceWith()
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
The main idea is that you handler must be bound to the same element (that is not removed when clicking).
So instead of using replaceWith method use method that modify existing element like this:
test.attr('href', blablabla);
And this is not a problem, but second time you don't need to use $ with test variable.
You need to delegate the event to a parent so that it can be applied to specific children wether they exist now or in the future.
See: http://learn.jquery.com/events/event-delegation/
$("body").on("click", ".recomanda", function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda"+((data.recom==1)?"t":"")+"</a> ');
}
if(data.recom==0){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});

bootstrap accordion how to check which panel is active

I am using Bootstrap's accordion widget to contain several forms i.e. each panel contains one form. When the last panel is selected, the data from the other panels is meant to be posted which will be used to graph the data. However, I am unable to get to the posting part as I cannot figure out which panel is currently selected. I know that this has to do with a class of active or inactive, but I don't think bootstrap's accordion supports that functionality unlike jquery accordion.
I am trying to figure out the first part i.e. check if the user has clicked on the last panel. In my HTML code it has an id of #results. Here's a jsfiddle that demonstrates the issue I am facing. It does not seem to trigger the second alert function when the user clicks on the #results tag, not sure why.
Sample javascript code:
$('#accordion').on('show.bs.collapse', function () {
$('#results').click(function () {
alert("works"); //testing purposes
});
});
Why don't you do?
$('#results').click(function (){
alert("clicked");
});
Just remove the accordion function and you'll get the on click event directly
Is this what you want?
Fiddle: Demo
take this outside the on function
$('#results').click(function (){
alert("clicked");
});
This is an old thread but I wanted to post an answer as the expected result is not suggested.
What you need to do here is to handle the currently selected collapse items with the event handler. If you use the this keyword for this, you can access the values of the selected object (For example only one item in the form).
Here you can get the $(".collapse") element.
You can get the index number of the active item with $(this).parent().index().
Likewise, you can get the id of the active item with $(this).attr('id').
Your jQuery structure would be:
$(".collapse").on('show.bs.collapse', function(){
//0,1,2,etc..
var index = $(this).parent().index();
//collapseOne, collapseTwo, etc..
var id = $(this).attr('id')
//alert('Index: ' + index + '\nItem Id: ' + id );
console.log('Index: ' + index)
console.log('Item Id: ' + id)
if(id === 'collapseFour')
{
var username = $('#username').val();
var email = $('#email').val();
var age = $('#age').val();
//here you can check the data from the form
$("#result").html("<p> UserName: " + username + "</p> <p> EMail: " + email + "</p> <p> Age: " + age + "</p>");
}
});
I've included a working example here for you (jsfiddle).
$('#accordion').on('show.bs.collapse', function (accordion) {
var $activeCard = $(accordion.delegateTarget.children);
});
or
$('#accordion').on('show.bs.collapse', function () {
var $activeCard = $(this.children);
});

Repeatable Blocks

I currently have a bit of JS which will generate buttons based on the data attribute stored in the HTML, which will generate 2 buttons:
Plus Button to add a repeatable block(Will/should only display a plus button if there is only one block)
A minus button to remove the repeatable field(will/should show when there is more than one blocks)
Thing is, I have the buttons working fine, but when I added the event handlers for them to do as I ask, and click on them nothing happens, am not sure why and hopefully you can point me in the right direction.
Regards!
P.S jQuery Code
$('.glyphicon-plus-sign').on("click", function () {
prevInput = $(this).prev('input');
count = $(prevInput).attr('data-count');
countIncremented = count++;
br = '<br/><br/>';
inputElement = '<input type="' + $(prevInput).attr("type") + '" name="' + $(prevInput).attr("name") + countIncremented + '" data-count="' + countIncremented + '"/>';
$(br + inputElement + plusMinusButtons).insertAfter('.' + $(prevInput).attr("name") + ':last');
});
$('.glyphicon-minus-sign').on("click", function () {
prevInput = $(this).prev('input');
$(this).remove(prevInput).remove(this);
});
$("button").click(function () {
console.log("here");
x = $('#form').serializeArray();
$.each(x, function (i, field) {
console.log(field.name + ":" + field.value + " ");
});
I currently have a bit of JS which will generate buttons
Dynamically adding buttons means you have to approach events a little differently. You need to do the following:
$('body').on("click", '.glyphicon-minus-sign', function () {
...
}
$('body').on("click", '.glyphicon-plus-sign', function () {
...
}
Essentially, you are now listening to clicks on the body element, instead of the actual buttons (which might not actually exist yet). Any other statically created buttons aren't affected.

How to have Jquery blur trigger on everything except hyperlinks/input buttons

I'm having a slight issue getting a jquery action to function ideally. Currently everything is working properly on a blur from a particular field, which is called "person_email". The issue is that if the end user does this, and decides to click a hyperlink for example on the rest of the page that jquery from the blur triggers, the user see's this briefly, and then continues to the corresponding link.
Ideally this would work that the blur would only trigger if a hyperlink was not clicked.
var $email = $("#person_email");
var $hint = $("#hint_edit");
$email.on('blur',function() {
$hint.hide; // Hide the hint
$(this).mailcheck({
suggested: function(element, suggestion) {
// First error - Fill in/show entire hint element
var suggestion = "Did you mean: <span class='suggestion'>" +
"<span class='address'>" + "</span>" +
"<a href='#' class='domain'>" + suggestion.address +
"#" + suggestion.domain + "</a></span>?";
$hint.html(suggestion).fadeIn(150);
}
});
});
$hint.on('click', '.domain', function() {
// On click, fill in the field with the suggestion and remove the hint
$email.val($(".suggestion").text());
$hint.fadeOut(200, function() {
$(this).empty();
});
return false;
});
})
I assume you want off
$("a").on("click",function() {
$email.off();
});

Categories

Resources