button change jquery javascript - javascript

Is there a way to change my button to "remove" if i clicked the "add to stay button"
Like when i click the add button it will load the data then it will be changed to remove button because it is already added.
and if i press the remove button how can it go back to "add to your stay" button? Here is my js code and My button code
$(document).ready(function() {
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if (id != '') {
$.ajax({
type: "POST",
url: "Pages/addonajax",
data: {
id: id
},
success: function(data) {
console.dir(data);
if (data) {
result = JSON.parse(data);
$("#test4>span").html(result[0]['name']);
$("#test5>span").html(result[0]['price']);
$("#test2>span").append(result[0]['price']);
} else {
$('#test1').append('no records found');
}
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="bookingroom">Total: PHP 2,750.00</h3>
<h5 class="addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200">ADD TO MY STAY</button>
here's the example fiddle
https://jsfiddle.net/j501fwb8/1/

It's much harder to maintain a single element that has to do multiple things based on some criteria. Instead I highly suggest using multiple elements with a Single Responsibility.
I'd also HIGHLY recommend reading Decoupling Your HTML, CSS, and JavaScript - Philip Walton (Engineer # Google)
My example would be something like:
$(document).ready(function() {
$('.js-btn-addon').on('click', function() {
var $this = $(this);
/// do whatever
var addonId = $this.data('addon-id');
$this.addClass('is-hidden');
$('.js-btn-remove[data-addon-id="' + addonId + '"]').removeClass('is-hidden');
});
$('.js-btn-remove').on('click', function() {
var $this = $(this);
/// do whatever
var addonId = $this.data('addon-id');
$this.addClass('is-hidden');
$('.js-btn-addon[data-addon-id="' + addonId + '"]').removeClass('is-hidden');
});
});
.is-hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "1">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "1">Remove</button>
<br/>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "2">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "2">Remove</button>
<br/>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "3">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "3">Remove</button>
<br/>

You can change the HTML of the element to say Remove by using:
$(".addons").html('Remove');
You will have to handle the onClick method functionality accordingly though. Or you can remove the button altogether and show a different one.

You can change text after ajax call and load data, also you can add class for remove process etc.
Note: here i remove your ajax call, just put .text() on ajax success when load data
$(document).ready(function(){
$(".addons").on("click", function(event) {
var _t = $(this);
if(_t.hasClass('remove')){
_t.removeClass('remove').text('ADD TO MY STAY');
} else {
_t.addClass('remove').text('Remove');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class = "bookingroom">Total: PHP 2,750.00</h3>
<h5 class = "addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200">ADD TO MY STAY</button>

You can use a class to mark the button once it has been used to add the item. Wrapping the execution code inside an if/else block lets you check whether the class exists so you can act accordingly.
See the comments in this suggested code:
$(document).ready(function() {
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if (id != ''){
// Tests which type of button this is (see below)
if(!this.classList.contains("isRemoveButton")){
/* Your ajax call for adding goes here */
// Changes the button text
$(this).text("REMOVE");
// Adds a class indicating which type of button this is
this.classList.add("isRemoveButton");
} else {
/* Different ajax call for removing goes here */
// Restores original button text
$(this).text("ADD TO MY STAY");
// Restores original classList state
this.classList.remove("isRemoveButton");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="bookingroom">Total: PHP 2,750.00</h3>
<h5 class="addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200" data-addon-id="1">ADD TO MY STAY</button>

$(document).ready(function(){
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if(id != '')
{
$.ajax(
{
type:"POST",
url : "Pages/addonajax",
data:{id:id},
success:function(data)
{
console.dir(data);
if (data) {
result = JSON.parse(data);
$("#test4>span").html(result[0]['name']);
$("#test5>span").html(result[0]['price']);
$("#test2>span").append(result[0]['price']);
}
else {
$('#test1').append('no records found');
}
}
});
}
$(this).hide();
$('.remove').show();
//and write a remove property which you want.
});
$('.remove').on("click", function(){
//write your property here for remove once.
$(".addons").show();
$(this).hide();
})
});

Related

Javascript $(var).html(data); not working

I'm currently using javascript to try and update a page with ajax. however, using .html to update the page with the parameter i pass in ends with no resulting changes. The html page is a grid of buttons and i'm trying to update the button being right clicked with the 'flaggedcell' img. I can sucessfully log the data that i'm trying to replace, however, in the line right below that, the .html function isnt doing anything.
Javascript:
$(function() {
console.log("Page is ready");
$(document).bind("contextmenu", function(e) {
e.preventDefault();
console.log("Right click. Prevent context menu from showing.")
});
$(document).on("mousedown", ".game-button", function(event) {
switch (event.which) {
case 1:
var buttonNumber = $(this).val();
console.log("Button number " + buttonNumber + " was left clicked");
break;
case 2:
alert('Middle mouse button is pressed');
break;
case 3:
event.preventDefault();
var buttonNumber = $(this).val();
console.log("Button Number " + buttonNumber + " was right clicked");
doFlag(buttonNumber);
break;
default:
alert('Nothing');
}
});
});
function doFlag(buttonNumber) {
$.ajax({
datatype: "json",
method: 'POST',
url: '/grid/flag',
data: {
"cellNumber": buttonNumber
},
success: function(data) {
// this data logs succesfully
console.log(data);
//this changes nothing
$("#" + buttonNumber).html(data);
}
})
}
data html:
#model MinesweeperASP.NET.Models.Cell
#{
//store image names in an array for more efficient code.
string[] imageNames = { "UnoenedCell.png", "green.png", "bomb.png", "FlaggedCell.png" };
int i = 0;
}
#if (!Model.isVisited && Model.isFlagged)
{
i = 3;
}
<button class="game-button" type="submit" value="#Model.rowNumber,#Model.colNumber" name="cellNumber" asp-controller="Grid" asp-action="HandleLeftClick">
<img class="game-button-image" src="~/img/#imageNames[i]" />
<div class="button-label">
#Model.rowNumber
,
#Model.colNumber
</div>
</button>
Developer tools output:
Page is ready
site.js?v=yEzTfLHBcae6F8YYH3SeJjYAxKx_gxgY8BqS9gC2o5c:24 Button Number 0,1 was right clicked
site.js?v=yEzTfLHBcae6F8YYH3SeJjYAxKx_gxgY8BqS9gC2o5c:42
<button class="game-button" type="submit" value="0,1" name="cellNumber" formaction="/Grid/HandleLeftClick">
<img class="game-button-image" src="/img/FlaggedCell.png" />
<div class="button-label">
0
,
1
</div>
</button>
site.js?v=yEzTfLHBcae6F8YYH3SeJjYAxKx_gxgY8BqS9gC2o5c:5 Right click. Prevent context menu from showing.
Your button is not having id attribute. Add the id attribute and check it.

adding dynamically input box but it should stop base on the criteria,,,

elow is the code i am using i am able to add new input box wen i click but it should stop adding based on the user input like no. of user-entered as 4 based on that add input box should stop
in below example:-$bookcount is user input field which comes from html input box
var i = 1;
if(i>$(bookcount))
{
$('#add').click(function()
{
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="title[]" </td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
}});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
**strong text** {
alert(data);
$('#add_name')[0].reset();
}
});
});
Couple of issues to note:
Assuming bookcount is found from $("#bookcount") then you'll need to get the .val() and convert it to a number (as "10"<"2")
Check against bookcount value inside the click event:
var i = 1;
var bookcount = $("#bookcount");
$('#add').click(function() {
if (i>(bookcount.val()*1)) {
// do nothing
return false;
}
i++;
$('#dynamic_field').append('<tr....
as you also have a remove function, don't forget to reduce i when removing
$(document).on('click', '.btn_remove', function(){
--i;
(in this case, I recommend something other than i, eg rowCount).
You can also do away with i (rowCount) by querying how many rows have been created dynamically:
var bookcountinput = $("#bookcount");
$('#add').click(function() {
var rows = $("#dynamic_field tr").length;
if (rows > bookcountinput.val()*1)
return;
$('#dynamic_field').append('<tr....
});

How do I get an element with a specific ID from getElementsByClassName?

EDIT: SOLVED. Thanks everyone!
I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!
$(document).ready(function() {
var anchors = document.getElementsByClassName('editButton');
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div>
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.
So your final code should be something like this:
$(document).ready(function() {
$('.editButton').click(function() {
console.log('innerHTML is:', $(this).html())
console.log('id is:', $(this).attr('id'))
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(this).value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
<button class="editButton" id="firstButton">button 1</button>
<button class="editButton" id="secondButton">button 2</button>
<button class="editButton" id="thirdButton">button 3</button>
<button class="editButton" id="fourthButton">button 4</button>
</div>
save the button with button = this when run the onclick function and use it
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
var button;
var anchor = anchors[i];
anchor.onclick = function() {
button = this;
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+ button.value +'</p><br>';
$("#records").html(string);
});
}
}
});
https://jsfiddle.net/x02srmg6/
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.
One simple way to resolve this issue is listed below.
<div id="records"></div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
//Wrap the function with an IIFE and send i value to the event listener
(function(anchor){
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
})(anchors[i]);
}
}
});
You can read more about this in JavaScript closure inside loops – simple practical example
In your code..
var id = anchor.value;
could be
var id = anchor.id;
but I recommend you to use event delegation
If you have a html like this
<div id="buttonArea">
<a class="editButton" id="1"/>
<a class="editButton" id="2"/>
<a class="editButton" id="3"/>
.......(so many buttons)
</div>
you can code like below.
$(document).ready(function(){
$('#buttonArea').on('click', 'a.editButton', function (event) {
var anchor = event.currentTarget;
$.ajax({
method: "GET",
url: "/testedit.php",
})
.done(function(data) {
var id = anchor.id;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
You can use getAttribute. Like:
var anchors = document.getElementsByClassName('editButton');
// Id of anchors
id_of_anchor = anchors.getAttribute("id");
Refs
EDIT
anchor.onclick = function() {
id_of_anchor = $(this).attr("id");
});
You have jQuery in your application, there is easier and more readable way to do it with jQuery;
$(document).ready(function() {
$(".editButton").each(function(a, b) {
$('#' + $(b).attr('id')).on('click', function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(b).attr('id');
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
});
});
});
Example: https://jsfiddle.net/wao5kbLn/

jquery get value of each button

I'm trying to get the value of each button, but what i get is the value of the first button. This is my content
<div class="my_btn">
<button id="id_button" value="page-1">Page One</button>
<button id="id_button" value="page-2">Page Two</button>
<button id="id_button" value="page-3">Page Three</button>
<button id="id_button" value="page-4">Page Four</button>
</div>
and this is my script
jQuery('.my_btn').on('click',function(){
var my_content = jQuery('#id_button').val();
var my_link = '<li>Link</li>';
if( !tinyMCE.activeEditor || tinyMCE.activeEditor.isHidden()) {
jQuery('textarea#content').val(my_link);
} else {
tinyMCE.execCommand('mceInsertContent', false, my_link);
}
});
Basically this is a wordpress function. I'm trying to add different links inside the textarea box.
Thanks in advance
Apply the event listener to the buttons instead of the wrapper, then get the value with this.value.
jQuery('.my_btn button').on('click',function(){
var my_content = this.value;
var my_link = '<li>Link</li>';
if( !tinyMCE.activeEditor || tinyMCE.activeEditor.isHidden()) {
jQuery('textarea#content').val(my_link);
} else {
tinyMCE.execCommand('mceInsertContent', false, my_link);
}
});
Also, you should use unique values for each id attribute. While it won't effect this script, if you try to select by id then it will only affect the first element with that id.
jQuery('.my_btn button').on('click',function(){
var my_content = this.value;
alert(my_content);
/*var my_link = '<li>Link</li>';
if( !tinyMCE.activeEditor || tinyMCE.activeEditor.isHidden()) {
jQuery('textarea#content').val(my_link);
} else {
tinyMCE.execCommand('mceInsertContent', false, my_link);
}*/
});
<div class="my_btn">
<button id="id_button_1" value="page-1">Page One</button>
<button id="id_button_2" value="page-2">Page Two</button>
<button id="id_button_3" value="page-3">Page Three</button>
<button id="id_button_4" value="page-4">Page Four</button>
</div>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
first off id_button should be a class because it is on multiple elements
second your first jquery command should look like this, this way it will handle the button click and get the correct value
jQuery('.my_btn').on('click', '.id_button',function(){
var my_content = $(this).val();
var my_link = '<li>Link</li>';
if( !tinyMCE.activeEditor || tinyMCE.activeEditor.isHidden()) {
jQuery('textarea#content').val(my_link);
} else {
tinyMCE.execCommand('mceInsertContent', false, my_link);
}
});

Clone form input and clear value

I'm trying to create an upload form. It's working well so far and i'm trying to sort out a couple of bugs that I dislike.
The line that I seem to be having trouble with is
$(element).find(">:first-child").attr("value", "");
When cloning the form, it clones the div and replaces the value with nothing leaving a blank form, this works well, if I were to delete that line I would get the previous form's value, so it would be nice for a blank form to show.
The issue i'm having is when you delete a form all the forms values delete, What I want is when you delete a form, leave the value alone for the other forms.
Here's a fiddle http://jsfiddle.net/d77pd/1/ or see code below
HTML
<button class="clone">Add an Image</button>
<div id="upload_image_sets">
<div id="clonedInput1" class="clonedInput">
<input type="text" id="upload_image_link_1" class="image" size="36" name="hero_options[upload_image_link_1]" value="' . $hero_options['upload_image_link_1'] . '" />
<input id="show_upload_image_link_button_1" class="button upload_images" type="button" value="Upload Image" />
<button class="remove">Remove</button>
</div>
</div>
JavaScript
function updateClonedInput(index, element) {
$(element).appendTo("#upload_image_sets").attr("id", "clonedInput" + index);
$(element).find(">:first-child").attr("id", "cs_product_menu_img_src_" + index);
$(element).find(">:first-child").attr("name", "hero_options[upload_image_link_" + index + "]");
$(element).find(">:first-child").attr("value", "");
$(element).find(">:first-child").next().attr("id", "cs_product_menu_img_src_" + index + "_button");
displayRemove();
}
function displayRemove() {
if ($('.clonedInput').length === 1) {
$('.remove').hide();
} else {
$('.remove').show();
}
}
displayRemove();
$(document).on("click", ".clone", function (e) {
e.preventDefault();
var cloneIndex = $(".clonedInput").length + 1;
var new_Input = $(this).closest('.clonedInput').length ? $(this).closest('.clonedInput').clone() : $(".clonedInput:last").clone();
updateClonedInput(cloneIndex, new_Input);
});
$(document).on("click", ".remove", function (e) {
e.preventDefault();
$(this).parents(".clonedInput").remove();
$(".clonedInput").each(function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement);
})
});
Clone the form a few times, if you delete any form apart form the 1st one with the content, you'll notice the first form's content deletes, I want this left alone.
First approach:
call $(element).find(">:first-child").attr("value", ""); after calling updateClonedInput(cloneIndex, new_Input); from add function.
Working Demo First approach:
Second Approach:
I have modified some code. pass one more bool argument in function updateClonedInput.which will be set true when added and set false when dom is removed.This will prevent the value getting replaced on remove function:
function updateClonedInput(index, element,param) {
$(element).appendTo("#upload_image_sets").attr("id", "clonedInput" + index);
$(element).find(">:first-child").attr("id", "cs_product_menu_img_src_" + index);
$(element).find(">:first-child").attr("name", "hero_options[upload_image_link_" + index + "]");
if(param)
$(element).find(">:first-child").attr("value", "");
$(element).find(">:first-child").next().attr("id", "cs_product_menu_img_src_" + index + "_button");
displayRemove();
}
function displayRemove() {
if($('.clonedInput').length === 1) {
$('.remove').hide();
} else {
$('.remove').show();
}
}
displayRemove();
$(document).on("click", ".clone", function(e){
e.preventDefault();
var cloneIndex = $(".clonedInput").length + 1;
var new_Input = $(this).closest('.clonedInput').length ? $(this).closest('.clonedInput').clone() : $(".clonedInput:last").clone();
updateClonedInput(cloneIndex, new_Input,true);
});
$(document).on("click", ".remove", function(e){
e.preventDefault();
$(this).parents(".clonedInput").remove();
$(".clonedInput").each( function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement,false);
})
});
Working Demo Second Approach
An alternate solution that creates a blank clone from the first element once, then uses this every time a new row is required. It also uses CSS to hide/show the Remove button based on the fact that you only need Remove buttons on all rows unless it's the only child.
Disclaimer: I have removed the id manipulation as I am unsure if you really need it. I can update if necessary.
Demo
HTML
<button class="clone">Add an Image</button>
<div id="upload_image_sets">
<div class="clonedInput">
<input type="text" class="image" size="36" name="hero_options[upload_image_link_1]" value="an initial value" />
<input class="button upload_images" type="button" value="Upload Image" />
<button class="remove">Remove</button>
</div>
</div>
CSS
.clonedInput .remove {
display:inline-block;
}
.clonedInput:only-child .remove {
display:none;
}
JavaScript
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
var $blankClone = $('.clonedInput').clone();
resetForm($blankClone);
$(document).on('click', '.clone', function(e) {
e.preventDefault();
$blankClone.clone().appendTo('#upload_image_sets');
});
$('#upload_image_sets').on('click', '.remove', function(e) {
e.preventDefault();
$(this).closest('.clonedInput').remove();
});
resetForm() borrowed from Resetting a multi-stage form with jQuery

Categories

Resources