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.
Related
I am trying to make a script that counts up to the entered number in an field in HTML and makes an unordered list of every integer preceding it and also display whether it is even or odd.
I've tried something like this
<script>
const inputEl = document.getElementById("input-el")
let ulEl = document.getElementById("ul-el")
let number = null
inputEl.addEventListener("click", function() {
let number = inputEl.value
console.log(number)
})
function printNumbers(){
for (let i = 0; i <= number; i++){
if (i % 2 === 0){
ulEl.innerHTML += "<li>" + i + ": Even" + "</li>"
console.log(i)
}
else {
ulEl.innerHTML = "<li>" + i + ": Even" + "</li>"
}
}
}
</script>
However the for loop gets stuck on 0, regardless of my input. Tried pushing i into a numbersArray but it always displayed 0
You haven't called the function. So this has to be triggered when the button is clicked right? So you should call the function inside the event listener and pass the input value as an argument,
inputEl.addEventListener("click", function() {
let number = inputEl.value
printNumbers(number);
});
And add the parameter to your function now,
function printNumbers(number){
for (let i = 0; i <= number; i++){
if (i % 2 === 0){
ulEl.innerHTML += "<li>" + i + ": Even" + "</li>"
console.log(i)
}
else {
ulEl.innerHTML = "<li>" + i + ": Even" + "</li>"
}
}
}
The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
I have an application using firebase which looks like this:
The tick boxes to the right hand side of each 'Book', when clicked, sends the value of the firebase object into a string as shown below:
When clicking these tick boxes, I would like the style of the box and content to change so they turn blue. I have added this piece of code into the on click event:
function select(data, book, key) {
//What I added
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
//
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
However, this only turns the first box blue. No matter which check box I click, the first one just changes to blue and the rest stay grey.
Here is the JS code which creates the checkbox icons and the JS to highlight the selected check boxes.
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
//This generates the 3 columns on the application page
for (var i = 0; i < 10 && i < list.length; i++) {
lis += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 10; i < 20 && i < list.length; i++) {
lis2 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 20; i < 30 && i < list.length; i++) {
lis3 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
};
//This creates the 3 icons of delete, clear and select.
function genLinks(key, bkName) {
var links = '';
links += '<i id="deleteBook" class="material-icons">delete</i> ';
links += '<i id="removeBook" class="material-icons">clear</i> ';
links += '<i id="selectBook" onclick="functionSelected()" class="material-icons">check</i>';
return links;
};
function del(key, bkName) {
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
//This is the function to select and insert the data into the string as well as highlight each checkbox
function select(data, book, key) {
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
refreshUI(list);
});
If anybody can help it will be much appreciated.
Thanks,
G
The only thing I can see is that you are using the same id tags for multiple different objects on the same page. If you use it at more than one place, use a class! You should never have more than one of the same id because you will be facing a lot of repeating problems..
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.
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);
}
}