how to i get access to my remove button using javascript [duplicate] - javascript

I have a page with anchor tags throughout the body like this:
<a id="test" name="Name 1"></a>
<a id="test" name="Name 2"></a>
<a id="test" name="Name 3"></a>
The ID is always the same but the name changes.
I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I've got to so far:
document.write(document.getElementById("readme").name);
This writes out the name of the first anchor tag. I'm in need of a way to get multiple elements by Id.
Any help is greatly appreciated.

If you can change the markup, you might want to use class instead.
HTML
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>
JS
var elements = document.getElementsByClassName("test");
var names = '';
for(var i = 0; i < elements.length; i++) {
names += elements[i].name;
}
document.write(names);
jsfiddle demo

Today you can select elements with the same id attribute this way:
document.querySelectorAll('[id=test]');
Or this way with jQuery:
$('[id=test]');
CSS selector #test { ... } should work also for all elements with id = "test". Вut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id.
Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .
For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).

As oppose to what others might say, using the same Id for multiple elements will not stop the page from being loaded, but when trying to select an element by Id, the only element returned is the first element with the id specified. Not to mention using the same id is not even valid HTML.
That being so, never use duplicate id attributes. If you are thinking you need to, then you are looking for class instead. For example:
<div id="div1" class="mydiv">Content here</div>
<div id="div2" class="mydiv">Content here</div>
<div id="div3" class="mydiv">Content here</div>
Notice how each given element has a different id, but the same class. As oppose to what you did above, this is legal HTML syntax. Any CSS styles you use for '.mydiv' (the dot means class) will correctly work for each individual element with the same class.
With a little help from Snipplr, you may use this to get every element by specifiying a certain class name:
function getAllByClass(classname, node) {
if (!document.getElementsByClassName) {
if (!node) {
node = document.body;
}
var a = [],
re = new RegExp('\\b' + classname + '\\b'),
els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++) {
if (re.test(els[i].className)) {
a.push(els[i]);
}
}
} else {
return document.getElementsByClassName(classname);
}
return a;
}
The above script will return an Array, so make sure you adjust properly for that.

Here is a function I came up with
function getElementsById(elementID){
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++){
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.
However, I have come to discover that dollar sign function has become
the more-or-less de facto shortcut to document.getElementById(). Let’s
face it, we all use document.getElementById() a lot. Not only does it
take time to type, but it adds bytes to your code as well.
here is the function from prototype:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
[Source]

You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.

You should use querySelectorAll, this writes every occurrence in an array and it allows you to use forEach to get individual element.
document.querySelectorAll('[id=test]').forEach(element=>
document.write(element);
});

More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.
One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.
If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.
I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.
If you want a solution that actually finds all IDs of the same name though, then it's this:
function getElementsById(id) {
const elementsWithId = []
const allElements = document.getElementsByTagName('*')
for(let key in allElements) {
if(allElements.hasOwnProperty(key)) {
const element = allElements[key]
if(element.id === id) {
elementsWithId.push(element)
}
}
}
return elementsWithId
}
EDIT, ES6 FTW:
function getElementsById(id) {
return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}

With querySelectorAll you can select the elements you want without the same id using css selector:
var elems = document.querySelectorAll("#id1, #id1, #id3");

You can get the multiple element by id by identifying what element it is. For example
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
$("div#id")
. This will get you array of elements you loop them based on your logic.

No duplicate ids, it's the basis. If you have an html structure as
<a id="test1" name="Name_1">a1</a>
<a id="test2" name="Name_2">a2</a>
<a id="test3" name="Name_3">a3</a>
Nowadays, with ES6, you can select multiple elements with different id's using the map() method:
const elements = ['test1', 'test2', 'test3'].map(id => document.getElementById(id));
console.log(elements);
// (3) [a#test1, a#test2, a#test3]
Of course, it's easier to select them if they have a same class.
The elements with the different ids are in an array.
You can, for example, remove them from the DOM with the forEach() method:
elements.forEach(el => el.remove());

An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".

Below is the work around to submit Multi values, in case of converting the application from ASP to PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
var Arr_Elements = [];
Arr_Elements = document.getElementsByClassName("MultiElements");
for(var i=0; i<Arr_Elements.length; i++) {
Arr_Elements[i].value = '';
var Element_Name = Arr_Elements[i].name;
var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
var Multi_Elements = [];
Multi_Elements = document.getElementsByName(Element_Name);
var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
if (Main_Element_Type == "CheckBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements[j].checked == true) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
if (Multi_Elements[j].value != '') {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
Arr_Elements[i].value = Multi_Elements_Values;
}
}
</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
<table>
<tr>
<td>Check Box</td>
<td>
<input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
</td>
<td>
<input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
<input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
<input type="hidden" name="SdPart" id="SdPart" value="3451"></input>
<input type="textbox" name="Test11" id="Test11" value="345111"></input>
<!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc
-->
<input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
</td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
testCB.php
<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>

Use jquery multiple selector.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>
Link : http://api.jquery.com/multiple-selector/
selector should like this : $("#id1,#id2,#id3")

Related

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

Adding div elements to an array on button click

The page I am working on contains a div element with the id "exam", a button with the id of "copy" and a second button with the id "array". The div element contains the text "Exam 1" and when the "copy" button is clicked, this div is duplicated each time the button is clicked. The "array" button is supposed to add each of these "exam" divs to an array and use the alert function to display the length of the array. I can't figure out how to go about having these div elements added to an array when the button is clicked.
Here is the HTML I have so far (this also includes Javascript and CSS):
<html>
<head>
<title>Exam 1 Tanner Taylor</title>
<style type="text/css">
#exam {
border: 2px double black;
}
</style>
</head>
<body>
<div id="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()" >
<input type="button" id="array" value="Get Array" onclick="makeArray()">
</body>
<script type = "text/javascript">
var TTi = 0;
var TToriginal = document.getElementById("exam");
function copy() {
var TTclone = TToriginal.cloneNode(true);
TTclone.id = "exam";
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam[];
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
}
}
</script>
</html>
There's more to it, but I removed the parts that didn't actually deal with this problem. As you can see, I've started the makeArray() function, but wasn't really sure where to go from there, I feel like this is the function I need the most help with. Any suggestions?
I would add a class name to the exam div and use getElementsByClassName() to get all the divs with that class.
HTML:
<body>
<div id="exam" class="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="makeCopy()" />
<input type="button" id="array" value="Get Array" onclick="makeArray()" />
</body>
JS:
var TTi = 0;
var TToriginal = document.getElementById("exam");
function makeCopy() {
console.log('copy');
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam = document.getElementsByClassName("exam");
alert(TTexam.length);
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
console.log(TTexam[TTindex]);
}
}
You can replace the alert() and console.log() with whatever business logic you want.
Check out a working fiddle at http://jsfiddle.net/JohnnyEstilles/w6fdm5th/.
Some suggestions and something you maybe can proceed from: First, id-attributes should be unique, so it'd be better to use classnames:
<div class="exam">Exam 1</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()">
<input type="button" id="array" value="Get Array" onclick="makeArray()">
For the script:
var TTexam = [];
function copy() {
var TToriginal = document.getElementsByClassName("exam")[0];
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
alert(TTexam.length);
for (var TTindex = 0; TTindex < document.getElementsByClassName("exam").length; TTindex++)
{
TTexam.push(document.getElementsByClassName("exam")[TTindex]);
}
alert(TTexam.length);
}
That's just for starters. TTexam is an array defined global, just in case it should be accessible for both functions. But question is really what exactly you want to do - if you want to generate the array only once when you finished adding divs or if it should be possible to generate a new array containing all divs each time you click 'Get Array'. Then the array should be defined in the makeArray()-function.
To avoid having the same divs as doubles in the array in case of global definition, it would e.g. be possible to add a data-attribute with a counter to each newly created div and, when creating the array a second time, only add the new ones. Or it would be possible to add each new div to the array when it's added using TTexam.push(TTclone); in the copy()-function.

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

Remove span - tags and keep the content in an <td> parent tag

i have for example this:
<td "class=name">
<span class="removed">one</span>
<span class="added">two</span>
</td>
or this:
<td class=name> one
<span class="removed">two</span>
<span class="added">three</span>
</td>
or this:
<div>
one
<span class="added">two</span>
three four
<span class="removed">five</span>
six
</div>
and want to change it with JavaScript (without JQuery) to this:
<td "class=name">
two
</td>
or this:
<td class=name>
one
three
</td>
or this:
<div>
one
two
three
four
six
</div>
can't figure it out. and only found a lot of jquery stuff like replaceWith and so on, but need pure javascript for it
Here is the best and easiest method that only requires one line of code and uses jQuery:
$('.added').contents().unwrap();
Breakdown:
$('.added') = Selects the element with the added class.
.contents() = Grabs the text inside the selected element.
.unwrap() = Unwraps the text removing the <span> and </span> tags while keeping the content in the exact same location.
If all the span tags you have that you want removing have a class of removed or added and testing them using the class doesn't affect any of your other html you could try this.
var spans = document.getElementsByTagName("span");
for(var i=0; i<spans.length;i++)
{
if(spans[i].className == "added")
{
var container = spans[i].parentNode;
var text = spans[i].innerHTML;
container.innerHTML += text;
container.removeChild(spans[i]);
}
else if(spans[i].className == "removed")
{
var container = spans[i].parentNode;
container.removeChild(spans[i]);
}
}
Otherwise you need to find a way by ID or class name perhaps to grab the container of the span tags and do something similar. For instance like this
var myDiv = document.getElementById("myDiv");
var spans = myDiv.getElementsByTagName("span");
for(var i=0; i<spans.length;i++)
{
if(spans[i].className == "added")
{
var text = spans[i].innerHTML;
}
myDiv.innerHTML += text;
myDiv.removeChild(spans[i]);
}
Hope this helps
EDIT
Try here for an idea of how to implement this code using a getElementsByClassName() function which might simplify this. It returns an array like getElementsByTagName() does which you can iterate over.
You can remove any html class with the following code:
<div id="target_div">one<span class="added">two</span>three four<span class="removed">five</span>six</div>
<script type="text/javascript">
function remove_html_tag(tag,target_div){
var content=document.getElementById(target_div).innerHTML;
var foundat=content.indexOf("<"+tag,foundat);
while (foundat>-1){
f2=content.indexOf(">",foundat);
if (f2>-1) {content=content.substr(0,foundat)+content.substr(f2+1,content.length);}
f2=content.indexOf("</"+tag+">",foundat);
if (f2>-1){content=content.substr(0,f2)+content.substr(f2+3+tag.length,content.length);}
foundat=content.indexOf("<"+tag,foundat);
}document.getElementById(target_div).innerHTML=content;}
</script>
Remove span tag

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

Categories

Resources