What's easiest way to get value of a checkbox - javascript

what is the easiest way to get the value of a checkbox?
I create my checkboxes dynamically
function buildList() {
var output;
output = "<form><fieldset data-role='controlgroup' data-iconpos='right' id='fieldset_item'>";
if (codeCounter != 0 && codeCounter > 0 && codeCounter != null) {
for (var i = 0; i < codeCounter; i++) {
output += "<input type='checkbox' name='checkbox_" + i
+ "' id='checkbox_" + i + "'><label for='checkbox_" + i
+ "'>" + localStorage.getItem(i) + "</label>";
}
}
output += "</fieldset></form>";
$(output).appendTo("#fieldSet");
$('#fieldSet').trigger("create");
}
So how can i get the value of the each checkbox?

Having no value in the checkboxes you're generating, kind of made me feel you want the text inside the label tags, in case I was right:
var id = 'checkbox_1';
var checkboxLabel = $('label[for="' + id + '"]').html();

$('input[type=checkbox]:checked').val()

Related

search whether id consists of dynamic value

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

Insert "and" before the last element jquery

var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
'&nbsp' + ':' + '&#160' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!

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.

EventListener showing wrong target

I have the following JS code
var existingMenus = document.getElementsByClassName('multiSelectMenu');
for (var i = 0; i < existingMenus.length; i++) {
var existingMenu = existingMenus[i];
var existingMenuHTML = [];
var targetChildren = existingMenu.parentElement.nextElementSibling.children;
console.log(targetChildren)
// Here I'm adding +1 to the ID as it appears starting at zero with a styled checkbox does not work correctly
for (var x = 0; x < targetChildren.length; x++) {
if (targetChildren[x].selected) {
existingMenuHTML += '<li><input class="dropdown-input" type="checkbox" id="' + (x + 1) + '" data-label="' + targetChildren[x].textContent + '" checked="true"/><label class="multiLabel" for="' + (x +
1) + '"><span></span> ' + targetChildren[x].textContent + ' </label></li>';
} else {
existingMenuHTML += '<li><input class="dropdown-input" type="checkbox" id="' + (x + 1) + '" data-label="' + targetChildren[x].textContent + '"/><label class="multiLabel" for="' + (x + 1) +
'"><span></span> ' + targetChildren[x].textContent + ' </label></li>';
}
}
existingMenu.innerHTML += existingMenuHTML;
console.log(existingMenuHTML)
var inputs = existingMenu.children;
console.log(inputs);
for (var w = 0; w < inputs.length; w++) {
var input = inputs[w].children[0];
console.log(input);
input.addEventListener('click', function() {
console.log('--------------')
console.log(event)
var targetElement = event.target || event.srcElement;
console.log(targetElement);
var elementParent = targetElement.parentElement.parentElement.parentElement;
console.log(elementParent)
if (!elementParent.classList.contains('open')) {
elementParent.className += ' open';
}
var multiList = elementParent.nextSibling.querySelector('[value="' + targetElement.dataset.label + '"]');
console.log(multiList)
// Subtracting one to account for the plus one I added above
var inputId = targetElement.id - 1;
if (targetElement.checked == true) {
multiList.selected = "selcted";
} else {
multiList.selected = "";
}
console.log('--------------')
});
}
}
The code works correctly on the first instance of the multiPick but all others on page trigger the first multiSelectMenu items even though I was clicking on the 3rd multiSelectMenu on page.
Here is a screen shot of the console,
Here is a code pen, https://jsfiddle.net/6s3rc8d7/ When you click the 'label' and not the checkbox it has the same issue I am seeing.
The reason behind getting the different event.target in your fiddle is due to the below code snippet in your html.
<input class="dropdown-input" type="checkbox" id="1" data-label="English only">
<label class="multiLabel" for="1"><span></span> English only </label>
you can see that in the label element, you have the for attribute which contains the id of the input element. The functionality of for attribute is that the value of this identifies which form element a label is bound to. When you click on the label it will simulate the click event of the bounded element. This is why when you click the label , in your script the event.target is the input the label is bonded with.
More on for attribute you can read here. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
I was able to rework the code and added the EventListener to the label instead of the checkbox.

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