Selecting all the input type checkboxes - javascript

I am unable to select all the checkboxes using the following code:
cell = row.insertCell(0);
if (tblname == "tblAttributes1")
{
el = document.createElement('input');
el.setAttribute('type', 'checkbox');
el.setAttribute('name', 'nodeID');
el.setAttribute('value', chkValue);
el.setAttribute('onclick', function()
{
Toggle( "top_checkbox", this, "nodeID" )
});
}
and html tag is:
<input type="checkbox" name="top_checkbox" value="checkbox" title="Select/Deselect All" onClick="ToggleAll( this, 'nodeID' )">

If by "selected" you mean you want them to have the checkmark in them, you're looking for the checked property. And in general, you're using setAttribute where really you'd be better off using the reflected properties for things (especially the onclick, which just won't work cross-browser as you have it). So:
cell = row.insertCell(0);
if (tblname == "tblAttributes1")
{
el = document.createElement('input');
el.type = 'checkbox';
el.name = 'nodeID';
el.value = chkValue;
el.checked = true; // Makes it checked
el.onclick = function()
{
Toggle( "top_checkbox", this, "nodeID" )
};
}
You probably also want to append el to something at some stage; presumably you're doing that in code you haven't shown.
Separately, I'd suggest using modern event handling techniques rather than onclick, such as addEventListener (attachEvent on IE8 and earlier).

You are setting a function as the onclick attribute, so the function.toString() will be set as the attribute value which won't be a valid value, instead you want to set the function reference as the value of the el's onclick property
el.onclick = function () {
Toggle("top_checkbox", this, "nodeID")
};

Related

JavaScript HTML DOM - Retrieve element ID outside for loop

I need to create checkbox for each element in data.contents. So far I have created checkboxes using createElemnt(), set ID as their respective title and calling myFunction() during onClick. Now I am trying to retrieve ID when the checkbox is clicked using getElementbyID(b.title) and ended up with an error "b is not defined" which is obvious because I am trying to access b.title outside for loop.
I can't place myFunction() inside for loop because getElementById(b.title) is giving last checkbox's ID for all checkboxes if i do onClick which is also obvious because that's the last iteration's (b.title) of for loop.
My purpose is to retrieve ID(which was dynamically set inside for loop) of a checkbox during onClick from outside for loop. Any help would be much appreciated.
data.contents.forEach(b => {
const btn = document.createElement('input')
btn.type = 'checkbox'
btn.setAttribute("id", b.title)
btn.setAttribute("onClick", "myFunction();");
var t = document.createTextNode(b.title);
mydiv.appendChild(btn);
mydiv.appendChild(t);
});
window.myFunction = function() {
var checkBox = document.getElementById(b.title);
console.log(b.title)
}
HTML
<div id="mydiv">
</div>
Rather than using setAttribute('onClick', consider assigning directly to the onclick property - that will allow you to use the b in that iteration in the handler's closure. There's also no need to create a global function, and you can simply assign to the id property of btn rather than using setAttribute:
data.contents.forEach(b => {
const btn = document.createElement('input')
btn.type = 'checkbox'
btn.id = b.title;
btn.onclick = () => {
console.log(b.title);
// do stuff with button and b
};
var t = document.createTextNode(b.title);
mydiv.appendChild(btn);
mydiv.appendChild(t);
});
If the only reason you were setting the ID was to be able to select it again with getElementById later, you can omit that entirely, due to the closure.
Try this,
data.contents.forEach(b => {
const btn = document.createElement('input')
btn.type = 'checkbox'
btn.setAttribute("id",b.title);
btn.setAttribute("data",b.title);
btn.setAttribute("onClick","myFunction('"+b.title+"');");
var t = document.createTextNode(b.title);
mydiv.appendChild(btn);
mydiv.appendChild(t);
});
window.myFunction = function(id) {
var checkBox = document.getElementById(id);
console.log(id);
}

Use addEventListener on a class not working

I am trying to convert my script using addEventListener with getElementById on a var for a getElementByClassName but this doesn't work. How to fix it?
See my code
Javascript:
var input = document.getElementByClassName('myClass');
_slider.noUiSlider.on('update', function( values, handle ) {
var value = values[handle];
if ( handle ) {
input.value = Math.round(value);
});
input.addEventListener('change', function(){
_slider.noUiSlider.set([null, this.value]);
}, false);
HTML:
<input type="number" class="myClass">
This script work perfectly if I find my div with an ID, but not work with a CLASS.
There is no getElementByClassName. There is getElementsByClassName that returns a collection. If there is only one, than select the first index.
var input = document.getElementsByClassName('myClass')[0];
Other option is querySelector
var input = document.querySelector('.myClass');
My guess is that you do not have just one element, but multiple, than you need to loop over the collection.
var inputs = document.getElementsByClassName('myClass');
//or
//var inputs = document.querySelectorAll('.myClass');
for( var i=0; i<inputs.length; i++){
inputs[i].addEventListener("click", function() { console.log(this); } );
}
var input = document.getElementById('id_name')
...here addEventListener will work because "id" will unique but in case of "class" there might be same values entered...So you have to select which element you want to manipulate...example ==>
var input = document.getElementsByClassName('class_name')[0] // after this addEventListener will work.
Hope this might help you :)

use javascript to dislay a form field as text until clicked on

I have got this working with the start point as a span, but I want to have the form still function if javascript is disabled in the browser this is how I had it working originally. I'm still very new to javascript, can someone lend a hand please.
window.onload = function() {
document.getElementById('container').onclick = function(event) {
var span, input, text;
// Get the event (handle MS difference)
event = event || window.event;
// Get the root element of the event (handle MS difference)
span = event.target || event.srcElement;
// If it's a span...
if (span && span.tagName.toUpperCase() === "SPAN") {
// Hide it
span.style.display = "none";
// Get its text
text = span.innerHTML;
// Create an input
input = document.createElement("input");
input.type = "text";
input.size = Math.max(text.length / 4 * 3, 4);
span.parentNode.insertBefore(input, span);
// Focus it, hook blur to undo
input.focus();
input.onblur = function() {
// Remove the input
span.parentNode.removeChild(input);
// Update the span
span.innerHTML = input.value;
// Show the span again
span.style.display = "";
};
}
};
};
Best way to do this would be to show the input first, then quickly swap it out when the page loads, then swap it back when the user clicks.
You might also consider using the form element the whole time, but just changing CSS classes on it to make it look like normal text. This would make your UI cleaner and easier to maintain in the future.
Then just put the input fields there from the start, and hide them with a script that runs when the form has loaded. That way all the fields will be visible if Javascript is not supported.
I think your best option would be to wrap a form with noscript tags which will fire when Javascript is disabled in a browser. If they display even while in the noscript tags then just set them as not visible with Javascript.
if you have jQuery, something like this should work.
function makeElementIntoClickableText(elm){
$(elm).parent().append("<div onClick='switchToInput(this);'>"+ elm.value +"</div>");
$(elm).hide();
}
function switchToInput(elm){
$(elm).prev().prev().show();
$(elm).hide();
}
makeElementIntoClickableText($("input")[0]);
use the readonly attribute in the input elements:
<input type="text" readonly />
And then remove that attribute with JavaScript in the onclick event handler, reassigning it on blur:
var inputs = document.getElementsByTagName('input');
for (i=0; i < inputs.length; i++) {
inputs[i].setAttribute('readonly',true);
inputs[i].onclick = function(){
this.removeAttribute('readonly');
};
inputs[i].onblur = function(){
this.setAttribute('readonly',true);
};
}
JS Fiddle demo.

Dynamic index setting in javascript

I have a table to which i need to add rows dynamically on click of a button. Each row has 3 textboxes and a clear button. On click of clear the data in the textboxes need to be cleared i.e. onclick of the button i send the index of the row to a method which deletes the contents of the textboxes at that index.
Problem - How do i specify the index number in the onClick property of the row button while adding the new row?
How do i specify the index number in the onClick property of the row button while adding the new row?
You don't. Instead, use the fact that the textboxes and the button are in the same row. I probably wouldn't use onclick on the button at all; instead, I'd have a single click handler on the table and handle the button clicks there (this is called event delegation). Something like this:
var table = document.getElementById("theTableID");
table.onclick = function(event) {
var elm, row, boxes, index, box;
// Handle IE difference
event = event || window.event;
// Get the element that was actually clicked (again handling
// IE difference)
elm = event.target || event.srcElement;
// Is it my button?
if (elm.name === "clear") {
// Yes, find the row
while (elm && elm !== table) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
};
...but if you want to keep using the onclick attribute on the button instead, you can grab the middle of that:
The button:
<input type="button" onclick="clearBoxes(this);" ...>
The function:
function clearBoxes(elm) {
var row, boxes, index, box;
// Find the row
while (elm) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
References:
DOM2 Core specification - well-supported by all major browsers
DOM2 HTML specification - bindings between the DOM and HTML
DOM3 Core specification - some updates, not all supported by all major browsers
HTML5 specification - which now has the DOM/HTML bindings in it, such as for HTMLInputElement so you know about the value and name properties.
Off-topic: As you can see, I've had to work around some browser differences and do some simple utility things (like finding the nearest parent element of an element) explicitly in that code. If you use a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others, they'll do those things for you, letting you concentrate on your actual problem.
To give you an idea, here's that first example (handling the click via event delegation) written with jQuery:
$("#theTableID").delegate("input:button[name='clear']", "click", function() {
$(this).closest("tr").find("input:text[name='whatever']").val("");
});
Yes, really. And other libraries will similarly make things simpler.
Best to use event delegation, or you can use this in JavaScript.
Event Delegation w/jQuery
<input class="clear-row-btn" type="button" >Clear Row</input>
.live event
$(".clear-row-btn").live("click", function(){
var $tr = $(this).closest("tr");
$tr.find("input[type='text']").val("");
});
HTML w/onclick method
<input type="button" onclick="clearRow(this)" >Clear Row</input>
jQuery
function clearRow(btn) {
var $tr = $(btn).closest("tr");
$tr.find("input[type='text']").val("");
}
JavaScript
function clearRow(element) {
while(element.nodeName!='TR'){
element = element.parentNode;
}
//find textboxes inside the element, which is now the parent <tr>
}

How to use Javascript to create a checked radioButton in IE?

I was trying to create a checked radiobutton by using following code in IE7. But it doesn't work.
var x = document.createElement("input");
x.type="radio";
x.checked=true; //I also tried setAttribute here which doesn't work either.
var spn=document.createElement("span");
spn.appendChild(x);
document.body.appendChild(spn);
I found that I could put x.checked=true after appendChild statement to make it work. I also noticed that when I change "radio" to "checkbox", it can be checked without changing the order of statements.
I am really confused by these facts. Am I doing something wrong in the above code?
SOLUTION: Finally, I understand it's a IE bug. When appending the new radio button to its parent, the checked property will be cleared. So, I have to call "x.checked=true;" as the last statement.
It's a weird IE thing....you need to use innerHTML or IE's extended createElement because "expando" properties don't work right on radio buttons. http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
var x = document.createElement("input");
x.setAttribute('defaultChecked', 'defaultChecked');
x.type="radio";
var spn=document.createElement("span");
spn.appendChild(x);
document.body.appendChild(spn);
This should do the trick.
This isn't jQuery : you gotta build the properties yourself:
var x = document.createElement("input");
x.type = 'radio';
x.checked = true;
But if it were jQuery:
$(document).ready(function() {
var x = $("<input type='radio' checked='checked' value='value'/>");
$("body").append($("<span></span>").append(x));});
var input = document.createElement("input");
input.setAttribute("type", "radio");
input.setAttribute("checked", "checked");
var span = document.createElement("span");
span.appendChild(input);
document.body.appendChild(span);

Categories