only first paragraph appending javascript - javascript

I am attempting to add multiple "p" elements with different inner texts but for some reason only one paragraph element in total is appending, which always seems to be the final one in the code.
My code is shown below. Thanks for the help.
HTML:
<select>
<option>Movie Title</option>
<option>Movie Actor</option>
<option>Genre</option>
<option>Release Year</option>
</select>
<input type="text" id="search">
<button id="submitSearch">SUBMIT</button>
<div id="searchresult">
</div>
JAVASCRIPT:
var searchBtn = document.getElementById("submitSearch");
var userSearch = document.getElementById("search");
var resultDiv = document.getElementById("searchresult");
searchBtn.addEventListener("click",function(){
var userMovie = userSearch.value.toLowerCase();
//removing all white space from title
var arraySearch = userMovie.split(" ");
var convertedSearch = arraySearch.join("");
if (!movies[convertedSearch]){
console.log("Sorry, this does not match any DVD's you own");
} else {
var para = document.createElement("p");
resultDiv.appendChild(para);
para.innerText = "Title: " + movies[convertedSearch].title;
resultDiv.appendChild(para);
para.innerText = "Cast: " + movies[convertedSearch].cast;
}
})

The problem is that you're not asking the browser to append two paragraphs: you're asking it to append the same one (para) twice. No DOM element can be in two places at once, so it is failing.
You need to repeat para = document.createElement("p"); after appending it the first time. That will ask the browser to create two paragraphs and append them both.

Related

How to add new lines after HTML elements

I have a simple method for adding input boxes after a button is clicked. The goal of this method is to generate a set of input boxes with a newline inserted after each div.
In the screenshot above you can see that the divs are spaced properly. However, when the add_more button is clicked the generated inputs do not come out properly.
Expected:
The code should generate new input boxes like so:
<div>
Key Term 2: <input id="el2" type="text" value=""> <br>
</div>
<br>
Actual:
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
// create newline
br_key = document.createElement("br");
// create newline
br_description = document.createElement("br");
//create a new row for a key term.
row = document.createElement("div");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML += numberOfInputs;
row.innerHTML += " :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id", "el" + numberOfInputs);
//add the key to the row.
row.appendChild(key);
row.after(br_key);
//create a row for the new description.
row2 = document.createElement("div");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML += numberOfInputs;
row2.innerHTML += " :";
// create the description input
description = document.createElement("input");
description.setAttribute("id", "dl" + numberOfInputs);
// add the description to the row.
row2.appendChild(description);
row2.after(br_description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
<div>Key Term 5 :<input id="el5"></div>
Any help figuring out this issue would be greatly appreciated. Thanks.
Your issue here is essentially incorrect HTML, CSS. I'd implement your inputs, etc. like this:
.full-width-label {
display:block;
}
<label class="full-width-label" for="1">Label</label>
<input type="text" id="1"/>
There are multiple ways to achieve the above, this is just one of your options but now you no longer need to embed the look into the HTML and the format of your HTML (line breaks) is independent of your look.
You might want to look into an off the shelf solution for these kinds of things, like Bootstrap or Tailwind
You can use make it in a simple way
HTML
add this jquery cdn
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<button type="button">Click Here</button>
<div class="appendDiv">
</div>
Js
$(document).ready(function (){
var button = document.getElementsByTagName('button');
var appendDiv = document.getElementsByClassName('appendDiv');
var key = 1;
var descKey = 1;
$('button').click(function(event){
event.preventDefault();
$(appendDiv).append('<div class="child"><div class="grand-child"><label>Key Form :'+ ' '+(++key)+'</label><input type="text" value=""/></div><div class="grand-child"></div><label>Description :'+ ' '+(++descKey )+'</label><input type="text" value=""/></div>');
})
})

How to replicate text on many spans

What you type inside the input box should be replicated below, on each span.
I can do this with de js code below, but to do so I need to make the same code over and over again for each span that needs to be completed. I've tried using same class "one" on every span, but only works on the first span. I have to create a new class for every span and some code for each one of those spans.
I want to know a way to replicate the same text in many many spans without so much code. How?
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelector('span.one');
result.innerHTML = this.value;
});
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelector('span.two');
result.innerHTML = this.value;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="A">
<p>One: <span class="one"></span></p>
<p>Two: <span class="two"></span></p>
Use querySelectorAll to select all the elements of same css selector. Please use following code:
Please use this link to study more about querySelectorAll
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelectorAll('span');
for(const res of result) {
res.innerHTML = this.value;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="A">
<p>One: <span class="one"></span></p>
<p>Two: <span class="two"></span></p>

Add element works but clears input value

I have a script below that adds an element to my form, another text input field. It adds the new text input field but if I type something into the first one then add a new field it removes the input text from the first one.
I cant see where im going wrong here, im fairly new to JavaScript so please go easy :)
function addAnother() {
var id = 1;
var elemebt = document.getElementById('quest');
var number = elemebt.getElementsByTagName('*').length;
var add = number + 1;
var element = '<input type="text" name="question[]" id="quest'+ add +
'" placeholder="Example: What previous experiance do you have?" class="form-control" id="cloan"><a id="name'+
add +'" onClick="removeEle('+ add +')">Remove</a>';
document.getElementById('quest').innerHTML += element;
}
In JavaScript, the following two statements are practically identical:
str = str + ' more text ';
str += ' more text ';
The key point here is that in the end, the value of str is COMPLETELY OVERWRITTEN.
In your case, that means the innerHTML of the "quest" element is overwritten and the browser completely recreates it's children nodes, thus reseting any state and input values.
To overcome this, you can use the appendChild method but you first need to create the element to append. The easiest way to do that given you have a string of your HTML is to inject that string into a dummy element using the innerHTML property:
var target = document.getElementById('target');
var tDiv = document.createElement('div');
var htmlString = '<input type="text"></input>';
tDiv.innerHTML = htmlString;
target.appendChild(tDiv.children[0]);
<div id="target">Keep my content safe!</div>

How to insert a line break with javascript?

The Submit Form I have has the name, email, and phone number fields. Of course, I want to insert line break between the three. I tried to insert a line break between all three, but only generated one at the end of the form, when my code should appended 3 line breaks, not one.
The generated view source shows this:
<label>Name: </label><input required="" name="fullName" type="text"><label>Email: </label> <input required="" name="email" type="text"><label>Phone Number: </label><input required="" name="phoneNumber" type="text"><br><input value="Submit Query" type="submit"></form>
My Javascript Code to produce this form:
function queryForm()
{
var queryBox = document.getElementById("queryBox").style.display = "block";
var queryForm = document.getElementById("queryForm");
var linebreak = document.createElement("br");
var lblName = document.createElement("label");
lblName.textContent = "Name: ";
queryForm.appendChild(lblName);
var fullName = document.createElement("input");
fullName.name = "fullName";
fullName.type = "text";
fullName.required = "required";
queryForm.appendChild(fullName);
queryForm.appendChild(linebreak);
var lblEmail = document.createElement("label");
lblEmail.textContent = "Email: ";
queryForm.appendChild(linebreak);
queryForm.appendChild(lblEmail);
var email = document.createElement("input");
email.name = "email";
email.type = "text";
email.required = "required";
queryForm.appendChild(email);
var lblPhoneNumber = document.createElement("label");
lblPhoneNumber.textContent = "Phone Number: ";
queryForm.appendChild(linebreak);
queryForm.appendChild(lblPhoneNumber);
var phoneNumber = document.createElement("input");
phoneNumber.name = "phoneNumber";
phoneNumber.type = "text";
phoneNumber.required = "required";
queryForm.appendChild(phoneNumber);
var submitQuery = document.createElement("input");
submitQuery.type = "submit";
submitQuery.value = "Submit Query";
queryForm.appendChild(linebreak);
queryForm.appendChild(submitQuery);
}
You should create new <br> tag each time when you will append it, something like
linebreak = document.createElement("br");
queryForm.appendChild(linebreak);
DEMO
You should try to append each time a new node, and not the same one that was previously created, i.e:
queryForm.appendChild(document.createElement("br"));
EDIT:
the explanation is here on the documentation
Node.appendChild
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
The problem with your code is you're inserting the same element over and over again.
Here's an analogy: Imagine you have several children lined up in a row. Yes you can attempt to move one of them after each of the other children, however, at the end of the day you still only have one of that child. He's going to end up at the end of the row.
Solution: Create the line break element each time you need to insert it.
Also, here's an obligatory plug for jQuery: http://www.jquery.com
Protip: Append your inputs to your labels. That way a user can click the label to get focus on the input.
This has the additional perk that you can simply apply the CSS display:block to your labels and have them on separate lines!
You can use the classic \n to get this to work. I used this solution for a multi-line textarea in my project, but I cut out some code to simplify the example:
explanation.value = 'Equation: ' + equation;
explanation.value += '\nAnswer: ' + answer;

Contents From Two Divs to One Input Field Value

I'm trying to insert the contents of the two divs into a single input field in a form.
This is what I have so far but at the moment the only field that copies over when the onclick occurs is the edit1 div contents.
any help would be greatly appreciated.
The JAVASCRIPT:
<script language="javascript" type="text/javascript">
function copyText2() {
var output = document.getElementById("edit1","edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
</script>
The HTML:
<div id="edit1">foo</div>
<div id="edit2">bar</div>
<form>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input onClick="copyText2()" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
Get the two contents separately, and then add them.
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + " " + output2;
Change
var output = document.getElementById("edit1","edit2").innerHTML;
into
var output = document.getElementById("edit1").innerHTML + document.getElementById("edit2").innerHTML;
That should work.
You should copy them one at a time and then concatenate
function copyText2() {
var output = "";
output += document.getElementById("edit1").innerHTML;
output += document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
document.getElementById("") is only using the first id string you give it. It doesn't accept multiple ids. From the Mozilla Dev docs:
id is a case-sensitive string representing the unique ID of the
element being sought.
Just have output grab the content from the first id, then from the second and append them together.

Categories