Get full ID searching with a selector - javascript

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

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>

Display element of array onclick

This code displays the content of JSON file by formatting every word into sentences and then into HTML. On mouseover, words become blue. On click they become red. The next thing I want to do is to display the translation of the words (already in the json array) onclick.
https://jsfiddle.net/ve64qvtm/
var json = [
[
["Peki", "Well"],
["nedir", "what"],
["bu", "it"],
...
]
];
var arr2 = [];
for (k = 0; k < json.length; k++) {
var arr = json[k];
arr2.push('<p>');
for (i = 0; i < arr.length; i++) {
if (arr[i][0].length == 1) {
arr2.push(arr[i][0]);
} else {
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
}
}
arr2.push('</p>');
}
document.getElementById("text").innerHTML = arr2.join('');
var words = [...document.getElementsByClassName("word")];
words.forEach(function(word) {
word.onclick = function() {
if (word.className == "clicked") {
word.className = 'notclicked';
}
if (word.className == "onmouse") {
word.className = 'clicked';
}
}
word.onmouseover = function onMouse() {
if (word.className != "clicked") {
word.className = 'onmouse';
}
}
word.onmouseout = function onMouse() {
if (word.className != "clicked") {
word.className = 'notclicked';
}
}
});
I have no idea how to do this as the text to display is a variable.
How am I supposed to do this?
How about using Twitter Bootstraps tooltip. Add jQuery, bootstraps JS and CSS; once all this is added you would need to edit the line
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
To something like
arr2.push(' <span class="notclicked word ' + i + '" data-toggle='tooltip' data-placement='top' title='YOUR_TRANSLATION_HERE'>' + arr[i][0] + '</span>');
EDIT 2 - Updated Link:
Here is a working example
Edit 3
I Would also add a bit of margin on top and bottom so that you don´t get unexpected behaviour from the tooltips, just because there is no space.

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.

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

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.

Categories

Resources