find inputs in HTML using JavaScript - javascript

In the below table which is generated dynamically, I want to traverse and find html controls (input,select,textarea) using JavaScript DOM. I don't want span and div values.
Can anyone give an idea on how to traverse?
<html>
<head>Html</head>
<body>
<tr>
<td>
<div id="one"></div>
</td>
<td>
<input type="text" name="textbox" id="txtid" value=10"/>
</td>
<td>
<select id="cuskstatus" name="cuskstatus" class="selectStyleBorder">
<option selected value="LOCAL">Local</option>
<option value="GLOBAL">Global</option>
</select>
</td>
</tr>
<tr>
<td>
<textarea id="tareaid" name="" value="10"/>
</td>
<td>
<span id="span1">value</span>
</td>
</tr>
</body>
</html>

I would do it like this
var desired_tag_names = new Array('select', 'input', 'textarea');
function getElements(e) {
var elements = new Array();
for (i=0; i<e.length; i++) {
var el = document.getElementsByTagName(e[i]);
for (j=0; j<el.length; j++) {
elements.push(el[j]);
}
}
return elements;
}
var all_the_desired_elements = getElements(desired_tag_names);

In plain JavaScript, just use form.elements.
Assuming that you've a <form id="formid">:
var inputs = document.getElementById("formid").elements;
// ...
Or if you want to traverse all forms of the document on a per-form basis, just use document.forms to get all forms first.
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
var inputs = form.elements;
// ...
}
If you're already using jQuery, or are open to, use :input selector.
var $inputs = $(':input');
// ...

Applying jQuery makes this problem trivial:
$('input','select','textarea')
This will return a jQuery collection of all input, select and textarea elements.

Related

Clear contents of multiple input fields?

Hi I am dynamically adding rows with a button and when I am finished entering information, I would like it to then clear the contents. The button "Add Pokemon" is the one I want to press and it should clear all the contents.
function addPokemon() {
var pokemonName = document.getElementById("pokemon-name-container");
pokemonName.innerHTML = document.getElementById("pokemon-names").value;
for (var i = 0; i < element.length; i++) {
if (element[i].value !== "undefined") {
pokemonArray.push(element[i].value);
}
}
console.log(pokemonArray);
for (var i = 0; i < pokemonArray.length; i++) {
document.getElementById("pokemon-container").innerHTML += "<li>" + pokemonArray[i] + "</li>";
}
document.getElementById("pokemon-name-container").value = "";
document.getElementById("move-name").value = "";
}
This is my function I am using. ^^
And below is my HTML vv
<div>
<table>
<tbody id="tbody">
<tr>
<td>
<div id="pokemon-name-container">
<p>Pok&eacutemon Name:</p>
<input type="text" id="pokemon-names" size="30">
</td>
</tr>
<tr>
<td>
<p class="moves">Moves:</p>
</td>
</tr>
<tr>
<td>
<input class="move-container" type="text" id="move-name" placeholder="Enter move here">
</td>
<td>
<input class="button-container" type="button" id="remove-btn" value="Remove Move" onclick="removeRow()">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" class="add-move-button" id="add-move-button" value="Add Move" onclick="addRow()">
</div>
<div>
<input type="button" class="add-pokemon-button" id="add-pokemon-button" value="Add Pokémon" onclick="addPokemon()">
</div>
You could put to all the inputs you create a unique class that defines them under a parent with a unique id. Then use inside the function of javascript the next pice of code const childs = document.querySelectorAll('#idParent.classChilds') this querySelectorAll is kind of like the getElementsById but uses selectors of CSS so it's more powerfull. The querySelectorAll returns you a NodeList of all the elements that matches de DOM with the CSS query.
Then you would only need to do something similar to this using functional programming:
const childs = document.querySelectorAll('#idParent .classChilds')
childs.forEach(child=>{
child.value = ""
})
I'm not sure if this code works (I'm not with an code editor and a browser to check if there isn't mistakes), as I said, you could do something similar to it
HOPE IS HELPFULL
FYI, try to avoid the selectors like getElementById or getElementsByClass....
Try to use this:
document.querySelector('CSS SELECTOR') // GIVES YOU THE FIRST MATCH OF THE CSS SELECTOR
document.querySelectorAll('CSS SELECTOR') // GIVES YOU A NODELIST WITH ALL MATCHES

JQuery script to fill textbox / input based on class

I'm looking to craft a JQuery script to fill all textboxes on a page with a single string of text.
The textboxes on this page have no name or ID, so I need to fill them in by class.
<td>
<input class="form-control input-sm" placeholder="Optional Comment" value="" style="">
</td>
Thank you everyone.
Are you familiar with vanilla JS DOM manipulation?
var allTextboxes = document.querySelectorAll(".CLASS_SELECTOR");
for(var i = 0, len = allTextboxes.length; i < len; i++){
allTextboxes[i].value = "YOUR_VALUE";
}

Modifying all DOM elements using Javascript

I am working on a page which has certain number of Dojo textarea elements.
<textarea readonly class="readTextBox versionText"></textarea>
The number of these elements is more than one. I am trying to add a javascript function or formatting of a textarea. The function gives me certain line count for the textarea elements. The script is :
<script type="application/javascript">
window.onload=function() {
var versionElement = document.getElementsByClassName("versionText");
console.log("length:" + versionElement.length);
var versionElementText = versionElement.value;
var lines = versionElementText.split(/\r\n|\r|\n/);
var rowCount = 0;
for(var line=0;line<lines.length;line++) {
rowCount += Math.ceil(lines[line].length/82);
}
versionElement.rows=rowCount;
}
The problem is, i am not able to add it for all the textarea elements. I am just bale to get only one textarea elements.
I tried Windo.onload still i am getting textarea element count as 1. JS snippet is placed at the very bottom of the page as well.
the parent file which calls up the textarea is :
<div class="box-content">
<div id="pnl_{$id}">
{foreach from=$version item=version name=version}
{assign var=textBoxes value=$version->textBoxes}
<div data-dojo-type="dijit.TitlePane>
{include file="addTextArea.tpl"}
</div>
{/foreach}
</div>
</div>
The generated HTML looks like:
<div class="box-content">
<div id="productPanel_80920">
<div data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Version 4 <span class=versionDate>2014-01-16 15:35:21</span>'">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td class="tableCell">
<textarea readonly class="readTextBox versionText" style="resize: none; outline: none; word-wrap: break-word;" spellcheck="true"> random text
</textarea>
</td>
</tr>
</tbody>
</table>
</div>
<br class="box-divider"/>
<div data-dojo-type="dijit.TitlePane" data-dojo-props="href:'addTextArea.html?id=4059&version=3', title:'Version 3 <span class=versionDate>2014-01-10 14:52:46</span>',open:false"></div>
<br class="box-divider"/>
<div data-dojo-type="dijit.TitlePane" data-dojo-props="href:'addTextArea.html?id=4059&version=2', title:'Version 2 <span class=versionDate>2014-01-10 14:48:09</span>',open:false"></div>
<br class="box-divider"/>
<div data-dojo-type="dijit.TitlePane" data-dojo-props="href:'addTextArea.html?id=4059&version=1', title:'Version 1 <span class=versionDate>2014-01-10 14:47:41</span>',open:false"></div>
<br class="box-divider"/>
the textarea is populated anytime i click on the div.
First off, the proper HTML would be this (you were missing a closing >):
<textarea readonly class="readTextBox versionText"></textarea>
Second off, document.getElementsByClassName returns a nodeList which is like an array. You have to go through each DOM element in the nodeList to operate on all your textarea elements.
I'm not sure I know exactly what you're trying to do, but converting your code to perform the oepration you've code on each textarea returned, it would be something like this:
window.onload=function() {
var items = document.getElementsByClassName("versionText");
for (var i = 0; i < items.length; i++) {
var versionElement = items[i];
var versionElementText = versionElement.value;
var lines = versionElementText.split(/\r\n|\r|\n/);
var rowCount = 0;
for(var line=0;line<lines.length;line++) {
rowCount += Math.ceil(lines[line].length/82);
}
versionElement.rows=rowCount;
}
}
var objs=document.getElementsByTagName('textarea');
for (var i=0;i<objs.length;i++){
var obj=objs[i];
if (!obj.className||obj.className!='versionText') continue;
//do your transformation here
}

How to add items to a list in similar check box format from user input

I am trying to make an editable check list, using check boxes. One feature I would like is for users to be able to add their own items to this list.
With the help of another user, I have got this far:
HTML:
<table id="myTable">
<tr>
<td>
<label for="checkbox65">
<input name="checkbox65" class="checkbox65" type="checkbox" />
Get directions for where you are going
</label>
</td>
</tr>
<tr>
<td>
<fieldset data-role="controlgroup">
<label for="textinput4">
Add new item
<input name="new_item" id="textinput4" placeholder="" value="" type="text" />
</label>
</fieldset>
<button id="add">Add</button>
</td>
</tr>
</table>
Javascript:
$('#add').on('click', function (e) {
var $this = $(this);
var $firstRow=$this.closest('table').find('tr:first');
var $newRow = $firstRow.clone();
$newRow.find(':input').prop('checked', false);
$newRow.insertAfter($firstRow);
});
What I'm trying to get is something that looks a bit like this:
What I want
But at the moment it just repeats the original check box with label.
Assuming you need to set the text next to the checkbox to what you enter in the input box, you can do:
$('#add').on('click', function (e) {
var $this = $(this);
var $firstRow=$this.closest('table').find('tr:first');
var $newRow = $firstRow.clone();
var input = $newRow.find(':input').remove();
input.prop('checked', false);
$newRow.empty().append(input).append(' '+$('#textinput4').val());
$newRow.insertAfter($firstRow);
});​
Demo: http://jsfiddle.net/VHe6C/
You can add the text box value for the check box
$(document).ready(function(){
$("#addbutton").on("click",function(){
if ($("#goingtoadd").val()!="")
document.getElementById('adding').innerHTML+='<br/><input name="checkbox65" class="checkbox65" type="checkbox" />'+$("#goingtoadd").val();
$("#goingtoadd").val("");
})
});
See this Fiddle for Demo
If anyone is interested in a pure javascript based solution here is it:
document.querySelector('#add').addEventListener('click', function(e){
var table = this.parentNode.parentNode.parentNode,
rowsLen = table.rows.length,
beforeLastRow = table.rows[rowsLen - 2],
inputToAdd = document.querySelector('#textinput4');
var newRow = beforeLastRow.cloneNode(true),
input = newRow.querySelector('input');
input.checked = false;
var label = newRow.querySelector('label');
label.innerHTML = "";
label.appendChild(input);
label.appendChild(document.createTextNode(inputToAdd.value));
inputToAdd.value = "";
table.insertBefore(newRow, table.rows[rowsLen - 1]);
}, false);
Here is a jsFiddle to test it out:
http://jsfiddle.net/subhamsaha1004/2G9Qv/

Get Html Attributes inside div

<div>
<table>
<tr>
<td>
<input type="text" id="one" value="1" name="textbox"/>
</td>
<td>
<input type="hidden" id="two" value="2" name="hidden"/>
</td>
</tr>
<tr>
<td>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
</td>
<td>
<span id="sdf" title="sdf">ok</span>
</td>
</tr>
</table>
<div>
Get Html Attributes inside div,How to get attribute like type,name,value
from above div using dom(traversing) for each elements like input,span etc
a simple search on google returned this guide for javascript. here you can find everything you need
I assume you're asking how to do this with javascript. Here's sample code for the objects with id values. For the other values, put id names on them too and use the same technique.
var input_one = document.getElementById("one");
var input_two = document.getElementById("two");
alert("Input one: type='" + input_one.type + "', name='" + input_one.name + "', value='" + input_one.value + "'");
And a fiddle that shows it in action: http://jsfiddle.net/jfriend00/nZyjN/
using getAttribute( "type" ) we can get value of the particular attribute
The querySelectorAll(selectors) method allows you, for a given element, to retrieve an array of its descendant elements that match given criteria.
For example:
// Replace "yourDiv" with a reference to you main div
var elements = yourDiv.querySelectorAll("input, span");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var name = element.name;
var type = element.type;
var value = element.value;
// Now you can do what you want with name, type and value, for example:
alert("Name: "+name+"\r\n"+"Type: "+type+"\r\n"+"Value: "+value);
}
According to the Mozilla Developer Network the querySelectorAll method is supported in IE8, Fx3.5, Chrome1, Opera 10 and Safari 3.2.

Categories