Why are my checkboxes not remaining ticked? [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?
(3 answers)
Closed 2 days ago.
I have been trying to create a completion tracker where I can use checkboxes to track tasks I have to do. I would like the checkboxes to remain checked. However the only place where I can get this to happen with my current code is in codepen.io . When I open with live server or open in browser using the extensions in vscode, it has not remembered that I have checked the boxes. How can I fix this?
This is my javascript file (app.js):
let boxes = document.getElementsByClassName('box').length;
function save() {
for(let i = 1; i <= boxes; i++){
var checkbox = document.getElementById(String(i));
localStorage.setItem("checkbox" + String(i), checkbox.checked);
}
}
//for loading
for(let i = 1; i <= boxes; i++){
if(localStorage.length > 0){
var checked = JSON.parse(localStorage.getItem("checkbox" + String(i)));
document.getElementById(String(i)).checked = checked;
}
}
window.addEventListener('change', save);
And this is the html file:
<script src="app.js"></script>
<input type="checkbox" id="1" class="box">checkbox1</input><br>

Related

Passing a value into onclick anonymous JavaScript function [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
Objective: Have multiple "Full Product Specifications" buttons that need to toggle the visibility of their respective Product Specification Tables. Initially, set all Product Specification tables to NOT display, then use the buttons to control. Cant use jQuery because ... reasons/stupid old website I don't have full control over...
I'm trying to use an anonymous JavaScript Function, but I'm unsure how to pass in my table? Or if I even can? My JS is not that great...
With jQuery I could probably just use .click() and .closest(). Unsure how to translate into pure JavaScript, so this is what I have instead.
The error...
Uncaught TypeError: Cannot set property 'display' of undefined at HTMLButtonElement.y.(anonymous function).onclick
And the code...
var x = document.getElementsByClassName("pdp-full-specs-table");
console.log("There are " + x.length + " tables");
for(i = 0; i < x.length; i++){
x[i].style.display = "none";
}
var y = document.getElementsByClassName("pdp-full-specs-toggle");
console.log("There are " + y.length + " toggles");
for(i = 0; i < y.length; i++){
var pdpTable = x[i];
y[i].onclick = function(pdpTable){
// Make this a toggle later
pdpTable.style.display = "table";
}
}
And the HTML in case that helps anyone
<button type="button" class="btn btn-link pdp-full-specs-toggle">Full Specifications ›</button><br>
<table class="pdp-full-specs-table">
<tr>
<td>Product Size</td>
<td>some size</td>
</tr>
</table>
A simple, efficient solution is just to store the index of each element on the element itself so that when the handler is invoked, you can reference it via the this reference to the element.
for(var i = 0; i < y.length; i++){
y[i].__table__ = i;
y[i].onclick = buttonHandler;
}
function buttonHandler() {
x[this.__table__].style.display = "table";
}
Some may use closures and such to accomplish this, but there's no need to be so complicated.
If each button comes just before each table, then you could do this.nextElementSibling to get to the table, but that won't work in IE8 and lower.

Vanilla JavaScript bind a mouseout event [duplicate]

This question already has answers here:
Add event handler to HTML element using javascript
(3 answers)
JS li tag onclick not working on IE8
(1 answer)
Correct usage of addEventListener() / attachEvent()?
(2 answers)
Closed 5 years ago.
NO JQUERY!!!!!!
I need to write this in pure JS. I have a bunch of elements in a calendarr timeline, some are linked by invoice_id so I want to add a hover class to all the matching class elements when the mouse is hovered over one, and then remove the hover class on mouse out.
I have the on mouse over part all working fine, but am struggling to get the mouse out event to work.
here is my JS:
function highlightRange(id)
{
var d = document.getElementsByClassName('invoiceCell' + id); // get all the elements
d.className += "hover"; // add the hover class
for (var i = 0; i < d.length; i++) { // remove the hidden class
d[i].classList.remove('hidden');
}
// now how to I bind the mouseout event??
}
I have a similar script running jQuery that does exactly this, but in this scenario I cannot use jQuery.
The jQuery version looks like this:
function highlightRange(id)
{
$(".price_cell_"+id).addClass('hover');
$(this).bind("mouseout", function(){
$(".price_cell_"+id).removeClass('hover');
})
}
EDITED after response:
function highlightRange(id)
{
var d = document.getElementsByClassName('invoiceCell' + id); // get all the elements
d.className += "hover"; // add the hover class
for (var i = 0; i < d.length; i++) // remove the hidden class
{
d[i].classList.remove('hidden');
d[i].on('mouseout', function(){
d[i].classList.remove('hover');
d[i].className += "hidden";
});
}
}
Is that what you're looking for?
object.addEventListener("mouseout", function(){
...
});

JavaScript onclick event on elementByClassName [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 7 years ago.
I have following mark up and I am trying to run a javascript function once clicked. So far I haven't faced any success. Plz help -
<div class='color-bar'></div>
<div class='color-bar'></div>
<div class='color-bar'></div>
<div class='color-bar'></div>
var ColorBars = document.getElementsByClassName("color-bar");
var charts = $("#line-container").highcharts();
var series;
var colorIndex = new Array();
for(var i = 0; i < ColorBars.length; i++){
ColorBars[i].onclick = function(){
hideColor(i);
}
}
function hideColor(index){
var charts = $("#line-container").highcharts();
var series = charts.series[index];
if(series.visible){
series.hide();
}
else{
series.show();
}
}
The problem I am having is figuring out which color-bar user has clicked. Is it first one, 2nd or 3rd. Based on this I need to fire the hideColor function.
Thanks a lot. Best regards, jahid
You need to give you colorbars ids:
<div class='color-bar' id="colorbar1"></div>
<div class='color-bar' id="colorbar2">></div>
<div class='color-bar' id="colorbar3">></div>
<div class='color-bar' id="colorbar4">></div>
And then you can check with:
ColorBars[i].id == X

Javascript concept for variable scope [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
adding 'click' event listeners in loop [duplicate]
(5 answers)
Closed 7 years ago.
I have 5 buttons and I can not change DOM and can not use id and name attribute and cant use innerHTML and now I need to give output like when I click button 1 it should give a alert like "You click button # 1" and same will continue for all 5 buttons. I want to print the value of i .Now I got stuck as I have two solutions :
HTML Part:
//creating 5 buttons
<button>one</button>
<button>two</button>
<button>three</button>
<button>four</button>
<button>five</button>
1st Solution:
/* here I am always having you clicked element #5*/
var nodes = document.getElementsByTagName('button');//getting references
var counter;
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
alert('You clicked element #' + i);
});
} //which is not working
2nd Solution:
/* here I am getting correct output*/
var nodes = document.getElementsByTagName('button');
var counter;
for (var i = 0; i < nodes.length; i++) {
assignEvent(nodes[i], i);
}
function assignEvent(node, i){
node.addEventListener('click', function(){
alert('You clicked element#' + (i+1));
});
}//this one is working
Now my question is why Solution 2 is working but solution 1 doesn't.. Please help. Why solution 2 is carrying the value of i correctly, while not solution 1.
If you don't want to create an additional function, just wrap the event listener assignment within a self-invoking anonymous function to which you pass 'i':
var nodes = document.getElementsByTagName('button');
var counter;
for (var i = 0; i < nodes.length; i++) {
(function(j) {
nodes[i].addEventListener('click', function() {
alert('You clicked element #' + (j+1));
});
})(i);
}
jsfiddle here: http://jsfiddle.net/vu31aa7y/
In your first solution when you add the anonymous function as parameter of addEventListener, the alert message is looking for the last value of i in this case i=5, that happens because you don't have the variable as local in the function, so your onlye possible value if the global variable.
If you want to do that try this:
var nodes = document.getElementsByTagName('button');//getting references
function alertMessage(i){
alert('You clicked element#' + (i+1));
}
for (i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', alertMessage.bind(null,i) , false);
}
Also I recommend you this lecture
You can write this:
[].forEach.call(document.getElementsByTagName('button'),
function(elt, index) {
elt.addEventListener('click', function() {
alert('You clicked element #' + (index + 1));
}, false);
});

how to get selected radio button from radiobuttonlist in javascript [duplicate]

I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:
var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;
("answer" is being returned as "undefined")
Please forgive my JavaScript ignorance, but what am I doing wrong?
Thanks in advance.
ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-
var list = document.getElementById("radios"); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
selected = inputs[i];
break;
}
}
if (selected) {
alert(selected.value);
}
Try this to get the selected value from the RadioButtonList.
var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
I always View Source. You will find each radio button item to have a unique id you can work with and iterate through them to figure out which one is Checked.
Edit: found an example. I have a radio button list rbSearch. This is in an ascx called ReportFilter. In View Source I see
ReportFilter1_rbSearch_0
ReportFilter1_rbSearch_1
ReportFilter1_rbSearch_2
So you can either loop through document.getElementById("ReportFilter1_rbSearch_" + idx ) or have a switch statement, and see which one has .checked = true.
RadioButtonList is an ASP.NET server control. This renders HTML to the browser that includes the radio button you are trying to manipulate using JavaScript.
I'd recommend using something like the IE Developer Toolbar (if you prefer Internet Explorer) or Firebug (if you prefer FireFox) to inspect the HTML output and find the ID of the radio button you want to manipulate in JavaScript.
Then you can use document.getElementByID("radioButtonID").checked from JavaScript to find out whether the radio button is selected or not.
The HTML equivalent to ASP.NET RadioButtonList, is a set of <input type="radio"> with the same name attribute(based on ID property of the RadioButtonList).
You can access this group of radio buttons using getElementsByName.
This is a collection of radio buttons, accessed through their index.
alert( document.getElementsByName('RadioButtonList1') [0].checked );
function CheckRadioListSelectedItem(name) {
var radioButtons = document.getElementsByName(name);
var Cells = radioButtons[0].cells.length;
for (var x = 0; x < Cells; x++) {
if (document.getElementsByName(name + '_' + x)[0].checked) {
return x;
}
}
return -1;
}
For a 'RadioButtonList with only 2 values 'yes' and 'no', I have done this:
var chkval=document.getElemenById("rdnPosition_0")
Here rdnposition_0 refers to the id of the yes ListItem. I got it by viewing the source code of the form.
Then I did chkval.checked to know if the value 'Yes' is checked.
I would like to add the most straightforward solution to this problem:
var reasons= document.getElementsByName("<%=RadioButtonList1.UniqueID%>");
var answer;
for (var j = 0; j < reasons.length; j++) {
if (reason[j].checked) {
answer = reason[j].value;
}
}
UniqueID is the property that gave you the name of the inputs inside the control, so you can just check them really easily.
I've tried various ways of determining a RadioButtonList's SelectedValue in Javascript with no joy. Then I looked at the web page's HTML and realised that ASP.NET renders a RadioButtonList control to a web page as a single-column HTML table!
<table id="rdolst" border="0">
<tr>
<td><input id="rdolst_0" type="radio" name="rdolst" value="Option 1" /><label for="rdolst_0">Option 1</label></td>
</tr>
<tr>
<td><input id="rdolst_1" type="radio" name="rdolst" value="Option 2" /><label for="rdolst_1">Option 2</label></td>
</tr>
</table>
To access an individual ListItem on the RadioButtonList through Javascript, you need to reference it within the cell's child controls (known as nodes in Javascript) on the relevant row. Each ListItem is rendered as the first (zero) element in the first (zero) cell on its row.
This example loops through the RadioButtonList to display the SelectedValue:
var pos, rdolst;
for (pos = 0; pos < rdolst.rows.length; pos++) {
if (rdolst.rows[pos].cells[0].childNodes[0].checked) {
alert(rdolst.rows[pos].cells[0].childNodes[0].value);
//^ Returns value of selected RadioButton
}
}
To select the last item in the RadioButtonList, you would do this:
rdolst.rows[rdolst.rows.length - 1].cells[0].childNodes[0].checked = true;
So interacting with a RadioButtonList in Javascript is very much like working with a regular table. Like I say I've tried most of the other solutions out there but this is the only one which works for me.
I wanted to execute the ShowShouldWait script only if the Page_ClientValidate was true. At the end of the script, the value of b is returned to prevent the postback event in the case it is not valid.
In case anyone is curious, the ShouldShowWait call is used to only show the "please wait" div if the output type selected is "HTML" and not "CSV".
onclientclick="var isGood = Page_ClientValidate('vgTrxByCustomerNumber');if(isGood){ShouldShowWait('optTrxByCustomer');} return isGood"
To check the selected index of drop down in JavaScript:
function SaveQuestion() {
var ddlQues = document.getElementById("<%= ddlQuestion.ClientID %>");
var ddlSubQues = document.getElementById("<%=ddlSecondaryQuestion.ClientID%>");
if (ddlQues.value != "" && ddlSubQues.value != "") {
if (ddlQues.options[ddlQues.selectedIndex].index != 0 ||
ddlSubQues.options[ddlSubQues.selectedIndex].index != 0) {
return true;
} else {
return false;
}
} else {
alert("Please select the Question or Sub Question.");
return false;
}
}
reasonCode.options[reasonCode.selectedIndex].value
From here:
if (RadioButtonList1.SelectedIndex > -1)
{
Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
}

Categories