How to use checkbox for DOM display toggle (with objects) - javascript

I'm writing in jquery/javascript and I'm stumped. I have an input form that creates objects in an empty array, each object is a band, containing the band name and some other info.
Once these objects are made, they're displayed on the site as a list like an address book, creating a master list. Each display of the band object has a serialized checkbox, with their id's being set to 0, 1, 2, and so forth as they get created with each form submit. You can submit one band at a time, and it will add them to the array in the order you create them.
First I have an empty array to hold all the bands:
var bands = []; // This is the overall list of bands that have been entered.
Then I use this following function to add to the DOM, listing the bands out with a serialized checkbox for the users to check.
var showBands = function() { // this function will add the bands to the DOM
$("#all-bands").empty();
var totalNumberOfBandsInAddressBook = 0;
bands.forEach(function(band) {
totalNumberOfBandsInAddressBook++;
$("#all-bands").append(
'<div class="band-list">' + "<div class='row'>" + "<div class='col.md-2'>"
+ "<input type='checkbox' class='BandContactCheckbox' id='" +
(totalNumberOfBandsInAddressBook-1) + "'></input></div>" +
'<div class="col-md-10"><b>' + band.BandName + '</b><br>' +
band.BandMainContactFirstName + ' ' +
band.BandMainContactLastName + ', ' +
band.BandEmail + ', ' +
band.BandPhone +
'</div>' + '</div>' + '</div>'
);
});
}
And finally I'm stuck here, trying to get get this thing to find each checked box, no matter the order, and list the bands upon check or uncheck on the website:
$('form#all-bands-form').click(function(event) { // this function will display the bands in the "Bands to Add" section dynamically with the checkboxes turned on or off
$("input:checkbox[class=BandContactCheckbox]:checked").each(function(band) {
var bandID = $("input:checkbox[class=BandContactCheckbox]:checked").getAttribute('id').val();
debugger;
$('span#bandListForShow').text('<li>' + bands[bandID].bandName + ' test1' + '</li>')
});
});
I'm pretty new to a lot of this, so full explanations are most helpful. Basically my intention with this last function here is to have a click event listener on the checkboxes which would toggle the display on or off depending on whether the box is checked. With the checkbox ID being serialized, I was hoping to use that ID number to sort through the array locations per checkbox ID, but I can't figure out how to get this 'each' method to grab the attribute value.

Inside the .each() loop, you should use the band variable (or this) to refer to the current element of the loop. If you use the selector again, you're referring to all the checked boxes.
You shouldn't use .val() after calling getAttribute(). getAttribute() returns the attribute's value already. Also, getAttribute() is a DOM method, not a jQuery method (the analogous jQuery method is .attr()). But you don't need any method, just band.id will get the ID.
To get all the bands that were checked you should be using .append() rather than .text(). .text() replaces the text of the element rather than appending to it; also, it doesn't parse HTML, it will show the <li> literally.
Before the loop that appends, you need to empty the element; otherwise you'll add to whatever was shown on the previous click.
$('form#all-bands-form').click(function(event) { // this function will display the bands in the "Bands to Add" section dynamically with the checkboxes turned on or off
$('span#bandListForShow').empty();
$(".BandContactCheckbox:checked").each(function(band) {
var bandID = band.id;
$('span#bandListForShow').append('<li>' + bands[bandID].bandName + ' test1' + '</li>')
});
});

Related

Enable/Disable an HTML Element With Dynamically Generated Names/Tags

I have a table in HTML where the ID is dynamically generated from a row counter:
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>"
+ "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>"
+ "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>"
+ "</tr>"
I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input.
Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding:
$(#maxAltitude).prop("disabled", true);
How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed.
I've tried jQuery and javascript but can't seem to find a good way to do this:
<option onclick="shapeSelect()" value="sphere">Sphere</option>
<option onclick="shapeSelect()" value="cylinder">Cylinder</option>
function shapeSelect() {
var shapeSelects = document.getElementsByName("shapeSelect");
var maxAlts = document.getElementsByName("maxAlt");
for(var i = 0; i < shapeSelects.length; i++) {
switch(shapeSelects[i].value) {
case "sphere":
maxAlts[I].disabled = True;
break;
case "cylinder":
maxAlts[i].disabled = False;
}
}
}
With the above code I get: SyntaxError: unexpected token: identifier whenever shapeSelect() is fired.
I've modified the code as follows:
<table class="myTable" id="myTable"></table>
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option value=\"sphere\">Sphere</option>"
+ "<option value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude_" + rowCount + "\"</td>"
+ "<td><input class=\"maxAltitudeInput\" type=\"text\" id=\"maxAltitude_" + rowCount + "\" disabled></td>"
+ "</tr>"
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
And still nothing happens when I change the shape selector dropdown.
EDIT:
Apologies on the naming mismatches. My dev machine is on an airgapped network and I was hand jamming the post here on Stack Overflow. The rowCount variable was being created and incremented in another function. I was trying to only put relevant code in the post for brevity.
I was missing a class from shapeSelector. That was the missing link. It works now!
jQuery actually makes this really easy by binding this to whichever element triggered an event.
For instance, instead of writing a generic function for when that value changes, you could use jQuery to bind an event listener to them:
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
You'll notice a few things in this snippet:
The element we are binding the listener to is the table, not the individual row. That's because the row is dynamic, and we don't want to have to keep adding listeners every time we add a row. Instead we add it to the parent which is stable, but then we specify that we are interested in its children that match ".shapeSelector"
The listener relies on class names, not IDs, since we want to match multiple copies of them, not just a specific one. So you'd need to add those class names or a similar way of matching more than one item
Inside the callback function that runs, you'll notice a couple uses of this. jQuery has bound that to the element that triggered the event listener, in this case, the <select> control. So when we use this, we have to think of it from that perspective. We can get its value by $(this).val(), we can find its parentt with $(this).parent(), etc. In this case, I'm travelling up to the nearest tr, then from there down to that tr's input that I want to disable. You'd need to adjust a little depending on your dom.
Also note that this is a DOM element, not a jQuery result. That's why when we want to run more jQuery commands on it, we have to put it in $() again.
That's how I'd approach it. We don't have your entire code here, so you'll have to adjust a bit, but hopefully that pushes you off in the right direction.
EDIT
To be honest, there were a lot of naming mismatches and things that didn't line up. For instance, you were attempting to append onto a tbody tag, but that tag didn't exist. You were using a rowCount variable, but didn' ever set that up or increment it. The select tag sill didn't have the class name you were trying to use.
I suggest you look at your code piece by piece, ask yourself what you're telling the browser to do, and then do that instruction in your mind to make sure the computer can do it.
HTML:
<table class="myTable" id="myTable"><tbody></tbody></table>
JavaScript:
var rowCount = 0;
function addRow(){
$('.myTable tbody').append(`<tr name="tableRow">
<td>
<select class="shapeSelector" id="shapeSelect_${rowCount}">
<option value="sphere">Sphere</option>
<option value="cylinder">Cylinder</option>
</select>
</td>
<td><input type="text" id="altitude_${rowCount}" /></td>
<td><input class="maxAltitudeInput" type="text" id="maxAltitude_${rowCount}" disabled></td>"
</tr>`);
rowCount++;
}
$('.myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
});
addRow();
addRow();
addRow();
https://jsfiddle.net/32vnjq81/

How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.
Second Scenario:
In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.
Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.
So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){
var allow_to_open_condiments_conditional = $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();
if(allow_to_open_condiments_conditional == 'Yes') {
$('.conditional_table_hidden_noun').hide();
$('.conditional_table_hidden_condiments').show();
$('table#noun_chaining_order tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_condiments = $(this).find('td.condi_section_id').text();
$("table#customer_table_update_chain_order tbody").html('');
$('#customer_modal_update_chain_order').modal('show');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#customer_table_update_chain_order tbody').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
},
error:function(response){
console.log(response);
}
});
}
else
{
}
});
So the question will be, How to stop appending multiple times once I force double click the table row?
I see simple solutions here.
When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
(button)to prevent it from another click.
Check your database for multiple records.
Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?

LocalStorage element not corresponding with visual element after moving

I created a note-taking front end page which saves the data from text field into the localStorage. The problem occurs when the user deletes one field using the Delete button, which corresopndents to DeleteT function.
For example if we have three textareas with id txt1, txt2, txt3 they apper with the sames names in the localStorage. After the user deletes for example txt2 using the Delete button, in the local Storage the left ones are txt1 and txt3 but on the next reload there are two textareas with id txt1 and txt2 because in the localStorage the number of textareas is saved by key AllNum. The data from txt3 in the localStorage should go to txt2 in the DOM on the page.
The problematic functions:
// Deletes textelemnt
function DeleteT(num) {
localStorage.removeItem("txt" + num);
localStorage.removeItem("h" + num);
console.log('del');
i=i-1;
var now = localStorage.getItem("AllNum");
if((now-1)<0){
now=0;
localStorage.setItem("AllNum", (0));
}else{
localStorage.setItem("AllNum", (now-1));
}
$("div.textarea" + num).remove();
}
//Loads all the text elemnts with a for loop until the number of areas is reached
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea' + i + '"><input onkeyup="save()" id="h' + i + '"></input><textarea onkeyup="save()" id="txt' + i + '"></textarea></br><button onClick="cut(txt' + i + ')" class="f b">Cut</button> <button onClick="copy(txt' + i + ')" class="f b">Copy</button> <button onClick="speak(txt' + i + ')" class="f b">Speak</button> <button onClick="download(' + i + ')" class="f a">Save</button><button onClick="textFull(' + i + ')" class="f">Fullscreen</button> <button onClick="DeleteT(' + i + ')" class="f">Delete</button> </div>');
document.getElementById('txt' + i).innerHTML = localStorage.getItem("txt" + i);
document.getElementById("h" + i).setAttribute('value', localStorage.getItem("h" + i));
}
}
}
https://codepen.io/abooo/pen/NoqOXX?editors=1010
To experience the problem create three textareas using the + button. Then Enter data in the them. After this delete the latter. Finally reload the page and make sure the two textreas appeared. You can see the data from the second one is missing replaced with null value. How to fix this issue?
The result
LocalStorage values
The value "AllNum" only stores total number of items; it does not contain any information about which items were there before reloading. So in first load, if you add 3 items and remove the 2nd, your local storage will have "AllNum" equal 2, and the next time it loads, your load() function will iterate from 1 to 2, looking for data of text1 and text2. That's why only 1st item displays correctly.
Another problem that you might notice after fixing the above issue is that the iteration is not good for unique id; a simple test can prove it: you add 3 items, remove the 2nd - now you have text1 and text3 in localStorage, and AllNum is 2. If you add one more, the newest item will have id as 3 and all its data will be written on top of the existing text3 and h3.
2 suggestion for your code:
Use something else as unique id instead of iteration number. Use Math.random(), for example.
Store all your unique ids in localStorage, not AllNum. Rewrite your code to add and delete unique ids from localStorage.
A small example of how to modify the 2 function add() and save():
function add() {
var newId = Math.random();
// your render logic here. Replace i with newId
save(newId);
}
function save(newId) {
localStorage.setItem("txt" + newId, document.getElementById('txt' + a).value);
localStorage.setItem("h" + newId, document.getElementById('h' + a).value);
var allIds = JSON.parse(localStorage.getItem('AllIds'));
allIds.push(newId);
localStorage.setItem("AllIds", JSON.stringify(allIds));
}

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

Printing JSON object with jQuery into html

I have a JSON object that looks like this:
var content = '[{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}]';
And I am trying to edit it with jQuery to display in my div tag with the id of content-view
here is my jquery:
$.each(content, function(t, l){
$('#view-content').appendTo('<div id = "' + l + '">' + t + '</div>');
});
For some reason on my jsFiddle, which is right here: http://jsfiddle.net/gAWTV/
It just comes up blank with the result. Does anyone have any ideas? I am stumped...
---EDIT---
What i would like to do is have everything output into its own div tags like this:
<div id="Apple">John Apple</div>
<div id="Patel">Kumar Patel</div>
<div id="Quinn">Michaela Quinn</div>
etc...
Your content is a string, not an array of objects.
You firstly need to store it as an array, so get rid of the single quotations marks.
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
Unless there is a reason you store it as a string? Then you need to parse it.
var content_object = JSON.parse(content);
Then you can run your code. However, I think you want to "stringify" your JSON. If that's the case you also need to swap t with l, because l is the object. Finally, you want to append, not appendTo. The latter appends the subject to the target you specify, not the other way round (so in your case appendTo appends #view-content to your div you've constructed, which doesn't work).
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + t + '">' + JSON.stringify(l) + '</div>');
});
JSFiddle
Final comment, I would use document fragments to build your list instead of appending the new divs to an existing one in the each loop - that improves performance.
After OP edit:
Change the last snippet to:
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + l.lastname + '">' + l.title + '</div>');
});
Updated JSFiddle
Try this:
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
$.each(content, function(t, l){
$('<div/>',{
id: l,
text:t }).appendTo('#view-content');
});
DEMO

Categories