jquery toggle only execute the first condition - javascript

This must be fairly simple for many of you. I wrote a function to select all checkboxes if user clicks on anchor tag (). However, on the first click the function select all checkboex but nothing happens when I click on the anchor tag again (it should deselect all the checkboxes again). Here is my JS function
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
.append($('<td />')
.append($('<a id="fieldSelectAll"/>')
.html(field)
.click(function() {
var els = document.getElementsByName(mainTableId + "_select" + i);
for (var j = 0; j < els.length; j++) {
if ($("#fieldSelectAll").toggle()) {
els[j].checked = true;
}
}
})) )
}
Edit 1:
So if I remove the anchor tag and replacing with a select all check box it works if I modify my function as follow:
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
// Create row with checkbox
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
// Create checkbox
.append($('<td/>')
.html(field)
.append($('<input type="checkbox" id="' + mainTableId + '_select' + i + '"/>'))
.click(function () {
var els = document.getElementsByName(mainTableId + "_select" + i);
for (var j = 0; j < els.length; j++) {
if ($("#" + mainTableId + "_select" + i).is(':checked')) {
els[j].checked = true;
} else els[j].checked = false;
}
}))
}
However, instead of using a 'checkall' checkbox, I simply need to toggle the checkall thing on anchor tag click. If that makes senses?

Use a variable to keep track of the state:
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
var allChecked = false;
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
.append($('<td />')
.append($('<a id="fieldSelectAll"/>')
.html(field)
.click(function() {
var els = document.getElementsByName(mainTableId + "_select" + i);
allChecked = !allChecked;
for (var j = 0; j < els.length; j++) {
els[j].checked = allChecked;
}
})) )
}

Related

How to return to the starting position in a dynamically rebuilt table after having followed a link from it?

I rebuild a table (tbody) from the local storage. When it is necessary, I rebuild the <a> tag to get a link to an image. Contrary to what happen normally, when returning from the linked document or image to the calling document containing the rebuilt table, the cursor position nor the scrollbar position is retained, and the table is re-positioned at the beginning (row 0, col 0). I would like that the user would not have to scroll again to find it starting position (with the link) in the table.
The problem is simple to explain and I already did it. By clicking to expand a small view of a table in order to get a full view of it on a new page, I have to dynamically rebuild this table from information in the localstorage: firstly call the function storeLocOeuvresTbl() in the origin page; secondly, the function getInventOeuvresTblFromStoreLoc() in the destination page. This can be done by clicking on the link according to the code here : Le contenu de cette table peut être trié en cliquant sur les entêtes de colonnes.
Veuillez suivre ce lien
Expand
pour agrandir la table sur une page séparée..
If I follow a link from a cell in the built table in the destination page and return to this page from any other document/page accessed through this link, the cursor and scrollbar positions are lost. I suppose having to specify some property/attribute.
Which property/attribute do I have to specify for a dynamically built table so that the table from which I followed the link, does not move to the initial pos (0,0) when I return from this link. If I have to specify a property to keep the position, at which level? Div, table contained in the div, tbody?
Whit a dynamically built table, the normal behavior is perturbed.
Here is a link to a test page simplifying this problem:
http://www.danielpisters.be/testTable.html
Click bellow the table and you get a full view of the table in
http://www.danielpisters.be/testExpandTestTable.html
Move right to the column header "tLink" (all the others are "Foo", "Bar"). Then move down in the column until you reach a cell with a link. Click on it and you will see an image on another page. Returning from it, the position on the cell containing the link is lost, becoming 0,0.
// Build the table from the origin document
<script type="text/javascript">
function storeLocOeuvresTbl()
{
var oTable = document.getElementById('myOeuvresTable');
var s = "";
var stopAlert = true;
if (oTable == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
var aTBODY = oTable.getElementsByTagName("tbody");
localStorage.setItem("myOeuvresTableTBlen", aTBODY.length);
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var aTR = aTBODY[i].getElementsByTagName("tr");
localStorage.setItem("myOeuvresTableTB" + i + "len", aTR.length);
for (var j = 0; j < aTR.length; j++)
{
var aTD = aTR[j].getElementsByTagName("td");
localStorage.setItem("myOeuvresTableTB" + i + "TR" + j + "len", aTD.length);
var aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTD.length; k++)
{
s = s + aTD[k].id + ": " + aTD[k].innerHTML + "|";
var tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
var innerHTML = "";
if (aTD[k].innerHTML.length > 0)
{
innerHTML = aTD[k].innerHTML;
}
else
{
innerHTML = " ";
}
localStorage.setItem(tdId, innerHTML);
innerHTML = localStorage.getItem(tdId);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
alert("innerHTML get: " + innerHTML);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
}
s = s + "\n";
}
}
return s;
}
// Rebuild onLoad of the destination document
<script type="text/javascript">
function getInventOeuvresTblFromStoreLoc()
{
var tbl = document.getElementById('myOeuvresTable');
var s = "";
var tdId = "";
var innerHTML = "";
var aTBODYlen = 0;
var aTRlen = 0;
var aTDlen = 0;
var stopAlert = true;
var arrEvent = new Array("onMouseOver", "onMouseOut", "onClick", "onDbleClick", "onMouseUp", "onMouseDown", "onFocus", "onBlur");
var DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
if (tbl == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
aTBODYlen = parseInt(localStorage.getItem("myOeuvresTableTBlen"));
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODYlen; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var tblBody = tbl.tBodies.item(i);
aTRlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "len"));
for (var j = 0; j < aTRlen; j++)
{
var row = document.createElement("tr");
aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTDlen; k++)
{
var cell = document.createElement("td");
tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
innerHTML = localStorage.getItem(tdId);
if (innerHTML.substr(0, 7).toLowerCase() == "<a href")
{
var link = document.createElement("a");
var indDblQuote1 = innerHTML.indexOf('"');
var indDblQuote2 = innerHTML.indexOf('"', indDblQuote1 + 1);
var indOf1 = innerHTML.indexOf(">");
var indOf2 = innerHTML.toLowerCase().indexOf("</a>");
var cellLink = innerHTML.substring(indDblQuote1 + 1, indDblQuote2);
var cellText = innerHTML.substring(indOf1 + 1, indOf2);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
var s = "innetHTML: " + innerHTML + "; " + "cellLink: " + cellLink + "; " + "cellText: " + cellText;
alert(s);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
link.setAttribute('href', cellLink);
link.appendChild(document.createTextNode(cellText));
cell.appendChild(link);
}
else
{
var cellText = document.createTextNode(innerHTML);
cell.appendChild(cellText);
}
row.appendChild(cell);
s = s + tdId + ": " + innerHTML + "|";
}
tblBody.appendChild(row);
s = s + "\n";
}
tbl.appendChild(tblBody);
}
return s;
}
</script>

Get Checked count in dynamic check boxes JavaScript

I'm using following code to design my screen dynamically according to the DB data.
function RefillUI(data) {
var html = "";
$.each(data,
function (i, item) {
$('#patientName').html(item.PatientName);
html += "<div class='col-md-3'> <div class='card'><div class='card_header'><h5>" +
item.DrugName +
"</h5></div><div class='card_body'>" +
"<div class='col-md-12'></div><ul class='col-md-6'><li class='bold'>Ref #</li><li class='bold'>" +
item.ReferenceNo +
"</li>" +
"</ul><ul class='col-md-6'><li class='center'>Refills</li><li class='fill'>1</li></ul>" +
"<table class='table table-bordered table-inverse'><tbody><tr><th>Prescriber</th><td>" +
item.PatientName +
"</td>" +
"</tr><tr><th>Last filled</th><td>Nov 14 2014</td></tr><tr><th>Next fill</th><td>Oct 16 2016</td></tr>" +
"<tr><th>Qty</th><td>" +
item.LastRefillQty +
"</td></tr><tr><th>Last Filled Dispensory</th><td>" +
item.LastRefillDispensory +
"</td></tr></tbody></table><form action='' class='cta center bold'>" +
"<label><input name='refill' type='checkbox' value='refill'>Refill</label></form></div></div></div>";
});
$('#refillcards').html(html);
}
Now I want to check how many check boxes are checked when click a button. How can I do this?
I know only answer in pure Javascript:
First, put this declaration at the top:
checkboxes = []; // No `var', it's global
This will initialize the stuff
function
init (n)
{
// n is the number of check boxes
checkboxes[0] = document.getElementById ('some-id');
checkboxes[1] = document.getElementById ('other-id');
// ...
checkboxes[n - 1] = document.getElementById ('different-id');
}
To check selection for a particular check box, do:
function
checkSelect (n)
{
if (n >= checkboxes.length)
{
throw "Index out of bounds: " + n;
}
return checkboxes[n].value;
}
Then, count all of then
function
count ()
{
var ret = 0;
for (var n = 0; n < checkboxes.length; n++)
{
if (checkSelect (n))
{
ret = ret + 1;
}
}
return ret;
}
var n = $( "input:checked" ).length;
you can replace input with a better selector if you want.

Get text and id from an li element on click with pure JS

I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.

Get full ID searching with a selector

I have a schedule made in a table. Each td has an id that start with "schedule" + dayofweek;
I mark when the schedule starts adding a class ".schedule_start".
I'm searching with a selector and i want to get the full id of the td's with the class "schedule_start"
here is my example:
for (i = 0; i < 7; i++) {
var tag1 = 'schedule-' + i + '-';
if($("td[id ^='" + tag1 + "']").hasClass("schedule_start"))
{
console.log(tag1);
// here i want to return the full id
}
}
You can instead do this:
$('td[id^=schedule].schedule_start').each(function() {
console.log(this.id);
});
try this:
for (i = 0; i < 7; i++) {
var tag1 = 'schedule-' + i + '-';
var $tag = $("td[id ^='" + tag1 + "']");
if($tag.hasClass("schedule_start"))
{
console.log($tag.attr("id");
// here i want to return the full id
}
}

Same name inserting again and again in the the dropdown list when click on tab button

I am using my function in onclick nav tabs event (when click on any tab this below function activates). I just want that no same name can twice be inserted into the dropdownlist. Below function is working just perfectly. I just need a check maybe like name.text != arr[i] something like that to prevent it to insert the same name twice in the list. Any help would be appreciated.
js:
<script>
$(".nav-tabs li").click
(
function()
{
var getnumber = document.getElementById("permanentno").value;
var getData = 'methodname=getList&no='+getnumber;
$.ajax
({
type: 'GET',
url: 'Dropdown List/List.php',
data: getData,
success: function(resp)
{
alert(resp); // names for example: mile,stone,
var arr = resp.split(",");
var list = $(".dropdownlist");
var html = "";
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
}
}
$(".dropdownlist").append(html);
}
});
}
);
</script>
You could keep track of the names with another array and IndexOf. Note that for IE<9 support you'll need a shiv to use it.
var names = [];
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0 && names.indexOf(name) == -1)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
names.push(name);
}
}
You can append options to the dropdownlist on the loop, and check repeated names using jQuery like:
var list = $(".dropdownlist");
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (name.length != 0 && !list.find("option[value='" + name + "']").length) {
var html = "<option value='" + name + "'>";
html += name;
html += "</option>";
list.append(html);
}
}

Categories

Resources