I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
Here is an example of my source code below:
<script>
var element = document.getElementById('#re');
element.addEventListener('click', function() {
document.getElementById("#id1").value = "";
document.getElementById("#id2").value = "";
document.getElementById("#id3").value = "";
});
</script>
Assuming your IDs have the format shown in your example:
for (var i = 1; i <= 3; i++) {
document.getElementById("id" + i).value = "";
}
If that's not the case but you know the ID of every element you can put all IDs in an array and use that:
var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
document.getElementById(id).value = "";
});
Another solution is to give all the elements you want to reset a specific class and target that:
var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
element.value = "";
});
Instead of using ids, you can loop through your inputs for example:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):
for(var i = 1; i <= 3; i++) {
document.getElementById('id' + i).value = '';
}
If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:
var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
element.value = '';
});
Related
I want to fill my Selection by Script. I am struggling with the filling method.
When I want to fill my FontSizeMenu I use this code:
function FillFontSizeMenu() { // run this at Start
FillSelection(GetPossibleFontSizes(), "fontSizeMenu"); // Fill the selection with values
}
function GetPossibleFontSizes(){ // Return all values for the menu
var sizeMin = 1;
var sizeMax = 100;
var possibleSizes = [];
for(var i = sizeMin; i <= sizeMax; i++)
{
possibleSizes.push(i);
}
return possibleSizes;
}
function FillSelection(possibleValues, elementId){ // Fill the menu
for(var i = 0; i < possibleValues.length; i++)
{
var optionElement = "<option></option>"; // add one option element per value
optionElement.html(possibleValues[i]);
optionElement.val(possibleValues[i]);
$(elementId).append(optionElement); // add the option element to the selection
}
}
Something is wrong with the "FillSelection" method, it says the option element is not a function.
Does someone knows what is wrong or missing?
Thanks
Wrap html string in jQuery()
var optionElement = $("<option></option>");
You can also use jQuery() to set html, value and call .appendTo()
$("<option></option>", {
html: possibleValues[i],
value: possibleValues[i],
appendTo: $(elementId)
});
Here is one more solution
You need to create new Option object
$(elementId).append(new Option("Font size "+i, possibleValues[i]));
and you should pass #id to function:
FillSelection(GetPossibleFontSizes(), "#fontSizeMenu")
function FillFontSizeMenu() { // run this at Start
FillSelection(GetPossibleFontSizes(), "#fontSizeMenu"); // Fill the selection with values
}
function GetPossibleFontSizes(){ // Return all values for the menu
var sizeMin = 1;
var sizeMax = 100;
var possibleSizes = [];
for(var i = sizeMin; i <= sizeMax; i++)
{
possibleSizes.push(i);
}
return possibleSizes;
}
function FillSelection(possibleValues, elementId){ // Fill the menu
for(var i = 0; i < possibleValues.length; i++)
{
$(elementId).append(new Option("Font size "+i, possibleValues[i])); // add the option element to the selection
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="FillFontSizeMenu()">Populate it</button>
<select id="fontSizeMenu">
</select>
You have to create an element first then append properties using jquery. Something like this
var ele = document.createElement("<option>");
$("body").append(ele);
$(ele).html(possibleValues[i]);
$(ele).val(possibleValues[i]);
I wan to collect all text from a list of elements obtains using
var elements =document.body.getElementsByTagName("*");
What I've done so far:
var text = '';
for (var i = 0; i < elements.length; i++) {
text = text + ' ' + elements[i].innerText
}
This will return duplicated text because it get the own text of each element plus its children's. I want to know if there is a way to get element's owntext using pure javasript?
I think the issue is that nested matching elements of a particular tag are being counted twice. The solution is to check if we've already visited a parent element and to skip the child if that's the case.
var text = '';
var visited = [];
for (var i = 0; i < elements.length; i++) {
var found = false;
for (var e = elements[i]; e != null; e = e.parentNode) {
if (visited.indexOf(e) > -1) {
found = true;
break;
}
}
if (!found) {
text = text + ' ' + elements[i].innerText;
visited.push(elements[i]);
}
}
http://jsfiddle.net/h8k0xx82/
How can I select with plan javascript or jQuery every element which has an attribute that starts with "data-"?
I've tried
$("[data-*"])
but it doesn't work.
Here is a non-JQuery function that will do what you need:
function getAllDataElements() {
//get all DOM elements
var elements = document.getElementsByTagName("*");
//array to store matches
var matches = [];
//loop each element
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
//get all attributes for the element and loop them
var attributes = element.attributes;
for (var j = 0; j < attributes.length; j++) {
//get the name of the attribute
var attr = attributes.item(j).nodeName;
//check if attibute name starts with "data-"
if (attr.indexOf("data-") == 0) {
matches.push(element); //add it to matches
}
}
}
return matches; //return results
}
Which can be used like so:
var results = getAllDataElements();
results.forEach(function (i) {
i.style.color = "#FF0000";
});
Here is a working example
I thought this would be easier, but running into a weird issue.
I want to split the following:
theList = 'firstword:subwordone;subwordtwo;subwordthree;secondword:subwordone;thirdword:subwordone;subwordtwo;';
and have the output be
firstword
subwordone
subwordtwo
subwordthree
secondword
subwordone
thirdword
subwordone
subwordtwo
The caveat is sometimes the list can be
theList = 'subwordone;subwordtwo;subwordthree;subwordfour;'
ie no ':' substrings to print out, and that would look like just
subwordone
subwordtwo
subwordthree
subwordfour
I have tried variations of the following base function, trying recursion, but either get into infinite loops, or undefined output.
function getUl(theList, splitOn){
var r = '<ul>';
var items = theList.split(splitOn);
for(var li in items){
r += ('<li>'+items[li]+'</li>');
}
r += '</ul>';
return r;
}
The above function is just my starting point and obviously doesnt work, just wanted to show what path I am going down, and to be shown the correct path, if this is totally off base.
It seems you need two cases, and the difference between the two is whether there is a : in your string.
if(theList.indexOf(':') == -1){
//Handle the no sublist case
} else {
//Handle the sublist case
}
Starting with the no sublist case, we develop the simple pattern:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
//Add your element to your list
}
Finally, we apply that same pattern to come up with the implementation for the sublist case:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
if(element.indexOf(':') == -1){
//Add your simple element to your list
} else {
var innerElements = element.split(':');
//Add innerElements[0] as your parent element
//Add innerElements[1] as your child element
//Increment i until you hit another element with ':', adding the single elements each increment as child elements.
//Decrement i so it considers the element with the ':' as a parent element.
}
}
Keep track of the current list to add items to, and create a new list when you find a colon in an item:
var baseParent = $('ul'), parent = baseParent;
$.each(theList.split(';'), function(i, e) {
if (e.length) {
var p = e.split(':');
if (p.length > 1) {
baseParent.append($('<li>').append($('<span>').text(p[0])).append(parent = $('<ul>')));
}
parent.append($('<li>').text(p[p.length - 1]));
}
});
Demo: http://jsfiddle.net/Guffa/eWQpR/
Demo for "1;2;3;4;": http://jsfiddle.net/Guffa/eWQpR/2/
There's probably a more elegant solution but this does the trick. (See edit below)
function showLists(text) {
// Build the lists
var lists = {'': []};
for(var i = 0, listKey = ''; i < text.length; i += 2) {
if(text[i + 1] == ':') {
listKey = text[i];
lists[listKey] = [];
} else {
lists[listKey].push(text[i]);
}
}
// Show the lists
for(var listName in lists) {
if(listName) console.log(listName);
for(var j in lists[listName]) {
console.log((listName ? ' ' : '') + lists[listName][j]);
}
}
}
EDIT
Another interesting approach you could take would be to start by breaking it up into sections (assuming text equals one of the examples you gave):
var lists = text.match(/([\w]:)?([\w];)+/g);
Then you have broken down the problem into simpler segments
for(var i = 0; i < lists.length; i++) {
var listParts = lists[i].split(':');
if(listParts.length == 1) {
console.log(listParts[0].split(';').join("\n"));
} else {
console.log(listParts[0]);
console.log(' ' + listParts[1].split(';').join("\n "));
}
}
The following snippet displays the list depending on your requirements
var str = 'subwordone;subwordtwo;subwordthree;';
var a = []; var arr = [];
a = str;
var final = [];
function split_string(a){
var no_colon = true;
for(var i = 0; i < a.length; i++){
if(a[i] == ':'){
no_colon = false;
var temp;
var index = a[i-1];
var rest = a.substring(i+1);
final[index] = split_string(rest);
return a.substring(0, i-2);
}
}
if(no_colon) return a;
}
function display_list(element, index, array) {
$('#results ul').append('<li>'+element+'</li>');
}
var no_colon_string = split_string(a).split(';');
if(no_colon_string){
$('#results').append('<ul><ul>');
}
no_colon_string.forEach(display_list);
console.log(final);
working fiddle here
How can I, using javascript, loop through all input boxes on a page and clear the data inside of them (making them all blank)?
Try this code:
$('input').val('');
It's looping over all input elements and it's setting their value to the empty string.
Here is a demo: http://jsfiddle.net/maqVn/1/
And of course if you don't have jQuery:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].value = '';
}
Since I prefer the functional style, you can use:
Array.prototype.slice.call(
document.getElementsByTagName('input'))
.forEach(function (el) {
el.value = '';
});
[].forEach.call(document.getElementsByTagName('input'), function(e){
e.value = '';
});
Edit: If you want to grab textareas and other elements, you can use querySelectorAll:
[].forEach.call(
document.querySelectorAll('input, textarea'),
function(e) { e.value = ''; }
);
var inputs = document.getElementsByTagName("input"),
clearTypes = { "text" : 1, "password" : 1, "email" : 1 }, // etc. you fill this in
i = inputs.length,
input;
while (i) {
if (clearTypes[(input = inputs[--i]).type]) {
input.value = "";
}
}
Just to register an alternative without JavaScript, the HTML element <input type="reset" /> clear all fields of the form. In some scenarios it may be enough.
Without jquery:
var list = document.getElementsByTagName('input');
for(var i = 0; i < list.length; i++) {
if(list[i].type == 'text' || list[i].type == 'password')
list[i].value = '';
}
You are able to do something like tha following:
<script>
e = document.getElementsByTagName('input');
for (i = 0; i < e.length; i++){
if (e[i].type != 'text') continue;
e[i].value = '';
}
</script>
Edited: added exclude for input which their types are not text!