Adding to a <div> element using innerHtml creates a new line? - javascript

I have a tool that is supposed to be an easy way to create a checklist, and it works, but what happens when I use it for something with two checkboxes, it creates a new line between each one, is there a way to stop it from doing that? my code is here for yes/no
<!DOCTYPE html>
<html>
<h1>Create a checklist</h1>
<div>
<input type="text" placeholder="Text for object" id="txt" />
<button onclick="addYN()">Add yes/no</button>
</div>
</html>
<div style="background-color: grey;" id="prv"></div>
<script>
var pv = document.getElementById("prv");
var txt = document.getElementById("txt");
function getVarYn() {
let tx = txt.value;
return (
"<div><p>" +
tx +
"</p> <p> yes</p> <input type = 'checkbox'/> <p>no </p> <input type = 'checkbox'/> </div> "
);
}
function addYN() {
var t = txt.value;
pv.innerHTML = pv.innerHTML + getVarYn();
}
</script>

The problem is not the <div> you create but all the <p> tags. <p> tags are paragraphs and they do create "a new block/line"
See like so you would have no new lines
var pv = document.getElementById("prv");
var txt = document.getElementById("txt");
function getVarYn() {
let tx = txt.value;
return (
"<div>" +
tx +
" yes<input type = 'checkbox'/>no<input type = 'checkbox'/> </div> "
);
}
function addYN() {
var t = txt.value;
pv.innerHTML = pv.innerHTML + getVarYn();
}
<h1>Create a checklist</h1>
<div>
<input type="text" placeholder="Text for object" id="txt" />
<button onclick="addYN()">Add yes/no</button>
</div>
<div style="background-color: grey;" id="prv"></div>
Note: the closing </html> element should always be the very last element of your HTML document. And everything else should be inside the <body> element which you do not have. The basic structure looks like so
<!DOCTYPE html>
<html>
<body>
<!-- ADD all your HTML content here -->
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<!-- BUT NOW you need to finish with all the HTML here -->
<!-- THE VERY LAST thing here before the closing </body> -->
<!-- should be the <script> tags -->
</body>
</html>

Related

for loop with array of strings rendering the same thing twice?

I am building in javascript a simple feedback that has a text area and is grabbing the text and displaying a successful message when the add button is clicked. When the view feedback button is clicked it should render the feedback and it does but if I click the button once and then type in the text area again and again it keeps rendering multiple times the same feedback message. Attached is my javascript code.
var array = Array();
var x = 0;
function addFeedback() {
array[x] = document.getElementById('feedback').value;
x++;
document.getElementById('feedback').value = '';
document.getElementById('result').innerHTML =
'<h2><h3> Your have successfully Added Feedback!</h3></h2>';
}
var feedback = '';
function displayFeedback() {
for (var i = 1; i < array.length + 1; i++) {
feedback = array[i - 1] + '<br/>';
console.log(feedback);
}
document.getElementById('result').innerHTML =
'<h2>feedback Details: </h2>' + feedback.split('<br>');
}
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<!-- Fill code here -->
<div>
<h2>Feedback for the ART OF LIVING</h2>
<div>
<label for="feedback"></label>Enter the Feedback:
<textarea id="feedback" name="feedback" value="feedback" type="text"></textarea>
<div>
<input type="button" id="create" name="create" onclick="javascript:addFeedback()">Add Feedback</input><br/>
<input type="button" id="view" name="view" onclick="javascript:displayFeedback()">View feedback</input>
</div>
<div id="result"></div>
</div>
</div>
</body>
</html>

Replace empty lines with <p> tags in textarea and show it as HTML valid code

There is a textarea where someone can write a text. The text could be on multiple lines, I want to check the blank lines in the text and replace them with <p> tags, so the text between 2 blank lines should be wrapped in <p> tags.
So far it is working to check the blank lines and return a boolean if there is a blank line.
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
if (inTxt.match(/^\s*\n/gm)) {
console.log('yes, there is a blank line');
} else {
console.log('nope. no blank lines');
}
document.getElementById('output').innerHTML = inputVal;
}
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<textarea id="output" name="w3review" rows="6" cols="15"> </textarea>
<script src="script.js"></script>
</body>
</html>
Is there a way to replace the blank lines with tags and also show it in the output as HTML, not to show it with but with the HTML parsing of it?
EDIT - updated to reflect the OP's requirements as noted in the comments
Simply split the textarea value at the newlines, then build a string with the portions encased in the p element tags - and then insert that string as the innerHTML of an output div. You cannot have html within a textarea - so the only way to do it is to create the elements - if you inspect the output div - you will see that ervery portion of the textarea input is encased in <p>...</p> tags - with the emty line in the textarea translating to an empty p element in the output.
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
const newTextPortions = inputVal.split('\n');
newTextStr = ''
newTextPortions.forEach(function(portion){
newTextStr += "<p>" + portion + "</p>"
})
document.getElementById('output').innerHTML = newTextStr;
}
<label>Enter text</label>
<textarea id="w3review" name="w3review" rows="4" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<div id="output"></div>
If you prefer to use HTML instead of a textarea (as you can't have HTML in a textarea), then you can write HTML into a div instead:
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
if (inTxt.match(/^\s*\n/gm)) {
console.log('yes, there is a blank line');
} else {
console.log('nope. no blank lines');
}
document.getElementById('output').innerHTML = '<p>' + inTxt.replaceAll(/(\n+)/g, '</p><p>') + '</p>';
}
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
Short answer:
use replace insted of if
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
inTxt = inTxt.replace(/(\r\n|\n|\r)/gm," ");
inTxt = inTxt.replace(" "," ");
document.getElementById('output').innerHTML = inTxt;
}
Long answer (Best practice):
Create a function that sanetizes the input, creates "actual" P-tags and append them to the DOM and/or show render them in the textfield.
You can't show rich-content in the textfield, but one approach is to create a fake-textfield -> Format text in a <textarea>?
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<textarea id="output" name="w3review" rows="6" cols="15"> </textarea>
<script src="script.js"></script>
<div id="target"> </div>
</body>
<script>
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
inTxt = inTxt.replace(/(\r\n|\n|\r)/gm,",");
let textArray = []
let sanitizedArray = []
textArray = inTxt.split(",")
console.log(textArray)
//Sanitize the array
textArray.map((data, index)=> data === ""? console.log(`Index ${index} is empty don't push`): sanitizedArray.push(data))
console.log(sanitizedArray)
function createValidHtml(content){
const target = document.getElementById("target")
let pTag = document.createElement("p")
pTag.innerHTML = content
target.appendChild(pTag)
}
sanitizedArray.map(data => createValidHtml(data))
//Set as value of output-textfield (if necessary)
const target = document.getElementById("target")
document.getElementById('output').innerHTML = target.innerHTML
}
</script>
</html>

"x" is not a function at

I keep getting an error message that:
check is not a function at area question 1
and
check is not a function at HTMLInputElement.onclick
and I think this is the reason that the check() function is not running. I've looked at so many other solutions to this problem but none of them are really helpful for my issue. Any help would be greatly appreciated!
var number1;
var number2;
var response;
var calcanswer;
var score = 0;
window.onload = areaquestion1;
score.innerHTML = "SCORE: " + score;
function areaquestion1() {
var imageBlock = document.createElement("img");
imageBlock.setAttribute("id", "img");
imageBlock.setAttribute("src", "Images/2_1.png");
imageBlock.setAttribute("width", "700");
imageBlock.setAttribute("height", "400");
imageBlock.setAttribute("alt", "2_1");
document.getElementById('img').appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 2
number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("check").check();
}
function areaquestion2() {
var imageBlock = document.createElement("img");
imageBlock.setAttribute("id", "img");
imageBlock.setAttribute("src", "Images/4_2.png");
imageBlock.setAttribute("alt", "4_2");
document.body.appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 4
number2 = 2
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("solve").check();
}
function check() {
var statusDiv = document.getElementById("status");
response=document.getElementById("answer").value;
if(response != calcanswer)
statusDiv.innerHTML="Incorrect";
else
if (response==calcanswer)
{
statusDiv.innerHTML="Very good!";
score ++;
document.getElementById("score").textContent = score
document.getElementById("answer").value = "";
}
}
<!DOCTYPE html>
<html>
<title>Lego Area Play</title>
<head>
<link rel="stylesheet" href="CSS/gridtest.css">
<script src="JavaScript/Play.js"></script>
</head>
<body onload="areaquestion1();">
<div class="header">
<h1>LEGO AREA</h1>
<p>Calculating <b>area</b> with Emmet.</p>
<div id="scorelabel"><label>SCORE:</label></div>
<div id="score" class="score"></div>
</div>
<form>
<div class="row">
<div class="column" style="background-color:#aaa;">
<div id="question"></div>
<div id="img"></div>
<div id="status"></div>
</div>
<div class="column" style="background-color:#bbb;">
<div id ="prompt"></div>
<label>Area = </label>
<input type="text" id="answer" placeholder="Answer"/>
<label>Units<sup>2</sup></label>
</div>
<div class="column" style="background-color:#ccc;">
<input id="check" type="button" value="CHECK!" onclick="check()" />
<div class="practice"> <img src="Images/legoBlue2.png" id="practicebtn" alt="lego button for practice page" width=350px height=140px></div>
<div class="menu"> <img src="Images/menured.png" id="menubtn" alt = "lego button for menu page" width=350px height=140px></div>
</div>
</div>
</form>
</body>
</html>
As Cannicide pointed out, your second error occurs when the arequestion1() is called on load, on the line document.getElementById("check").check();
You added the check method to onclick, but that did not add a new property to the button.
Your first error is a little more complicated. This is the simplest recreation of your error I tried creating.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function f(){
console.log("f run")
}
</script>
<!-- id same as function name -->
<input id="f" type="button" value = "B1" onclick="f()" />
<!-- button inside a form -->
<form>
<input type="button" value = "B2" onclick="f()" />
</form>
<!-- button inside a form with random id -->
<form>
<input id="somethingelse" type="button" value = "B3" onclick="f()" />
</form>
<!-- button inside a form, equal id and method name -->
<form>
<input id="f" type="button" value = "B4" onclick="f()" />
</form>
</body>
</html>
There are 4 buttons, each with small difference in its environment. Notice how only the button that is inside a form and has the same id name and the onclick method name throws you an error.
To this error I unfortunately have no clue to why and how does this happen.
If someone here knows what is going on here, please explain!
cheers :)

Retrieve user input not working?

So my dilemmna is that I don't know how to record what the user inputs. (my goal as of now is to simply print what the user enters in an input box, not to add the numbers)
var x = document.getElementById('textboxone').value;
Why isn't this working?
<!DOCTYPE html>
<html>
<head>
<link href="cssFiles/ttt.css" rel="stylesheet" type="text/css"></link>
<script Language ="JavaScript">
//create skeleton divs
function createDivs () {
var s;
s = '<div class="simplebox" id="divBody">Bla 3 bla</div>';
document.write(s);
}
//create body skeleton
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div id="textboxone"><span>Add <input type="text" ></input></span></div>';
s += '<div id="textboxtwo"><span>To <input type="text" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
//adding the two numbers from input boxes
function addnumbers(form){
var x = document.getElementById('textboxone').value;
alert(x)
}
</script>
</head>
<body>
<script Language ="JavaScript">
createDivs();
createBodyDivs('divBody');
</script>
</body>
</html>
Check out AngularJS my friend! :)
JSFIddle Demo
<div ng-app="">
<input type="text" ng-model="data.message" />
<h1>{{data.message}}</h1>
<div class="{{data.message}}"></div>
</div>
using: https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js
I've quickly checked the code and first of all you input button will not trigger addNumbers(form) since the onclick of the input doesn't point of that function.
Then for the function itself, document.getElementById('textboxone').value returns undefined because the actual value you want is in the <input> and not in the <div id="textboxone">
So if you have you're createBodyDivs function modified so that the id where on the input, then this document.getElementById('textboxone').value would actually return the correct value.
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div><span>Add <input type="text" id="textboxone" ></input></span></div>';
s += '<div><span>To <input type="text" id="textboxtwo" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
For the click binding, you button should be the following for it to work:
<input type="button" value = "Answer Generator" OnClick="addnumbers()"></input>

jquery form not printing input

Found a nice website for an alternative to using /forms in share point. My code below though does not print my input to the screen. Any Suggestions.
<script type="text/javascript">
function printvalues()
{
var div = document.getElementById("divId");
div.innerHTML += "test";
div.innerHTML += inputobj1.value;
}
</script>
<div id="divId">
username: <input name="inputobj1" value="" />
<button id="idButton" type="button" onclick ="printvalues();">
Generate!
</button>
<div id="divId">
</div>
There's two issues with your code.
First, you're missing a closing </div> tag; and you have two <div> elements with the same id property! I think you should remove the first div's id property.
Second, your <input /> is missing the id property, therefore it's not automatically defined by inputobj1.
Try this markup:
<script type="text/javascript">
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += "test";
div.innerHTML += document.getElementById("inputobj1").value;
}
</script>
<div>
username: <input id="inputobj1" name="inputobj1" value="" />
<button id="idButton" type="button" onclick ="printvalues();">Generate!</button>
<div id="divId"></div>
</div>
Here's a working jsFiddle.
<script type="text/javascript">
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += "test";
div.innerHTML += inputobj1.value;
}
</script>
<div id="divId2">
username: <input name="inputobj1" value="" />
<button id="idButton" type="button" onclick ="javascript:printvalues();">
Generate!
</button>
<div id="divId"></div>
</div>
or
<div id="divId2">
username: <input name="inputobj1" value="" />
<button id="idButton" type="button">
Generate!
</button>
<div id="divId"></div>
</div>
<script type="text/javascript">
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += "test";
div.innerHTML += inputobj1.value;
}
$('#idButton').click(function(){
printvalues()
})
</script>
You had 2 divId's as well, i made an assumption on witch on to use
this doesnst work because you have two div with id="idButton" and your markup is not closed
this may also work as you tagged jquery
function printvalues() {
var value = $('input[name="inputobj1"]').val();
var $div = $('<div>',{text:value});
$('#divId').append($div);
}
or using the divId div
function printvalues() {
var value = $('input[name="inputobj1"]').val();
$('#divId').text(value);
}

Categories

Resources