incorrect array push and splice? - javascript

I am making an invite system. I am using ajax to load a list of search results. When an li is clicked I push the user's id into an array and append a checkmark to the li to let them know they were added to the list.
The push is working but the splice is not. Also when the list is empty the submit button does not return to its disabled state and original styling.
Lastly, when I search again (re-calling the ajax) it removes the appended checkmark. Is there a way with javascript to store which user was click on and retain the appended checkmark when they search for another name?
(^ when i load the results with ajax i check if a person is invited or not in my db i could do it so if they are already invited a click would delete from table..if not on li click i insert with an ajax and setTimeout on success.. do you think that would be a bad practice?)
Below is my html && script
HTML
<li class='inviteUser'>
<img src='$usersProfilePhoto' alt=''>
<h2>$usersname</h2>
<input type='hidden' value='$otherUserID'>
<span></span>
</li>
$(function(){
var inviteList = new Array();
$(document).on('click', '.inviteUser', function(){
var inviteUserID = $(this).children('input').val();
inviteList.push(inviteUserID)
$(this).children('span').append("<p class='remove'>✓</p>");
if(inviteList.length > 0) {
document.getElementById('imcSubmitButton').disabled = false;
$('#imcSubmitButton').css({'opacity':'1'});
} else {
document.getElementById('imcSubmitButton').disabled = true;
$('#imcSubmitButton').css({'opacity':'0.25'});
}
});
$(document).on('click', '.remove', function() {
inviteList.splice($(this).index(), 1);
$(this).remove();
});
});

The problem is that the indexes in inviteList don't correspond to indexes in the HTML. You should search for the element in inviteList that contains this item's userID, and splice that out.
$(document).on('click', '.remove', function() {
var userid = $(this).parent().siblings("input").val();
var index = inviteList.indexOf(userid);
if (index != -1) {
inviteList.splice(index, 1);
}
$(this).remove();
});
To solve your problem with remembering which users were invited, the code that processes the AJAX responsee can use:
if (inviteList.indexOf(userId) != -1) {
// Add checkmark
}
Things would be easier if inviteList were an object rather than array, using userids as keys.

Related

JQuery delete closest element from Firebase

So I append my chatbox with records from Firebase, but I would also like to delete those records. Now I am not a genious with JQuery and thus I would like to know what should be used. In the original example they use data-id's
//Delete when clicking element
jQuery('body').on('click', 'a#message', function() {
var $rec = $(this).closest('[data-reactid]');
var id = $rec.attr('data-reactid') || null;
if( id ) {
// Delete nested elements
$rec.find('[data-reactid]').each(function() {
ref.child($(this).attr('data-reactid')).remove();
});
// Delete record
ref.child(id).remove();
}
return false;
});
ref.on('child_removed', function (snapshot) {
$('ul.chat-messages').find('[data-reactid="'+snapshot.name()+'"]').remove();
});
This is the original example:
http://jsfiddle.net/katowulf/QnUpb/
My output is a bit else than the example, it is build as follow:
<ul class="chat-messages" data-reactid=".1.1.1.1">
<ul id="ulrecords">
<li id="limessage">[some message here]</li>
<li>[additional info for message</li>
</ul>
</ul>
Basically in the first 'li' i have a to activate the JQuery and when i click that delete button in the 'li', I want to delete the "ulrecords"
Hope anyone can help me with this

jquery check if string has been deleted from textarea and remove option from select

Hi I am using jquery to detect an # symbol been inserted into a textarea. When this is detected an ajax request is fired to the server to retrieve a list of users. A user would then click on the username and it will be appended to the textarea as follows and also added to a select so that I may notify the relevant users of this note;
$(document).on('click', '#fetchUsers li',function(e){
var username = $( this ).text();
var user_id = $( this ).attr('data-user-id');
$('textarea.addNote').val(function(_, val){return val + username; });
$(this).parent('ul#fetchUsers').html('');
$('#addAUsertoNote')
.append($("<option></option>")
.attr("value",user_id)
.text(username));
});
Now the problem I have is that if I delete the string #userone from the textarea this option value is in the options list but it shouldn't be. Does anyone know if and how it is possible check if a username has been deleted and remove this from the option group?
You can try this approach, add keydown event and each time check if each user is in textarea:
$('textarea.addNote').keydown(function() {
var self = $(this);
var note = self.val();
var users = $('#addAUsertoNote option').map(function() {
return $(this).text();
}).get();
users.forEach(function(user) {
if (!note.match("#" + user)) {
$('#addAUsertoNote option:contains(' + user + ')').remove();
}
});
});
Do you mean to exclude already clicked usernames from the next list of users?
I would extend the function that retrieves the list to scan the content of the textarea for #\w+ strings and disable any list options that match.
You could also look at the multi-select menus provided by Chosen: https://harvesthq.github.io/chosen/#optgroup-support

pre populate form data on page re load from the session storage

I have a HTML from to capture string data. I am saving those when I hit the save button via ajax. But the scope also includes saving the data on a sessionstorage once I focus out of the form field with the orange save button after it checks the value is not empty. The idea is to pre populate each form field with values stored in the session storage. Everything works fine but I just cant figure out the session storage part. The hard part is how to assign a unique key for each form field, and use that key to find and preload values in the field.
Here is my JS
$('.wrapper').remove()
function renderInput() {
var inputField = '<div class="wrapper"><input class="zoom-text-field" type="text" value=""/><span class="close">save</span></div>';
return inputField;
}
function hideZoomFiled(e, textData) {
$(e).parent().parent().children('.students-name-collection').val(textData);
console.log(textData)
$(e).parent().hide();
$('.students-name-collection').attr('disabled', false);
$(e).prop('disabled', false);
}
function disableInputField(obj) {
$('.students-name-collection').attr('disabled', false);
$(obj).attr('disabled', true);
}
$('.students-name-collection').on('focus', function () {
disableInputField(this);
$(this).next('.wrapper').focus();
$('.wrapper').remove();
$(this).parent().append(renderInput());
var textData = '';
$('.close').on('click', function () {
textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
});
$('.zoom-text-field').on('blur', function(){
if($(this).val() !== ''){
//save the value in the sessionstorage
//This is where I am getting lost
}
});
});
$('#submitForm').on('click', function(){
sessionStorage.clear();
})
// on page load read the session storage and pre fill the form fields
Here is my fiddle
http://jsfiddle.net/sghoush1/ykshgrxg/5/
Here is how you can handle this, as you pointed out the main problem here is how to figure out how to save each input item, and how to place it back when the page loads. What you can do is give each item an index, from 0 to 4.
To get the index of the element you are on, you can add an selected class to it, then use that class in order to find the elements position by using .index($('.selected')), of course we can remove that class when we are done with it. This can be used as the key for the sessionStorage, then the textData is the value:
// Get the index of the input item we are on
$(this).addClass("selected");
var key = $(".students-name-collection").index($('.selected'));
$(this).removeClass("selected");
$('.close').on('click', function () {
var textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
if(!!textData){
//save the value in the sessionstorage
sessionStorage.setItem(key, textData);
}
});
Then for loading them in you can use jQuerys .each and have that on the class .students-name-collection using an index of sessionStorage to give each input the correct value:
// on page load read the session storage and pre fill the form fields
$('.students-name-collection').each(function(index) {
if(sessionStorage[index])
$(this).val(sessionStorage[index])
});
Here is a Fiddle Example

ajax load should remain the status of my checkbox when checked [duplicate]

This question already has an answer here:
checked checkbox will remain through pagination
(1 answer)
Closed 8 years ago.
I have a problem here using .load() ajax/jquery when I use it in pagination. the status of my checkbox will not remain when I go to another page. For example I checked 2 items in page 1 then when I go to page 2 to select another item then when I go back to page 1 to test if my checked item remain checked. unfortunately it became unchecked maybe because of the .load(). Please help me if there is alternative to use aside .load() to remain my checkbox checked.
here is my code for .load() ajax:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');});
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active');
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$('body').on('click', '.paginate_click', function(e){
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
});
</script>
hi #charleshaa it doesnt work this is what i did to my script
and here is my checkbox code
echo "<div id='a'><input type='checkbox' class='tick' name='items[$i]' id='$i' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
What's wrong?? Im badly need help
You need to keep you checked boxes in a variable so you can recheck them after the load.
First add a class to your checkboxes class="tick".
Then you would :
$(".paginate_click").click(function (e) {
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
EDIT:
Also, it is preferable not to use the .click() notation, instead, you should always use .on()
In this example, you would write it like this :
$('body').on('click', '.paginate_click', function(e){
//code
});
It is much better for performance as it only attaches one event listener to body, instead of attaching one to every .paginate_click.
Check my comment about the unique IDs and you should be good to go.

Using JQuery detach and restore to filter a select list

http://jsfiddle.net/Ms9NY/
I'm using jquery and trying to use detach/prepend/append to dynamically remove and reinsert option items on a select.
Because hiding options does not work cross browser, the only way to really get it to function as needed is removing the options completely.
I can remove the items with detach but I'm lost on how to restore them later. I know I would need to add them to an array somehow but I can't figure out how to do that. How can I use an array to detach and restore only specifically matched items from the deleted list?
This is what I have been testing with:
$("#filter-specs-text").keyup(function(){
var searchString = $(this).val().toLowerCase();
$("#specs-excluded-select>option").each(function() {
var text = $(this).text().toLowerCase();
//found a match - show this entry
if ( text.indexOf(searchString) > -1 ) {
$(this).removeAttr("disabled");
$(this).prependTo("#specs-excluded-select");
}
//no match - hide this entry
else {
$(this).attr("disabled", "disabled");
$(this).detach();
}
});
Visual reference. The filter box is the text box noted by the arrow.
You could handle it like this instead:
--DEMO--
var $opts = $("#specs-excluded-select>option"); // keeping there all options
$("#filter-specs-text").keyup(function () {
var searchString = $(this).val().toLowerCase();
$("#specs-excluded-select").empty().append($opts); // append() to keep any data/events bound to options
$("#specs-excluded-select>option").each(function () {
var text = $(this).text().toLowerCase();
//found a match - show this entry
if (text.indexOf(searchString) > -1) {
$(this).prop("disabled", false);
}
//no match - hide this entry
else {
$(this).prop("disabled", true).detach();
}
});
});

Categories

Resources