document.getElementById("items_" + i) is null - javascript

I have the following code:
<script type="text/javascript">
for(var i=1; i<=3; i++) {
document.getElementById("items_"+i).checked=true;
}
</script>
With the following HTML
<input type="checkbox" id="items_1" name="myitems" value="1" />
<input type="checkbox" id="items_2" name="myitems" value="2" />
<input type="checkbox" id="items_3" name="myitems" value="3" />
I get an error saying:
document.getElementById("items_" + i) is null.
How do I fix this?

The first index in your for loop will be zero.
Do you have an element with the id items_0 ?
That's likely what's causing your problem. Set the initial value of i to 1
Secondly, you want to make sure that your Javascript code executes after the DOM has loaded.
I recomend you look into using jQuery as this makes it so much simpler to do these kinds of things.

Well your code looks like it's first iteration is pointed to i = 0 so it's trying to find an input tag with the id of 'items_0'.
Here is a JSBin that shows the code working correctly:
http://jsbin.com/amonel/edit

var VanillaRunOnDomReady = function() {
// code to execute after DOM has loaded
for (var i = 1; i <= 3; i++) {
document.getElementById("items_" + i).checked = true;
}
}
var alreadyrunflag = 0;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
}
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}

I ended up using:
$('#items_'+i).attr("checked", true);

Related

Uncaught TypeError: Cannot read property 'value' of null, Element does exist

Before you downvote, I've read a lot of questions and it didn't help me.
My Javascript's alert returns null even when there is a value in the input type.
Here's the code :-
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
It always returns null. The error in console says :
Uncaught TypeError: Cannot read property 'value' of null
Trying to fix it since last 1 hour. What is wrong here?
Wrap your JavaScript in window.onload. Currently your JavaScript is executing before the element exists:
<script>
window.onload = function () {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
}
</script>
Another thing you can do is move the script tag to be after the elements you're referencing:
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
Your script should be excuted after inputs being added to DOM. The most crossbrowser way to make your script work, is to move it just before your <body> tag is closed, and wrap it into an immediate function:
<script>
(function() {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
} else {
var str = null;
}
alert(str);
})();
</script>
</body>
This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.
Here your script should be after html.

What's the better solution for this javascript code not using reverse method

I'm trying that this code works but not success and I need help to find out where is the mistake to make it works. I don't want to use reverse method which will be a better and fast solution but to find the other way, It's challenge for me. Any instructions how to solve this problem? Any input will be welcomed.
Thanks
<body>
<form id="form_id">
<input type="text" id="your_input" />
</form>
<script>
isPalindrome = function() {
var len = this.length-1;
for (var i = 0; i <= len; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
}
}
else if (i === (len-i)) {
return true;
}
return true;
}
document.getElementById("form_id").onsubmit = function() {
isPalindrome(document.getElementById('your_input').value);
return false;
}
</script>
</body>
</html>

Hiding multiple form fields using checkboxes

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}
The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle
Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

Only one checkbox selected

I have a checkbox Yes and No so i want to user only able to use one. So if user tick Yes then No will cleared if Yes then no will clear
<input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "Yes" ? " checked" : "")/>Yes
<input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "No" ? " checked" : "")/>No
<script>
function selectOnlyThis(id) {
for (var i = 0; i <= 4; i++) {
document.getElementById("Check" + i).checked = false;
}
document.getElementById(id).checked = true;
}
</script>
The problem is that you are trying to access elements that do not exist
your loop goes from 0 to 4 but your elements are Check1 and Check2
So when it tries to set the checked property of Check0 (which does not exist) it throws an error and stops execution..
Use
function selectOnlyThis(id) {
console.log(id);
for (var i = 0; i <= 4; i++) {
var element = document.getElementById("Check" + i); // get element
if (element){ // if element was found only the set its checked property
document.getElementById("Check" + i).checked = false;
}
}
document.getElementById(id).checked = true;
}
Demo at http://jsfiddle.net/gaby/RHUVf/
or if your example html is the actual one you could just change your loop to
for (var i = 1; i <= 2; i++) {
As mentioned by others, you are describing the behavior of a radio button. However, it is possible to make a checkbox behave like this also.
jsFiddle demo
$('input:checkbox').click(function(){
$('input:checkbox').not($(this)).prop('checked',false);
});
The above code does the following:
$('input:checkbox') - selects all input elements of type checkbox
.not($(this)) - except this one
.prop('checked',false) - unchecks the checkbox
This code uses the jQuery javascript library, so you must reference this library (usually in the head tags of the document), thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
It would be a lot more helpful/easier to use HTML5 for this part
IF you choose HTML5 the following code WILL work but if you decide not to use it It wont help.
<input type="checkbox" name="<name>" value="<value"><*explanation*><br/><br/>
</form>
</div>
</div>
</body>

Javascript misfunction with checked box on internet explorer 6

i've this script that is supposed to check a list of checkbox:
function onchangeSelectAllAnalysable() {
var selectAll = document.forms[0].selectAllAnalysable;
var selectedItems = document.forms[0].selectedItemsAnalysable;
if(selectedItems != undefined) {
if(selectedItems.length != undefined) {
for (var i=0; i<selectedItems.length; i++) {
selectedItems[i].checked = selectAll.checked;
}
} else {
selectedItems.checked = selectAll.checked;
}
}
toggleShuntDiscardButtons();
}
On FF Chrome and IE7/8/9 it works fine but i need it on IE6.
Now when i activate the script i've seen that it gos thru every single box
and check it but at the end when they are all checked they get unchecked again.
It seems strange even because, after that script nothing is executed...
Thx
Daniele
Because you haven't posted relevant source code, I added my working base. After a couple of changes my code work also with IE6.
The code:
<html>
<head>
<script type="text/javascript">
function onchangeSelectAllAnalysable()
{
var selectAll = document.forms[0].elements["selectAllAnalysable"];
var selectedItems = document.forms[0].elements["selectedItemsAnalysable"];
if (typeof (selectedItems) == "object")
{
if(selectedItems.length != 0)
{
for (var i=0; i<selectedItems.length; i++) {
selectedItems[i].checked = selectAll.checked;
}
} else {
selectedItems.checked = selectAll.checked;
}
}
toggleShuntDiscardButtons();
}
function toggleShuntDiscardButtons(){/*whatever you do here*/}
</script>
</head>
<body>
<form name="x" action="http://www.stackoverflow.com" method="post">
<input type="checkbox" name="selectedItemsAnalysable"><br>
<input type="checkbox" name="selectedItemsAnalysable"><br>
<p><input type="checkbox" name="selectAllAnalysable" onClick="onchangeSelectAllAnalysable()"></p>
</form>
</body>
</html>
Attention! IE6 don't accept the event 'onChange' for radiobuttons and checkboxen. You have to use 'onClick' instead.
As you wrote, the checkboxes will be rechecked and you haven't provide the code for the function toggleShuntDiscardButtons(), you should checked the code there. Maybe you forgott some code to remove.

Categories

Resources