How to use multiple document.getElementById's? - javascript

I have a problem with html and js. I don't know why I can only use the first document.getElementById that is on top.
JavaScript.js
var one = "sentence"
document.getElementById("text").innerHTML = one;
var two = "sentence sentence"
document.getElementById("text_2").innerHTML = two;
var three = "sentence sentence sentence"
document.getElementById("text_3").innerHTML = three;
webpage.html
<html>
<head>
</head>
<body>
<div id="text"></div>
</body>
</html>
<script src="test.js"></script>
When using div id="text_2" or div id="text_3", nothing will come up on the output. Only the document.getElementById that is on top in the js file can be seen on the webpage. So I gues i cannot use multiple getElementById's but I don't know a other way yet. What to do?
Thank you

var sentence1 = 'sentence',
sentence2 = 'sentence two',
sentence3 = 'sentence three',
el1 = document.getElementById('text'),
el2 = document.getElementById('text_2'),
el3 = document.getElementById('text_3');
if (el1) {
el1.innerHTML = sentence1;
}
if (el2) {
el2.innerHTML = sentence2;
}
if (el3) {
el3.innerHTML = sentence3;
}

What I want is that sometimes I need just need "text" and another time text_2 and so the same for text_3.
This is easy enough, you just put whichever one you want in a variable that you can pass to getElementById. Something like:
var elementId;
if (conditionForText) {
elementId = "text";
}
else if (conditionForText2) {
elementId = "text_2"
}
else if (conditionForText3) {
elementId = "text_3"
}
// Note: you might want to handle the case where none of the above conditions
// evaluate to true
document.getElementById(elementId).innerHTML = someText
It's not really clear if the element you want to pick is supposed to get the same text or not, but if you have several id's with several different strings that need to be set, you could map them with an object:
var elementsAndStrings = {
text : "sentence one",
text_2 : "sentence two",
text_3 : "sentence three"
};
and now you could do something like:
document.getElementById(elementId).innerHTML = elementsAndStrings[elementId];

HTML
<div class="text">Text1</div>
<div class="text">Text2</div>
<div class="text">Text3</div>
<div class="text">Text4</div>
Javascript
function getElementByClass (className, parent) {
parent || (parent = document);
var descendants= parent.getElementsByTagName('*'), i=-1, e, result=[];
while (e=descendants[++i]) {
((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
}
return result;
}
texts= getElementByClass("text");
var txtVal="";
for (i = 0; i < texts.length; i++) {
txtVal += texts[i].innerHTML + ", ";
}
alert (txtVal);
DEMO

http://jsfiddle.net/mt78j5m0/
<div id="text_1"></div>
<div id="text_2"></div>
<div id="text_3"></div>
var text = {};
text.text_1 = "One";
text.text_2 = "Two";
text.text_3 = "Three";
var divs = document.querySelectorAll("[id^='text']");
for (var div of divs) {
div.innerHTML = text[div.id];
}

What about:
const elements = [
"id1",
"id2"
].map(document.getElementById);

Related

Add and Delete text using 2 buttons in javascript (conditions : use div id 'divResult' , console log.)

I want to make a webpage with 2 buttons (Add, Delete). Conditions are using div id divResult , console log and after removing that div has to stay. It works almost correct, just last step (remove alinea) doesn`t work. Can you help me , how can i fix it? :-)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>2 buttons</title>
<script >
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement')
var alinea = oldDiv.querySelectorAll('p:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
oldDiv.removeChild(alinea);
console.log('verwijderd!');
};
};
</script>
</head>
<body>
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
</body>
</html>
I've tried a few things, moved stuff around. I think it's doing what you want now.
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement');
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
alinea.remove();
// divResult.removeChild(alinea);
console.log('verwijderd!');
};
};
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
If I understand you correctly, change the following section:
document.getElementById('Btn2').onclick = function () {
var alinea = document.getElementById('div'+ --index);
console.log(alinea.innerHTML + ' wordt verwijderd...');
alinea.remove(alinea);
console.log('verwijderd!');
};

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

Javascript: Replace 'x' only if it is the first word of a text, not anywhere else

I'm working on a simple JS code to replace some words with others in a text using an array.
<textarea id="text1">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="myFunction()">try</button>
<pre id="demo"></pre>
<script>
function myFunction() {
var str = document.getElementById("text1").value;
var mapObj = {
"k":"g",
" e": "B",
"e":"ar"
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.toLowerCase().replace(re, function(matched){
return mapObj[matched];
});
document.getElementById("demo").innerHTML = str;
}
</script>
The result is:
ar mi B
gar fo
ar di
But I desire to have this:
B mi B
gar fo
B di
If "e"s are to be changed before " e"s (separated e with a space before it), then " e"s will not be " e" but "ar", so in the array, I've put " e" above "e" and it works well.
However the problem is that the text may contain a separated "e" as the first word of the whole text or as the first word of a line with no space before it. When it's the case how can I replace this separated "e"with "B" and prevent it from being replaced with "ar".
The problem with your current code is that the .replace function is only taking a single variable input. This limits you from using more specific RegExp in your replace, as the matched element will not match the regex.
.replace's function option provides access to matched groups as the 1+nth variables. As a result we can leverage this to lookup our replacement strings in an array.
By utilising RegExp groups we can capture the values we're looking for and replace them as needed.
JS
var myFunction = function() {
var str = document.getElementById("text1").value;
var regexs = ['(k)','(^e|\\se)', '(e)'];
var replacers = ['g', 'B', 'ar'];
var re = new RegExp(regexs.join("|"),"gi");
// you would need to add variables to the function for each matching group you add (currently there are 3 so we have 3 groups)
str = str.toLowerCase().replace(re, function(raw, group0, group1, group2){
if(typeof group0 !== "undefined"){
return replacers[0]; // replaces with 'g'
}else if(typeof group1 !== "undefined"){
// skip over the first character (white space) and concatenate the replacement
return raw[0] + replacers[1]; // replaces with 'B'
}else if(typeof group2 !== "undefined"){
return replacers[2]; // replaces with 'ar'
}
return raw;
});
document.getElementById("demo").innerHTML = str;
};
document.getElementById('go').addEventListener('click', myFunction);
CSS
#demo{
white-space:pre;
}
NOTE: because you're outputting to an elements .innerHTML without the above CSS new lines are not displayed.
JS FIDDLE
Try The below code.
function myFunction() {
var str = document.getElementById("text1").value;
str = str.toLowerCase().split('k').join('g').split(' e').join(' B').split('\\n').join(' B').split('e').join('ar');
document.getElementById("demo").innerHTML = str;
}
Its a different approach but I got the expected output.
A simple workaround.
<script type="text/javascript">
var myfunction = function(){
var f = document.getElementById('text1').innerHTML;
var c = f.replace(/e/ig,'ar').replace(/\bar/ig,'B').replace(/k/ig,'g');
document.getElementById('text1').innerHTML = c;
}
</script>
This works.
<textarea id="source" cols="5" rows="5">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="convert()">Convert</button>
<textarea id="destination" cols="5" rows="5">
</textarea>
<script>
function replaceWord(searchFor, replaceWith, paragraph) {
if (paragraph) {
var lines = paragraph.split('\n');
for (lineNo = 0; lineNo < lines.length; lineNo++) {
var words = lines[lineNo].split(' ');
for (wordNo = 0; wordNo < words.length; wordNo++) {
if (words[wordNo] === searchFor) {
words[wordNo] = replaceWith;
}
}
lines[lineNo] = words.join(' ');
}
paragraph = lines.join('\n');
}
return paragraph;
}
function replaceWords(wordMap, paragraph) {
for(var searchFor in wordMap)
{
if(wordMap.hasOwnProperty(searchFor))
{
paragraph = replaceWord(searchFor, wordMap[searchFor], paragraph);
}
}
return paragraph;
}
function convert() {
var mapObj = {
"ke":"gar",
"e": "B"
};
var source = document.getElementById("source");
var destination = document.getElementById("destination");
destination.value = replaceWords(mapObj, source.value);
}
</script>
Here is the jsFiddle.
https://jsfiddle.net/1egs7zgc/
For what it's worth, your mapObj isn't really an array it's an object.

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Change first letter in string to uppercase in JavaScript

I have an array of strings,
["item1", "item2"]
I'd like to change my array to
["showItem1", "showItem2"]
The most easy to understand way of doing exactly what you ask for is probably something like this:
var items = ["item1", "item2"];
​for (var i=0;i<items.length;i+=1) {
items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}
console.log(items); // prints ["showItem1", "showItem2"]
Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)
Strings are array-like. You could do this:
var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
var letters = arr[i].split('');
arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}
Demo: http://jsbin.com/asivec/1/edit
arr.map(function(i) {
return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
supported in Chrome, Firefox, IE9 and others.
Here is a reusable firstCharLowerToUpper() function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
span{
color:red;
}
</style>
</head>
<body>
<div>this is the text:
<span id="spn">
javascript can be very fun
</span>
</div>
<br/>
<input type="button" value="Click Here" onClick="change()"/>
<script>
function firstCharLowerToUpper(x)
{
var ar = x;
for (var i = 0; i < ar.length; i++)
{
ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
}
// join to string just to show the result
return ar.join('\n');
}
function change()
{
var ar = ["javascript ", "can ","be ","very ","fun" ];
var newtxt = firstCharLowerToUpper(ar);
document.getElementById("spn").innerHTML = newtxt;
}
</script>
</body>
</html>

Categories

Resources