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

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

Related

Fetch results from json

I have a bootstrap live search for pixabay api. But I have a problem with results from pixabay.
For example, I want to search images with query flowers but its returning results when i start typing. I type flo and i have a images with tag flo.
At the end I have links to images with tag flow flowe and flowers.
How to prevent this situation?
$('#search').keyup(function(){
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(q);
$.getJSON(URL, function(data){
if (parseInt(data.totalHits) > 0)
$.each(data.hits, function(i, hit){
htmlData = '<div class="col"><img src="'+hit.largeImageURL+'" class="img-fluid" alt=""/></div>';
$('.modal-body').append(htmlData);
});
else
console.log('No hits');
});
});
How to load expected images dynamically into modal?
Also how to remove images when i remove few chars from search bar?
If i put flowers It load flowers into modal, but when i type cars I want to show only cars, not flowers and cars.
There's two things you need to do to fix this behaviour. The first is to 'debounce' the event so that the AJAX request is only made when typing has finished for a short delay, eg. 150ms. The second is to wipe all previous results from the UI before you add the latest ones. Try this:
var searchTimeout;
$('#search').keyup(function() {
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key=" + API_KEY + "&q=" + encodeURIComponent(q);
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
$.getJSON(URL, function(data) {
if (parseInt(data.totalHits) > 0) {
var htmlData = data.hits.map(function(hit) {
return `<div class="col"><img src="${hit.largeImageURL}" class="img-fluid" alt=""/></div>`;
});
$('.modal-body').html(htmlData); // note 'html()' here. It will overwrite all existing content
} else {
console.log('No hits');
}
});
}, 150);
});

How to differ inputs with same class?

I have one Button that duplicates this line to choose more products.
My Html:
<td>
<input type="hidden" class="cod_linha" name="cod_linha[]"style="width: 100%;" />
<input type="text" name="linha[]" class="linha" style="width: 100%;" />
</td>
The problem is, I have two functions that find the product and other that Fill all the fields that I want automatically, what I have to do to differ this filled field of the empty field ? I tried this:
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== ''){
Executes my function to fill the fields and to add a new line.
}
else{ }
And this too :
var counter = $(table).find("input.linha").length;
for(var i =0; i < counter; i++){
if($(table).find('input.linha').eq(i).val()== ''{}
But those codes don't fill the other empty line. see the imagem :
My code to fill the fields :
function preencherCamposProduto(obj) {
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== '' &&
$(this).find('input.ref').val()=== '' &&
$(this).find('input.material').val()=== '' &&
$(this).find('input.cor').val()=== '' &&
$(this).find('input.descricao_marca').val()=== ''){
$.ajax({type: "POST",
url: '/pedidoOnline/index.php/Pedidos/pesquisarCamposProduto',
async: false,
data: {
cd_cpl_tamanho: obj
},
dataType: 'json',
success: function(data) {
var linhaId = data[0].idLinha;
var linhaLabel = data[0].labelLinha;
var refId = data[0].idRef;
var refLabel = data[0].labelRef;
var corId = data[0].idCor;
var corLabel = data[0].labelCor;
var marcaId = data[0].idMarca;
var marcaLabel = data[0].labelMarca;
var materialId = data[0].idMaterial;
var materialLabel = data[0].labelMaterial;`
var table = $('#tabelaPedido');
$(table).each(function() {
$(this).find('input.cod_linha').val(linhaId);
$(this).find('input.linha').val(linhaLabel);
$(this).find('input.cod_ref').val(refId);
$(this).find('input.ref').val(refLabel);
$(this).find('input.cod_material').val(materialId);
$(this).find('input.material').val(materialLabel);
$(this).find('input.cod_cor').val(corId);
$(this).find('input.cor').val(corLabel);
$(this).find('input.id_marca').val(marcaId);
$(this).find('input.descricao_marca').val(marcaLabel);
});
}
});
chamaAdicionarCampo();
}else{
console.log('Entrei no else');
}
});
}
Thanks a lot.
I've read your code and wrote a sample code in jsfiddle, that does things that you are writing about. In my solution I use CSS selector #tabelaPedido tr:last to select the last added row, and then write values to fields in this row.
Hope this helps.
The following simple jquery solution may help you:
$(document).ready(function(){
$('.linha').each(function(){
if ($(this).val() == ''){
//Call Your fill input function $(this) as parameter
}
});
});
Checkout This DEMO
With the answer of #zegoline and #semsem I figure it out.. Now it's working ! I added $( "tr:last" ).find() to every field on my each function and the #table tr:last too... Thanks a lot !

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

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.

How can I use an autosave partial view on a page with multiple forms?

Extending the example found at Autosave in MVC (ASP.NET), I wanted to create a partial to reuse in my application. I have one view with a tabbed layout, and each tab has its own form, and this is causing problems, namely that every form tries to submit every time, and only the first timestamp in the document updates. I understand why this is happening, but I don't know how I can fix it.
Partial's cshtml:
<div class="form-group">
<label class="control-label col-lg-2" for=""> </label>
<div class="col-lg-10">
<span class="help-block" id="autosaveTime">Not Autosaved</span>
</div>
</div>
#{
var autosaveString = "'" + #ViewData["autosaveController"] + "'";
if (ViewData["autosaveAction"] != null && ViewData["autosaveAction"] != "")
autosaveString += ", '" + ViewData["autosaveAction"] + "'";
}
<script type="text/javascript">
$(document).ready(function () {
autosave(#Html.Raw(autosaveString));
});
</script>
Javascript:
//methodName is optional-- will default to 'autosave'
function autosave(controllerName, methodName)
{
methodName = typeof methodName !== 'undefined' ? methodName : 'autosave'
var dirty = false;
$('input, textarea, select').keypress(function () {
dirty = true;
});
$('input, textarea, select').change(function () {
dirty = true;
});
window.setInterval(function () {
if (dirty == true) {
var form = $('form');
var data = form.serialize();
$.post('/' + controllerName + '/' + methodName, data, function () {
$('#autosaveTime').text("Autosaved at " + new Date);
})
.fail(function () {
$('#autosaveTime').text("There was a problem autosaving, check your internet connection and login status.");
});
dirty = false;
}
}, 30000); // 30 seconds
}
I have 2 ideas on how to fix it, but not sure which is more maintainable/workable:
Give each form an id, and pass that to the partial/autosave function. Add the name to the autosavetime text block for updates, and to determine which form to serialize/submit.
Somehow use jquery's closest function to find the form where the autosave block was placed, and use that to do what I was doing explicitly with #1.
First, make the URL using your Razor helper's Html extension (dynamically piecing URLs like this in JavaScript is unnecessarily risky). Take that, and stuff it in a data attribute on the tab control like so:
<div class="tab autosave" data-action-url='#Html.Action("Action", "Controller")'>
<form>
<!-- Insert content here -->
</form>
</div>
Then, you'll want something like this ONCE -- do not include it everywhere, and remove the javascript from your partial completely:
$(function() {
// Execute this only once, or you'll end up with multiple handlers... not good
$('.autosave').each(function() {
var $this = $(this),
$form = $this.find('form'),
dirty = false;
// Attach event handler to the tab, NOT the elements--more efficient, and it's always properly scoped
$this.on('change', 'input select textarea', function() {
dirty = true;
});
setInterval(function() {
if(dirty) {
// If your form is unobtrusive, you might be able to do something like: $form.trigger('submit'); instead of this ajax
$.ajax({
url : $this.data('action-url'),
data : $form.serialize()
}).success(function() {
alert("I'm awesome");
dirty = false;
});
}
}, 30 * 1000);
});
});

Categories

Resources