onClick not called for button (html) - javascript

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

Related

Getting the value of attribute data-* in an inline function

I have a data attribute data-niq which i am using to store some data. I want to pass the data in *-niq to a function as a second parameter to a function.
This is the code
<button onClick="editevent(this.id,this.id.getAttribute('data-niq'));" id="mid" data-niq="niq" class="mr edit btn btn-success pull-right"> Edit</button>
<script>
function editevent(clicked_id,attri_bute){
console.log('clicked id',clicked_id);
console.log('data-niq',attri_bute);
}
</script>
and the link https://jsfiddle.net/codebreaker87/zob8dm4z/8/
When i run the code i get TypeError: this.id.getAttribute is not a function
How can i pass the data-niq value in the inline function that i am calling?.
Few things here
Never mix your mark up with javascript
Try to bind events in javascript end.
check the following snippet.
window.onload = function() {
var mid = document.getElementById("mid");
mid.addEventListener('click', function() {
editevent(this);
})
}
function editevent(thisObj) {
var id = thisObj.getAttribute('id');
var dataniq = thisObj.getAttribute('data-niq');
alert(id);
alert(dataniq);
}
<button id="mid" data-niq="niq" class="mr edit btn btn-success pull-right">Edit</button>
Hope it helps
you have added this.id.getAttribute('data-niq');
remove id
this.getAttribute('data-niq')

aJax update a specific row in sqlite and php using a button

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();

Strange behavior with a "confirm" modal jquery

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

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

Categories

Resources