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

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.

Related

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

prevent double click on button in javascript

<script type="text/javascript">
$(document).ready(function () {
$("#submit").on("click", function () {
$(this).attr('disabled', true);
var taskid = num;
var loadnew = 1;
var guessnum = $("input[name=guessnum]:checked").val();
if (guessnum != 1 && guessnum != 2) {
alert("You could not submit an empty answer");
loadnew = 0;
location.href = "/minions/peerprediction1.php";
}
else if (loadnew == 1) {
finishedTask += 1;
}
var starttime = $("#timestart").val();
var timecost = starttime;
$.ajax({
type: "post",
url: "GameMysql.php",
data: "taskid=" + taskid + "&guessnum=" + guessnum + "&effort=" + effort + "&finishedTask=" + finishedTask + "&time=" + timecost,
success: function (data) {
}
});
});
});
</script>
<form>
<a class="button" id="submit"><span>&#10003</span>Submit report</a>
</form>
I want to make sure the form with same answers do not submit twice, and disable the button, but it does not truly work. For I click it twice the finished task number increased by 2
I already see the answer here Prevent double submission of forms in jQuery
and tried, but still could not make it work
Use the button element, it will provide the functionality you are after. It can be styled to look like an anchor. Less issues trying to get it working as intended across all browsers.
$("#submit").on("click",function(){
$(this).attr('disabled', true);
console.log('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" id="submit"> <span>&#10003</span> Submit report</button>
You should use a button instead of an anchor, anchors dont support the disabled attribute
<button id="submit">Submit Report</button>

Identifying a Specific Button when Submitting AjaxForm(s)

I'm using Django and AjaxForm to submit a form(s) that adds an item to a user's "cart". I have multiple items listed on the page, each with it's own "add to cart" button. Upon clicking a specific "add to cart" button, I use Ajax to add the item to the user's "cart" and display it in their "cart" at the top of the screen. Users can also delete an item from their cart by clicking on a given item in the cart.
I would now like to change the appearance of the "add to cart" button once it has been clicked, but I am having trouble identifying only the specific button that was clicked (and not all of the 'add to cart' buttons). How can I identify which 'add to cart' button was clicked. I added an 'id' field to my html button and have been trying to use that but have been unsuccessful....??
I have tried many different things but either they are not working or I am putting them in the wrong spot. For example, I have tried:
$('.add-to-cart').on('click',function(){
var id = $(this).attr("id");
console.log("ID: ");
console.log(id);
});
And also:
var addButtonID;
$(this).find('input[type=submit]').click(function() {
addButtonId = this.id;
console.log("ID: ");
console.log(addButtonId)
)};
Any ideas on how I can find the specifc button that was clicked so I can update the button's appearance???
My html:
{% for item in item_list %}
<form class="add-to-cart" action="/item/add/{{ item.id }}/" method="post" enctype="application/x-www-form-urlencoded">
<ul>
<li style="display: block"><button class="addItemButton2" type="submit" id="{{ item.id }}">Add to Cart</button></li>
</ul>
</form>
{% endfor %}
My javascript:
function remove_form_errors() {
$('.errorlist').remove();
}
function show_hide_cart(){
var cart = $('#cart');
var message = $('#message');
if (cart.find('li').length >= 1){
cart.show();
continueButton.show();
message.hide();
}
else {
cart.hide();
continueButton.hide();
message.show();
}
}
function process_form_errors(json, form)
{
remove_form_errors();
var prefix = form.data('prefix'),
errors = json.errors;
if (errors.__all__ !== undefined) {
form.append(errors.__all__);
}
prefix === undefined ? prefix = '' : prefix += '-';
for (field in errors)
{
$('#id_' + prefix + field).after(errors[field])
.parents('.control-group:first').addClass('error');
}
}
function assign_remove_from_cart() {
var cart = $('#cart');
$('.remove-from-cart').on('click', function(e) {
e.preventDefault();
$.get(this.href, function(json) {
remove_form_errors();
cart.find('a[href$="' + json.slug + '/"]').parent('li').remove();
show_hide_cart();
});
});
}
(function($){
$(function() {
var cart = $('#cart'),
message = $('#message');
continueButton = $('#continueButton');
assign_remove_from_cart();
// ajax-enable the "add to cart" form
$('.add-to-cart').ajaxForm({
dataType: 'json',
url: this.action,
success: function(json, status, xhr, form) {
if (json.errors !== undefined) {
// display error message(s)
process_form_errors(json, form);
}
else if(json.id == -1){
// duplicate, do nothing
console.log("json.id:%s:json.slug:%s", json.id, json.slug)
}
else {
// Hide any previously displayed errors
remove_form_errors();
// compile cart item template and append to cart
var t = _.template($('#cart-item-template').html());
$('#cart').append(t(json));
show_hide_cart();
assign_remove_from_cart();
}
}
});
});
})(jQuery);
Based on your comments, you ought to be able to drop your onClick function into a script tag at the end of your HTML page and have it function as intended (though your javascript should actually all be in a separate file that gets referenced via a script tag).
$( document ).ready(function(){
$('.add-to-cart :submit').on('click',function(){
var id = this.id;
console.log("ID: ",id);
//do something with your ID here, such as calling a method to restyle your button
$('#' + id).css("attribute","new value");
//or
$('#' + id).addClass("yourClassName");
});
});
Change the button type to 'button', and then add onClick="addToCartFunction(this);"
then in the addToCarFunction, this.id will be your item id your adding?, or you can use data-attributes to add more item details for the function to get.
if you then need to send information to the server to cache the cart, use a $.ajax jQuery call to the server.

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

How can I delete the selected messages (with checkboxes) in jQuery?

I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});

Categories

Resources