JavaScript - Get text in div by class - javascript

I am trying to get just the content/text of div by class name using javascript. The outcome isn't what i have expected. I did try to push it into array but it does not seems to be working. Please help!
What i have done so far :
JavaScript:
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year= document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i];
year.add(Entry ,null);
}
}
Html:
<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">
<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>
Output:
Desire outcome:

Use Node.textContent, The Node.textContent property represents the text content of a node and its descendants
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
}
<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">
<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>

Related

Populate textbox based on Dropdown selection - JS

Here am not able to add text inside the text box based on the dropdown selection.
example: If I Choose option2 in the dropdown the textbox will filled as option2
(function() {
'use strict';
setInterval(function () {
if (document.getElementById('ddid')) {
console.log('Found Tag dropdown button');
return;
}
var widgetcontentwrapper = document.getElementsByClassName('widget-content-wrapper');
if (widgetcontentwrapper.length > 0) {
console.log('Found widgetcontentwrapper controls');
var buttonToolbar = widgetcontentwrapper[0].children[0];
//Create array of options to be added
var array = ["option1", "option2", "option3", "option4"];
//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute('class', 'ddclass');
selectList.setAttribute('id', 'ddid');
//myParent.appendChild(selectList);
selectList.addEventListener('change', favTutorial, false);
var div = document.createElement('div');
div.setAttribute('class', 'flex-item');
div.appendChild(selectList);
buttonToolbar.insertBefore(div, buttonToolbar.firstChild);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
}
},
3000)
function favTutorial() {
var mylist = document.getElementsByClassname("ddclass");
document.getElementsByClassname("input-large").value = mylist.options[mylist.selectedIndex].text;
}
}
)()
<div class="widget-content-wrapper">
<div class="arrow"></div>
<form class="input-compressed"><fieldset>
<legend class="offscreen">
Add a Tag
</legend>
<div class="editable-field-change">
<span class="input-append input-smaller"><input class="input-large" data-link="proposedTag" placeholder="Add a tag (any text)..." size="16" type="text">
</span>
</div>
<div class="tags">
<ul class="unstyled editable-list inline-list"></ul>
</div>
</fieldset></form>
</div>
There's two problems here. Firstly, the method is getElementsByClassName(), not getElementsByClassname() - note the uppercase 'N'.
Secondly, that method returns an array-like object, not a single Element object. Therefore you can't call value or options on it directly. Given that there's only 1 instance of the element in the question you can just use [0] to access the first element in the set.
(function() {
'use strict';
setInterval(function() {
if (document.getElementById('ddid')) {
console.log('Found Tag dropdown button');
return;
}
var widgetcontentwrapper = document.getElementsByClassName('widget-content-wrapper');
if (widgetcontentwrapper.length > 0) {
var buttonToolbar = widgetcontentwrapper[0].children[0];
//Create array of options to be added
var array = ["option1", "option2", "option3", "option4"];
//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute('class', 'ddclass');
selectList.setAttribute('id', 'ddid');
//myParent.appendChild(selectList);
selectList.addEventListener('change', favTutorial, false);
var div = document.createElement('div');
div.setAttribute('class', 'flex-item');
div.appendChild(selectList);
buttonToolbar.insertBefore(div, buttonToolbar.firstChild);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
}
}, 3000)
function favTutorial() {
var mylist = document.getElementsByClassName("ddclass")[0];
document.getElementsByClassName("input-large")[0].value = mylist.options[mylist.selectedIndex].text;
}
})()
<div class="widget-content-wrapper">
<div class="arrow"></div>
<form class="input-compressed">
<fieldset>
<legend class="offscreen">
Add a Tag
</legend>
<div class="editable-field-change">
<span class="input-append input-smaller"><input class="input-large" data-link="proposedTag" placeholder="Add a tag (any text)..." size="16" type="text">
</span>
</div>
<div class="tags">
<ul class="unstyled editable-list inline-list"></ul>
</div>
</fieldset>
</form>
</div>
That being said, your code is doing some very odd things. Why do you repeatedly try and create the select element, and exiting from the function when it already exists after the first iteration?
I would assume from the context that this is a rudimentary method of checking the DOM to see if a dynamic element has been created from some external source. If this is the case, use a MutationObserver instead.
Also, avoid generating HTML in your JS code. Put it in <template /> elements and clone it. This way there is never any HTML logic within the JS.
Here's a full working example of this:
(function() {
'use strict';
// define MutationObserver to check the DOM for new .widget-content-wrapper elements being created
var newWidgetContainerObserver = new MutationObserver(mutations => {
mutations.forEach(m => {
m.addedNodes.forEach(n => {
if (n.className === 'widget-content-wrapper')
createSelectForWidget(n);
});
});
});
newWidgetContainerObserver.observe(document, { attributes: false, childList: true, characterData: false, subtree: true });
let widgetContainer = document.querySelector('#widget-container');
// when a new .widget-content-wrapper node is added to the DOM by external
// code, append the select to it.
let createSelectForWidget = node => {
let selectTemplate = document.querySelector('#dd-template').content.cloneNode(true);
let container = node.querySelector('.arrow');
let html = container.appendChild(selectTemplate);
container.addEventListener('change', favTutorial);
}
// event handler for the dynamically created select element, which sets
// the value of the related input
let favTutorial = e => {
let select = e.target;
let container = select.closest('.widget-content-wrapper');
container.querySelector('.input-large').value = select.value;
}
// only for this demo, generates content on button click - mocking the
// external process which is updating your DOM
document.querySelector('#test').addEventListener('click', e => {
let widgetClone = document.querySelector('#widget-template').content.cloneNode(true);
widgetContainer.appendChild(widgetClone);
});
})()
<button id="test">Test - dynamically append new widget</button>
<div id="widget-container"></div>
<template id="widget-template">
<div class="widget-content-wrapper">
<div class="arrow"></div>
<form class="input-compressed">
<fieldset>
<legend class="offscreen">Add a Tag</legend>
<div class="editable-field-change">
<span class="input-append input-smaller"><input class="input-large" data-link="proposedTag" placeholder="Add a tag (any text)..." size="16" type="text">
</span>
</div>
<div class="tags">
<ul class="unstyled editable-list inline-list"></ul>
</div>
</fieldset>
</form>
</div>
</template>
<template id="dd-template">
<div class="flex-item">
<select class="ddclass" id="ddid">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
</div>
</template>

How do I get the Onkey Function to copy the value of a input textfield to the other 3 textfields

This is the Java Script I'm using. I can enter in the proceduredate and it copies to proceduredate2 but not 3 and 4--Same with Procedure
function copyTextAreaValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
console.log('no dest element ' + destIds[i]);
}
}
}
}
Link to JSFiddle with full code
Your question id not clear to me. However, all I understood is you want to copy text from your current text input to other three text input. If that is true, then you can have your solution here. Please, checkout the snippet below.
let el = document.getElementById('field_1');
function copyTextValue() {
let elVal = el.value;
document.getElementById("field_2").value = elVal;
document.getElementById("field_3").value = elVal;
document.getElementById("field_4").value = elVal;
}
copyTextValue();
el.oninput = copyTextValue;
el.onchange = copyTextValue;
Today's Date: <input id="field_1" value=""/><br/>
Procedure Date: <input id="field_2" value=""/> <br/>
Date of Procedure: <input id="field_3" value=""/> <br/>
Surgery Date: <input id="field_4" value=""/> <br/>
function copyTextfieldValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
//console.log('no dest element ' + destIds[i]);
}
}
}
}
<input id="t1">
<input id="t2">
<input id="t3">
<input id="t4">
<input type="button" value='copy' onclick="copyTextfieldValue('t1','t2,t3,t4');">
Your code seems to work fine. See the snippet.

javascript appear a thing with specific id using appendChild

I don't know how to explain it, I don't want it to be unclear, so first thing first, I want to show this HTML code :
<body>
<form class="" action="index.html" method="post">
<input type="num" onkeyup="addOptions()" name="member" id="member">
<div id="selects">
</div>
</form>
</body>
And this is the javascript code :
<script type="text/javascript">
function addOptions() {
document.getElementById('selects').innerHTML = "";
var inputValue = document.getElementById('member').value;
for (var i = 0; i < inputValue; i++) {
var select = document.createElement('select');
var option = document.createElement('option');
option.innerText = "Example";
select.appendChild(option);
document.getElementById('selects').appendChild(select);
}
}
</script>
So, groove of this code will be if I type num in input num, the select will be appear as many as I type the num. But, it just will run the select option. So, my question is can I appear that the option is in HTML code? So when I type the num in the textfield, I will appear something like this for example :
<option value="example" id="example">example</option>
So the option code will be running as many as the num, like when I type 3 in the textfield, I will get 3 code like in above.
If I got it right, there are some issues in your code. I believe you are trying to achieve a drop down using select.
Inside for loop you creating select in each iteration which I think you don't want. To make value, id avilable to the newly created option you have to set those properties to the option.
Try the following:
function addOptions() {
document.getElementById('selects').innerHTML = "";
var select = document.createElement('select');
var inputValue = Number(document.getElementById('member').value);
for (var i = 0; i < inputValue; i++) {
var option = document.createElement('option');
option.innerText = "Example" + i;
option.value = "example" + i;
option.id = "example" + i;
select.append(option);
}
if(select.innerHTML) // if at least one option then append select
document.getElementById('selects').appendChild(select);
}
<input type="num" oninput="addOptions()" name="member" id="member"><br><br>
<div id="selects">
</div>
Just move some lines out of your for loop, as following:
function addOptions() {
document.getElementById('selects').innerHTML = "";
var inputValue = document.getElementById('member').value;
var select = document.createElement('select');
for (var i = 0; i < inputValue; i++) {
var option = document.createElement('option');
option.innerText = "Example "+i;
select.appendChild(option);
}
document.getElementById('selects').appendChild(select);
}
<form class="" action="index.html" method="post">
<input type="num" onkeyup="addOptions()" name="member" id="member">
<div id="selects">
</div>
</form>

Javascript finding indexOf select option

So this is what I managed to do, use a text box to add strings to my select.
How can I now use a second text box to write part of a string I created in the select with the first text box and find the indexOf the word I typed(indexOf need to appear underneath the second text box)?
Note: the simplest Javascript answer, please.
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.text = document.getElementById("txt").value;
addTwoSelect.add(write);
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select"><option value="0">Choose a string</option></select>
OK, so just a second input box and compute the indexOf:
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.value = write.text = document.getElementById("txt").value;
addTwoSelect.add(write);
}
function outputIndex() {
var addTwoSelect = document.getElementById("select"),
secondBox = document.getElementById("string"),
out = document.getElementById("index");
out.innerText = addTwoSelect.value.indexOf(secondBox.value);
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select" onchange="outputIndex()"><option value="0">Choose a string</option></select>
<input type="text" id="string" oninput="outputIndex()"/>
<output id="index"></output>
Use the value attributes of your <option>s!
var last = 0;
function addString(){
var addTwoSelect = document.getElementById("select");
var write = document.createElement("option");
write.text = document.getElementById("txt").value;
write.value = ++last;
addTwoSelect.add(write);
}
function outputIndex() {
var addTwoSelect = document.getElementById("select"),
out = document.getElementById("index");
out.innerText = addTwoSelect.value;
}
<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select" onchange="outputIndex()"><option value="0">Choose a string</option></select>
<output id="index"></output>

Is possible to get all the values of all the <input>s inside a div?

<div id="test">
<input type="text" value="10" size="3">
<input type="text" value="0" size="3">
<input type="text" value="25" size="3">
<input type="text" value="0" size="3">
</div>
I want a function to get all the values of the inputs. I was trying with this:
var inputs = $("test :input");
But I don't know how to go from there or even if it's correct.
Thank you
You can do this:
var inputs = new Array();
inputs = $('#test :text').map(function(){
return this.value;
}).get(0);
Or:
var inputs = new Array();
inputs = $('#test :text').each(function(){
inputs.push(this.value);
});
You can access each value like this:
alert(inputs[0]);
alert(inputs[1]);
alert(inputs[2]);
// and so on
The :text refers to inputs of type text.
$("#test :input").each(function(){
var value = $(this).attr("value"); //Save value in an array or something
});
Do you mean like this?
var values = [];
$('input').each(function(index, element){
values.push($(element).val());
});
Non-jQuery version:
var values = [];
var inputs = document.getElementById("test").getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; ++i) {
values.push(inputs[i].value);
}

Categories

Resources