I am trying to make a modal act like a confirm button. You click the button, a popup opens up and askes yes or no, if yes, stores some info in database, removes that item from the DOM then adds an item somewhere else. But, right now, if they click the confirm "yes", it runs the ajax call multiple times. I feel like it is running it for other places where data-express="yes" but I don't know why it could...shouldn't $(this) only be the button that is clicked? I don't see what in here would make it run more than one time.
The button -
<ul class="list-inline center-block">
<li><button type="button" class="btn btn-primary center-block express_button" data-confirm="yes" data-dismiss="modal">Yes</button></li>
<li><button type="button" class="btn btn-primary center-block express_button" data-confirm="no" data-dismiss="modal">No</button></li>
</ul>
JS
$('.snf_interest').on('submit', function(e){
e.preventDefault();
var id = $(this).find('input[name=resid]').val();
var ppcode = $('.placement_item_' + id + ' .pdcode' + id).text();
var ppdate = $('.placement_item_' + id + ' .pp_date').text();
var dcpname = $(this).find('input[name=dcpname]').val();
var dcpemail = $(this).find('input[name=dcpemail]').val();
var prefcom = $(this).find('input[name=prefcom]').val();
var ppid = $(this).find('input[name=ppid]').val();
var patientneeds = $('.placement_item_' + id + ' .patientneeds').text();
var dcphone = $('.placement_item_' + id + ' .dcphone').text();
var dcnote = $(this).find('input[name=notes]').val();
$('#express_interest_modal').modal();
//if(confirm('Are you sure you want to express interest in this patient')){
$('.express_button').on('click', function(){
console.log($(this));
if($(this).data('confirm') == 'yes'){
$.ajax({
// url: "/snf/express_interest",
type: "POST",
data: { 'ppid' : ppid,
'status' : status,
'dcpname' : dcpname,
'dcpemail' : dcpemail,
'prefcom' : prefcom
},
success:function(){
// $('#interest_modal').modal('show');
$('#panel-placement .panel-body').append('<ul class="list-group list-group-no-pad"><li class="list-group-item clearfix well well-sm"><label>'+ppcode+'| Posted: '+ppdate+'</label><form class="pull-right" action="http://dev.goodcareconnection.com/snf/" method="post"><input type="hidden" name="ppid" value="'+ppid+'"><div class="btn-group" role="group" aria-label="..."><input class="btn btn-sm btn-danger" type="submit" name="ppbutn" value="Hide This Patient"></div></form></li><li class="list-group-item clearfix"><div class="col-md-12"><label>Needs: <h5 class="patientneeds">'+patientneeds+'</h5></label></div></li><li class="list-group-item clearfix"><div class="col-md-4"><label>Posted by: <h5>'+dcpname+'</h5></label></div><div class="col-md-4"><label>Email: <h5>'+dcpemail+'</h5></label></div><div class="col-md-4"><label>Phone: <h5>(303) 570-9863 M: (303) 570-9863</h5></label></div></li><li class="list-group-item clearfix"><div class="col-md-6"><div class="form-group"><h5><label>Notes</label></h5><textarea id="ppnote35" class="form-control update_note" name="notes" readonly="">'+dcnote+'</textarea></div></div><div class="col-md-6"><form class="snf_interest"><button class="btn btn-danger btn-sm pull-right" name="submit">Remove Interest</button></form></div></li></ul>');
$('.placement_item_'+ppid).remove();
var number = $('.express_badge').html();
number = parseInt(number);
number = number + 1;
$('.express_badge').html(number);
var number = $('.bulletin_count').html();
number = parseInt(number);
number = number - 1;
$('.bulletin_count').html(number);
}
})
}
})
});
The problem stems from adding one event handler inside another event handler.
The first time submit is triggered...the express_button elements do not have a click handler that would do the ajax previously attached. It gets added in this first submit event
Clicking "Yes" should only do make one ajax request.
The next time submit is triggered it will add the same event handler again.
Now clicking "Yes" will run 2 instances of the event handler and make 2 requests.
Every submit will increment the number of requests made
A simple solution would be remove the click handler as soon as it gets used.
Beware though that if modal gets closed using methods other than the buttons the event handler will still be there and problem will persist
$('.express_button').on('click', function(){
$(this).off('click')
// other code
});
A better solution would be separate the submit and click handlers by storing the data that needs to be sent so it would be accessible when "Yes" is clicked
Related
I was writing a code to add 1 every time a button is pressed also the button is dynamically generated so are the table rows. the problem is i cant make the function work properly if there are second or third any other rows. I know the problem is that every button has the same class hence the count will always picks up where the other button left off.
$("form").submit(function(e){
e.preventDefault();
var name = $("input[name='name']").val();
$(".data-table tbody").append("<tr data-name='"+name+"' class='vote'><td>"+name+"</td><td><button class='but' id="+name+">VOTE</button></td><td><button class='btn btn-info btn-xs btn-edit'>Edit</button><button class='btn btn-danger btn-xs btn-delete'>Delete</button></td><td></td></tr>");
$("input[name='name']").val('');
});
// the code to count
let count = 1;
$("tbody").on("click", ".but", function(){
$(this).parents("tr").find("td:eq(3)").html('<span>'+count+'</span>');
return count++;
});
to be clear......
#1
Name button count
john 4
jane 0
#2 after one press of button on jane
Name button count
john 4
jane 5
i want to be able to count the number on Jane from 1 when pressed on her corresponding button
also i'm trying not to use any plugins
and Thank you for helping.
First replace
`<button class='but' id="+name+">VOTE</button> `
with
<button class='but' id="+name+" data-count="clicked-0">VOTE</button>
now your count code
$("tbody").on("click", ".but", function() {
let obj = $(this);
let clicks = obj.attr('data-count').replace('clicked-','');
clicks++;
obj.attr('data-count','clicked-'+clicks);
obj.parents("tr").find("td:eq(3)").html('<span>' + clicks + '</span>');
});
This is the div
<div class="col-lg-4 pre-scrollable" id="all-menus-div">
<h3 class="text-center">Tum menu listesi</h3>
<div class="list-group" id="all-menus-checkboxes" th:each="menu : ${allMenusList}">
<input th:id="${menu.id}" th:text="${menu.item}" th:value="${menu.item}" type="checkbox"/>
</div>
<button class="btn btn-success" disabled id="add-menus-to-role-btn" type="submit">Ekle</button>
</div>
<button class="btn btn-success" id="update-menus-for-role-btn" type="submit">Rolu guncelle</button>
</div>
it gets from model object.
This is the function of it for onchange:
$('#all-menus-checkboxes').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
it calls this function when I click the first checkbox only. And i can see only the log at this time. So, only button disabled becomes false only when i click the first one.
When i click others, nothing happens, no logs.
But when i click for example second one, then click first one, it shows 2 of them are selected.
Why is that?
Simple allMenuslist:
[MenuDTO{id=1, href='/check-deposit-money', menuName='Kontrol-Onay Ekranları', roles=[RoleDTO{id=1, name='ADMIN'}], iconName='null', item='Cüzdana Para Yükleme - Kontrol', className='null'}]
onchange event must to bind on the <input>.
bind event must to after <input> appended.
But your <input> like by dynamic generation, recommend use 'event delegation':
add class to <input>.
<input class="all-menus-checkboxes" />
use event delegation.
<script>
$('#all-menus-div').on('change', '.all-menus-checkboxes', function () { ... }
</script>
try this
$('#all-menus-checkboxes > input[type=checkbox]').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
My html fragmentRow is as below, which has a <a> and a
<a href="onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}">
<div class="col-md-4 pull-right">
<input type="button" class="btn btn-small btn-default btn-flat pull-right" value="${param.publishOrUnPublishValue}"
name="${param.publishOrUnPublishName}"
id="${param.publishOrUnPublishName}"
onclick="${param.publishOrUnPublishOnClick}"
data-val="${param.routeIdnpk}" style="margin-top: 6px;">
</div>
</a>
I am including fragmentRow.jsp like this
<jsp:include page="fragmentListRouteItem.jsp">
<jsp:param name="routeIdnpk"
value="${childRouteViewPojo.routeIdnpk}" />
<jsp:param name="publishOrUnPublishValue" value="Publish" />
<jsp:param name="publishOrUnPublishName" value="Publish" />
<jsp:param name="publishOrUnPublishOnClick" value="onPublish" />
</jsp:include>
And I have a ajax that is called onclick of the button
$('#unPublish').click(
function() {
var routeIdnpk = $(this).prev().val();
$.ajax({
type : "Get",
url : "unpublishRoute",
data : {
routeIdnpk : routeIdnpk
},
success : function(response) {
response = successAction(response);
},
error : function(e) {
ajaxGlobalErrorResponseWithTitleAndMessage("Unable to Unpublish",
"The unpublish operation failed, please try again");
}
});
});
When I click on the button, onLoadShowRoutesView gets called instead of $('#unPublish').click(
I have tried $('#unPublish').click( and onClick="unPublish", function unPublish() too. Still the href of <a> gets called. Is there a way to override the main div <a href> and instead call the caller of the button on click ?
I have read thru this, and other links too. But unable to find a fix for the issue.
Now I know I am missing something very basic here.
Edit 1 : I have tried
<div onclick="location.href='onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}';">
Still the onLoadShowRoutesView gets called even when I click the button
Edit 2 #zakaria-acharki : I also added
function onUnPublish () {
var routeIdnpk = $(this).prev().val();
$.ajax({
}) ;
}
function publish () {
var routeIdnpk = $(this).prev().val();
$.ajax({
}) ;
}
Yet same result
With help from #zakaria-acharki, What worked for me was the below. Some typos and 'ondblclick' with the parent div
1
$('#unPublish').click(
function() {
var routeIdnpk = $(this).val();
$.ajax({
});
$('#Publish').click(
function() {
var routeIdnpk = $(this).val();
$.ajax({
});
2
<button type="button"
class="btn btn-small btn-default btn-flat pull-right"
value="${param.routeIdnpk}"
name="${param.publishOrUnPublishName}"
id="${param.publishOrUnPublishName}" style="margin-top: 6px;">${param.publishOrUnPublishValue}</button>
3
<div
ondblclick="location.href='onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}';">
EDIT
$('#unPublish').click(
works only for the first button
$('button[name="unPublish"]').click(function(){
this worked for all the buttons
Today : I learnt the value of button[name="something"]
try edit your code a little bit like this
you can add your onclick function on your element or adding the function dynamically
I have a form which dynamically generates a table of attached (uploaded) files to the form. The last cell of each row is a delete button. That delete button when clicked executes this code:
Delete Button Clicked
$("td").on("click", ".btn-danger", function(event){
var rowID = "#"+$(this).attr("rowID");
var id = $(this).attr("id");
$("#confirmDelete").animate({top:'15%'}, 1000);
$("#confirmDelete").removeClass("hidden");
$("#confirmDelete").on("click", "#deleteFile", function(e){
var inn = document.thisItem.getInnovator();
var getInfo = inn.newItem("CSH_PLI_CommercialPartFiles", "get");
getInfo.setProperty("related_id", id);
getInfo = getInfo.apply();
var relatedID = getInfo.getProperty("id", "");
var thisRelated = inn.newItem("CSH_PLI_CommercialPartFiles", "delete");
thisRelated.setID(relatedID);
thisRelated = inn.applyAML(thisRelated.ToString());
var thisFile = inn.newItem("File", "delete");
thisFile.setID(id);
thisFile.apply();
$("#confirmDelete").animate({top:'-100%'}, 1000);
$("#confirmDelete").addClass("hidden");
$(rowID).hide();
});
$("#confirmDelete").on("click", ".btn-default", function (e){
$("#confirmDelete").animate({top: '-100%'}, 1000);
});
});
Which in turn brings into focus this bit of HTML, my confirmation window.
HTML
<div id="confirmDelete">
<div class="bg-danger">
<h4>Delete File Confirmation</h4>
</div>
<div>
<p><b>Delete this file? This action cannot be undone</b></p>
</div>
<div class="pull-right">
<button type="button" class="btn btn-default btn-sm">Cancel</button>
<button type="button" class="btn btn-danger btn-sm" id="deleteFile">Delete</button>
</div>
</div>
Now everything works fine enough. Cancel closes the popup. And delete, will actually delete the file from the server and remove it from the table in the form. However, as soon as delete is done, the popup will scroll up and then scroll back down as if it were called again.
I cannot figure out any combination of hides and removes which will actually stop this from happening.
I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();