Changing button class with JavaScript - 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>

Related

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

getting a default value to display in a div

currently when the page loads the defualt value of 10 displays which is what I want like so:
the custom amount shows:
but if I type something in the custom area and then delete it no default value is displayed. As shown here:
How can I get 10 to show up even if the user deletes their custom amount. I basically want 10 to always show if the user doesn't enter an amount or click a another button
here is my js:
$(document).ready(function() {
$('#donation-amount').keyup(function() {
$('#display-amount').text($(this).val());
});
$( ".selectvalue" ).click(function() {
$('#display-amount').text($(this).val());
});
$(".buttons .btn").click(function(){
$(".buttons .btn").removeClass('active');
$(this).toggleClass('active');
});
$('#display-amount').text($('#default').val());
});
and my html:
<div class="choose-pricing">
<div class="btn-group">
<div class="buttons">
<button type="button" id="default" class="btn btn-default selectvalue hover-color active" value="10">10</button>
<button type="button" class="btn btn-default selectvalue hover-color" value="15">15</button>
<button type="button" class="btn btn-default selectvalue hover-color" value="20">20</button>
<input type="Custom" name="donation-amount" class="inpt-first form-control" id="donation-amount" onclick="if(this.defaultValue == this.value) this.value = ''" onblur="if(this.value=='') this.value = this.defaultValue" value="Custom">
</div>
<input type="hidden" name="donation-amount-value" id="donation-amount-value">
</div>
<div class="money-donate">
<div class="display-amount" id="display-amount">
</div>
</div>
</div>
any help would be appreciated!
You can do this
store default in global and then apply when value is empty.
var defaultValue = 10;
$('#donation-amount').keyup(function() {
if($(this).val()) {
$('#display-amount').text($(this).val());
} else {
$('#display-amount').text(defaultValue );
}
});
See in action here http://jsbin.com/guxukodace/edit?html,js,output

onclick registering for multiple buttons with the same class name

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

RoR: jquery file upload on submit form button

How do I make it so my submit button will upload the images?
<%= simple_form_for #project, html: { multipart: true, id: 'fileupload' } do |f| %>
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input type="file" name="photos[]" id='photo_upload_btn', multiple>
</span>
<button type="submit" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel upload</span>
</button>
<%= f.button :submit, class: "btn btn-primary pull-right" %>
<% end %>
<script>
$(function () {
'use strict'; //not even sure what this is for
$('#fileupload').fileupload({
});
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
</script>
Right now, when I upload an image, it'll show thumbnail preview and start button with a cancel button. I want to move the start button and have it all upload using the submit button.
Try below sample -
$('#fileupload').fileupload({
dataType: 'json',
add: function (e, data) {
$(".btn-primary").off('click').on('click', function () {
data.submit();
});
},
});

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

Categories