onclick registering for multiple buttons with the same class name - javascript

Right now when I click on a separate button that uses the class "btn-danger" it will get removed. How can I modify my functions to only remove anything when its related to the function being ran?
function UpdateTrash(wo)
{
jQuery.ajax({
type: "POST",
url: "functions/markTrash.php",
data: 'wo='+wo,
cache: false,
success: function(response)
{
//alert("Record successfully updated");
}
});
}
$("#dataTables-example").on('click', '.btn-danger', function () {
$(this).parent().parent().remove();
});
$("#dataTables-example2").on('click', '.btn-danger', function () {
$(this).parent().parent().remove();
});
Button:
<td><br><center><button type="button" name="trashButton1" class="btn btn-danger" onClick="UpdateTrash(<?php echo $orow['WorkOrder']; ?>);"/>Trash</button></a></center></td>
Other button:
<td><center>
<button type="button" name="rush1" class="btn btn-outline btn-danger" onClick="UpdateRush(<?php echo $orow['WorkOrder']; ?>);"/>Rush</button>
</center><br><center>
<button type="button" name="pool1" class="btn btn-outline btn-info" onClick="UpdatePool(<?php echo $orow['WorkOrder']; ?>);"/>RFP</button></a>
</center></td>

I assume the issue is in your jQuery selector.
$(this) -> <button></button>
.parent() -> <div></div>
Here is a working example. https://jsfiddle.net/gcLt9d8f/
HTML:
<div id="dataTables-example">
<button class='btn-danger'>
Button 1
</button>
</div>
<div id="dataTables-example2">
<button class='btn-danger'>
Button 2
</button>
</div>
JS (jQuery):
$("#dataTables-example").on('click', '.btn-danger', function () {
$(this).parent().remove();
});
$("#dataTables-example2").on('click', '.btn-danger', function () {
$(this).parent().remove();
});

Related

How to use same php function for different button clicks

Here is a simple PHP form with a button..
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){
$("#btnnew1").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
$.ajax({
url: 'test.php',
success: function(data) {
$("p").text(data);
}
});
}
});
});
And the test.php is as follows,
<?php
echo 'Button1 clicked'
?>
My question is how to modify my test.php if I have multiple buttons.
As an example,
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked);
If btnnew2 clicks--->echo("Button2 clicked);
If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex:
If btnnew1 clicks--->
sleep(5)
echo("Button1 clicked);
If btnnew2 clicks--->
sleep(15)
echo("Button2 clicked by user);
If btnnew3 clicks--->
sleep(35)
echo("Button3 clicked by user);
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don't like you may neglect it...
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box...
$(document).ready(function(){
$('.button').click(function(){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
var clickBtnValue = $(this).attr('name');
var fetchdata= 'testme.php',
data = {'action': clickBtnValue};
$.post(fetchdata, data, function (response) {
// Response div goes here.
alert("Updated successfully -"+response);
});
}
});
});
Finally change your testme.php as follows,
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'fcn1':
fcn1();
break;
case 'fcn2':
fcn2();
break;
}
}
function fcn1() {
echo 'Button1 clicked';
exit;
}
function fcn2() {
sleep(5);
echo 'Button2 clicked';
exit;
}
Set the name to each button:
Button 1
Send data using ajax:
Get button text using e.target.text and send using POST method.
$.ajax({
type: 'POST',
url: 'test.php',
data: { buttonTitle: e.target.name},
success: function(data) {
$("p").text(data);
}
});
php:
Inside php use $_GET to get the data which we send from the frontend.
if(isset($_POST['buttonTitle'])) {
$buttonTitle = $_POST['buttonTitle'];
echo $buttonTitle . " clicked";
}

Changing button class with JavaScript

When the below button is clicked it, the javascript code checks if the class is btn-default, which it is and the javascript changes the class from "btn btn-default" to btn btn-success, but when I click the button again it calls the javascript code below again even that the button class has been changed from btn-default.
code on page:
<div class=vote>
<button type="button" id="test" type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-thumbs-up"></span></button>
javascript:
$(".vote").find(".btn-default").click(function () {
button_id = this.id;
$.ajax({
type: 'post',
url: '/vote',
data: {
'_token': $('input[name=_token]').val(),
'word_id': button_id
},
success: function(data) {
if ((data.errors)){
$('.error').removeClass('hidden');
$('.error').text(data.errors.name);
}
else {
$('#'+button_id).removeClass('btn btn-default').addClass('btn btn-success');
}
This is happening because the event is still attached even after the class changes.
You can prevent this by making use of event delegation:
$(".vote").on('click', ".btn-default", function() {
console.log('clicked');
$(this).removeClass('btn-default').addClass('btn-success');
});
.btn-default {
background-color: blue;
}
.btn-success {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class=vote>
<button type="button" id="test" type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-thumbs-up">Thumbs Up</span>
</button>
<button type="button" id="test" type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-thumbs-down">Thumbs Down</span>
</button>
</div>

jQuery submit form normally or Ajax dependant on variable using FontAwesome buttons

I am using buttons for submit, as that is the only easy way to use fontawesome buttons. I detect which button was selected and place that value in a hidden field so that it is available in my Ajax routine.
This presents a problem, as one button requires a normal submit, as it goes to a script that creates a pdf.
The other conditions submit using Ajax. I attempted the following which, of course, will not work, as it creates a recursion loop.
Cannot figure a means to do this without creating a submit loop.
In Form:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<button type="submit" class="btn btn-success ClickCheck" id="Create" style="display:inline;"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Reset" style="display:inline;"> <i class="fa fa-times"> <span>Reset</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="SaveData"> <i class="fa fa-archive"> <span>Save Only</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Create-Save"> <i class="fa fa-archive"> <span>Create and Save</span></i></button>
jQuery Code:
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
});
$("#MyForm").on("submit", function(event)
{
event.preventDefault();
var Form = $('#MyForm');
var Valid = verify();
if(Valid)
{
if($('#Clicked').val() == "Create")
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
console.log(response);
}
});
}
}
});
});
The callback should be done from verify() , I've written an example .
var goIsWaiting=false;
var goIsActive=false;
function go(){
if(goIsActive)
adviseGoIsActive()
else{
console.log("Go Is Waiting !");
goIsWaiting=true;
}
}
function activate(){
//.. Doing some stuff here
if(goIsWaiting) adviseGoIsActive();
goIsActive=true;
}
function adviseGoIsActive(){
console.log("Go Is Active !")
}
<input type="submit" value="Go" onClick="go()">
<input type="submit" value="Activate Go Action" onClick="activate()">
The solution for this problem was simply to use links rather than <input> or <button>.
Here is the HTML:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<a class="btn btn-success ClickCheck" id="Create" href="javascript:void(0)"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></a>
<a class="btn btn-success ClickCheck" id="Reset" href="javascript:void(0)"> <i class="fa fa-times"> <span>Reset</span></i></a>
<a class="btn btn-success ClickCheck" id="SaveData" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Save Only</span></i></a>
<a class="btn btn-success ClickCheck" id="Create-Save" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Create and Save</span></i></a>
One of these buttons is a reset. Although you can define a <button> as type="reset", for consistency, as well as other reasons, I left that too as a link and, since the button id is part of my post, the Ajax script detects that and just returns a null, then used a jQuery reset to clear the form after the null Ajax call.
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#MyForm');
var Valid = verify(); // form verify function
if(Valid)
{
if(ButtonID == "Create") // Send to PDF script
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
// Do whatever here with response data
}
}
if(ButtonID == "Reset")
{
$('#MyForm').trigger("reset");
$('#Clicked').val('');
}
}
}
});
});

jquery button active desactive state

I have an issue with the following jQuery code:
I have 3 buttons, here is the code :
<button class="btn btn-lg btn-primary" id="valider" data-actionname="appliquer" disabled>ok</button>
<button class="btn btn-lg btn-primary" id="choisir" data-actionname="choose" disabled>choisir</button>
<button id="add" data-actionname="ajouteritems" class="btn btn-lg btn-primary">Ajouter</button>
and i want that when i click on ajouter item the button choisir become active and when i click on choisir the button ok become active here is my js code for now :
var boutton = function(bouton) {
$('#add').click(function() {
$('#choisir').removeAttr('disabled');
});
}
thanks it's not reloading anymore but it won't activated the choisir button do you guy have any idea why ?is it understandable tell me if not
thanks.
You can bind click event to button tag and active its previous button using below jquery :
$('button').click(function(){
var $prevButton = $(this).prev('button');
// check if previous button available
if($prevButton.length > 0)
$prevButton.removeAttr('disabled');
});
Demo
And put type="button" as chriz said
<button type = "button" class="btn btn-lg btn-primary" id="valider" data-actionname="appliquer" disabled>ok</button>
<button type = "button" class="btn btn-lg btn-primary" id="choisir" data-actionname="choose" disabled>choisir</button>
<button type = "button" id="add" data-actionname="ajouteritems" class="btn btn-lg btn-primary">Ajouter</button>
Reloading (caused by submit by the button) can be prevented by using preventDefault() on the event like this:
var boutton = function(bouton) {
$('#add').click(function(e) {
e.preventDefault();
$('#choisir').removeAttr('disabled');
});
}
jQuery API reference event.preventDefault()
Here is your solution:
var boutton = function(bouton) {
$('#add').click(function(e) {
$('#choisir').removeAttr('disabled');
e.preventDefault();
});
$('#choisir').click(function(e) {
$('#valider').removeAttr('disabled');
e.preventDefault();
});
}
boutton(); // You need this to initialize the function
// Otherwise, it will not work
And here is the demo
$(document).ready(function(){
//by default am making the two buttons disbled(choisir & ok)
$("#valider,#choisir").attr('disabled','disabled');
//when clicking on the Ajouter
$("#add").click(function(){
$("#choisir").removeAttr('disabled');
});
$("#choisir").click(function(){
$("#valider").removeAttr('disabled');
});
});
if you have placed your buttons in a form then you can try with this:
var boutton = function(e, el) {
if($(el).prop('id') === 'add'){
$('#choisir').prop('disabled', false);
}else if($(el).prop('id') === 'choisir'){
$('#valider').prop('disabled', false);
}
}
$('button').click(function(e) {
e.preventDefault();
boutton(e, this);
});
Fiddle in action
add type = button to your button like below, because default type of button is submit
<button type = "button" class="btn btn-lg btn-primary" id="valider" data-actionname="appliquer" disabled>ok</button>
<button type = "button" class="btn btn-lg btn-primary" id="choisir" data-actionname="choose" disabled>choisir</button>
<button type = "button" id="add" data-actionname="ajouteritems" class="btn btn-lg btn-primary">Ajouter</button>
u need to call your function like boutton();
var boutton = function(bouton) {
$('#add').click(function() {
$('#choisir').removeAttr('disabled');
});
}
boutton();
or simply use this code
$('#add').click(function() {
$('#choisir').removeAttr('disabled');
});
I guess need to put 'type="button"' on the button
<button type="button" yclass="btn btn-lg btn-primary" id="valider" data-actionname="appliquer" disabled>ok</button>
<button type="button" class="btn btn-lg btn-primary" id="choisir" data-actionname="choose" disabled>choisir</button>
<button type="button" id="add" data-actionname="ajouteritems" class="btn btn-lg btn-primary">Ajouter</button>
JS:
$('#add').click(function() {
$('#choisir').removeAttr('disabled');
});
$('#choisir').click(function() {
$('#valider').removeAttr('disabled');
});
Here is the fiddle sample

Get button id of a form in cshtml

I've two forms on the same page. On clicking any one of the buttons, both queries of the buttons are being submitted as I've used the function IsPost like if(IsPost){ //run queries}
Since both the forms are on the same page, on submission of any button, both the events of the two buttons are triggered.
I want to run separate queries on submission of each of the buttons.
In php, we used if(isset($_REQUEST['buttonname'])){ //run queries }.
Is there any such way, I can achieve the same in cshtml?
Update
What if I already have passed a value in the buttons?
Like for eg:
<div class="btn-group pull-right">
#{
var followersearchcommand = "SELECT * from follow where follow_followerid = #0 and follow_followingid = #1";
var followsearch = db.Query(followersearchcommand, follower_id, row.student_id);
}
#if(followsearch.Count > 0){
<button class="btn btn-primary" type="submit" name="unfollow_followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="unfollow_button" value="unfollow" title="Follow">UnFollow</button>
}
else{
<button class="btn btn-primary" type="submit" name="followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="follow_button" value="follow" title="Follow">Follow</button>
}
</div>
Assign to both buttons the same name and test their value:
#{
if (IsPost){
if(Request["button"] == "buttonA"){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="button" value="buttonA" />
<input type="submit" name="button" value="buttonB" />
</form>
Edited
If you want to have two distinct forms, you could use the IsEmpty() method:
#{
if (IsPost){
if(!Request["buttonA"].IsEmpty()){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="buttonA" value="buttonA" />
</form>
<form method="post">
<input type="submit" name="buttonB" value="buttonB" />
</form>
html:
<form id="a">
<button type="submit">Submit A</button>
</form>
<form id="b">
<button type="submit">Submit B</button>
</form>
javascript:
$(function(){
$("#a").submit(function(e){
e.preventDefault();
// Query A
alert('A');
});
$("#b").submit(function(e){
e.preventDefault();
// Query B
alert('B');
});
});
Demo
Edit:
You can make an ajax call to your controller's action:
$.ajax({
type: "POST",
url: "#Url.Action("actionName", "controllerName")",
data: { /* your data */ },
success: function (data, textStatus, jqXHR) {
// success
},
error: function (jqXHR, textStatus, errorThrown) {
// error
}
});
And in your controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult actionName(/* your data */)
{
var success = DoSomething();
if (!success)
{
throw new HttpException(500, "Server error!");
}
return Json("");
}
Something along those lines...
Hope this helps!

Categories