I need to display boilerplate text on a web page and give visitors the ability to update the text by submitting a value in a text box. I have two issues:
I can only use the text box value once but I want to use it multiple. I understand this is due to using document.getElementById. I should be using document.getElementByClassName however I am having troubles making this work.
I would like to include a default value within the boilerplate text that would then be replaced by the value from the text box. For example "your company" would be replaced with "XYZ Company" (or whatever the user submits in the text box).
I have the following code:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span id="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span id="demo"></span></strong> and again <strong><span id="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
document.getElementById(
"demo").innerHTML = x;
}
</script>
</body>
</html>
What am I missing? Any direction is appreciated. Thanks in advance.
First of all, you should be using the classes, since ids are meant to be unique. Second, when calling getElementById() (or even querySelector()), you are only getting the first element that matches the query. You should give all of the the elements a shared class, select them all with querySelectorAll(), then loop over them all, as in the following:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span class="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span class="demo"></span></strong> and again <strong><span class="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
// select all elements with class ('.') of 'demo'
const allDemoElements = document.querySelectorAll(".demo");
// loop over each element, and alter innerHTML
allDemoElements.forEach(el => {
el.innerHTML = x;
});
}
</script>
</body>
</html>
Related
So I'm typing my first useful code for school right now, (I have about 1-2 years of basic coding knowledge) I know HTML and CSS, but right now I'm getting into JavaScript. I was wondering how by the press of a button, a word a user wrote in an HTML text box replaces with another word. Let's say they wrote:
"I like eating pie." In an HTML textarea element. How can I use JavaScript so I can replace the word "like" with "love" by the click of a button? Sorry if I'm bad at explaining, questions are welcomed!
So I wrote some code that does exactly what you asked for. The code is pretty simple it uses "onclick" to call a function that gets the value of the textarea replace the words (using the "replace" function of javascript) and then changes the value of the textarea with the new value (with the replaced words)
<!DOCTYPE html>
<html>
<head>
<script>
function replace(){
var text = document.getElementById("textarea").value;
var newText = text.replace("like", "love");
document.getElementById("textarea").value = newText;
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="textarea"></textarea>
<button id="button" onclick="replace();">replace</button>
</body>
</html>
Hope it help. Anything you can ask.
You will have to add the id attribute to textbox in form. like:
<form>
<input type="Text" id = "textField">
<input type = "Button" Value = "Change Text" onclick="ChangeText()">
</form>
The javaScript function(ChangeText) should have a statement:
document.getElementById('textField').Value= "I love eating pie.";
You can also use document.getElementByName().
If you want to change a single word then you can add following in ChangeText() function:
var oldtext = document.getElementById('textField').Value;
var newtext = oldText.Replace("like","love");
document.getElementById('textField').Value= newText;
This question already has answers here:
contenteditable change events
(21 answers)
Closed 7 years ago.
Basically I have a element as is demonstrated here:
<!DOCTYPE html>
<html>
<body>
<p contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
</body>
</html>
The user can paste data into that field and therefore change the contents between the tags. The reason to do this is to get the metadata (like hyperlinks, etc.) that would be lost with a simple <textarea> element.
How can you copy this data into an <input type=hidden> element, if the content is changed by the user?
This question is unlike this question where there is no output of the data (a static text is shown, which does not indicate how to access the real data that the User has entered) and the input is of a different type (<div> vs. <p>)
HTML:
<p id="input" contenteditable="true" onKeyup="myFunction()">This is a paragraph. It is editable. Try to change this text.</p>
<input type="text" id="output">
Javascript:
function myFunction() {
document.getElementById("output").value = document.getElementById("input").innerHTML;
}
JSfiddle: http://jsfiddle.net/qw2oveuo/1/
You can combine the input event with the innerHTML to grab the data:
document.querySelector("p").addEventListener("input", function(e) {
document.querySelector("input[type=hidden]").value = e.target.innerHTML;
});
Working Example
This will update the hidden input any time the user changes the content of the p either by keypress or copy/paste.
You can use the jQuery .html() method to get the content of the p tag
<p id="my-contenteditable-p" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<input type="hidden" id="hidden-in"/>
like
var content = $('#my-contenteditable-p').html();
and after checking if the content is changed by the user, You can use jQuery .val() method to set the value to hidden field.
$("#hidden-in").val(content);
Just add a listener that gets your text and put it somewhere else:
var get = document.getElementById('getcontenthere');
var put = document.getElementById('putcontenthere');
var updateInput = function() {
put.value = get.innerText;
}
get.oninput = updateInput;
updateInput();
<!DOCTYPE html>
<html>
<body>
<p id="getcontenthere" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<p>This is type=text so you can see it, but it could be hidden as well</p>
<input id="putcontenthere" type="text">
</body>
</html>
Okay, first thing, I had a lot of trouble thinking of a title for this, and also of what to search for in Google. So that may just be me being stupid, but here is what I would like you help with.
I have a form, that has a button that will add additional input fields, but I would like the the name of the field to iterate everytime the button is pressed. E.g. the first time it will be:
<input type="textfield" name="field1" value=""/>
Then the second time it is pressed, it will be:
<input type="textfield" name="field2" value=""/>
I also have a small example of what I currently have here: http://jsfiddle.net/5gh75/14/
Please let me know if you can help me, or if you require more info thanks :)
The best way to handle this is to name them all field[].
When handled by the server-side code, it will build an array for you. For instance, in PHP you would get $_POST['field'][0], $_POST['field'][1] and so on.
For your example:
JQuery
var i=0;
$('span.add').click(function () {
$('<input>').attr({
type: 'textfield',
name: 'program'+i
}).appendTo('#addsoftware');
i++;
});
JSFiddle.
But #Kolink-s answer is much better.
Edit: I just saw the previous posts after sending this. Using an array would definitely be better, and JQuery is always nice :).
Just use some javascript:
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
idx = 0;
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "textfield");
element.setAttribute("name", "field" . idx);
element.setAttribute("value", "");
idx++;
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
I took this example from: Add more text fields dynamically in new line (html)
This code changes whatever the user types in the box to uppercase, and displays the result in the box.
<html>
<head>
<script type="text/javascript">
function upperCase(x)
{
var y=document.getElementById(x).value;
document.getElementById(x).value=y.toUpperCase();
document.getElementById("mySpan").value=y.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onkeyup="upperCase(this.id)">
<br/>
<span id="mySpan"></span>
</body> </html>
But how can I make it so that it displays it UNDER the text box? And that when the user types, the upper case text is displayed under the text box?
Thanks!
I would suggest the following, more maintainable approach, which uses the event registration model as opposed to the inline model:
JS:
<script>
document.getElementById("fname").onkeyup = function() {
document.getElementById("mySpan").innerHTML = this.value.toUpperCase();
}
</script>
Markup:
Enter your name: <input type="text" id="fname"/>
<br/>
<span id="mySpan"></span>
Demo: http://jsfiddle.net/karim79/GPZ8h/
Create a css class
.showUpperCase { text-format: uppercase; }
and add this to your span or textBox.
<span id="mySpan" class="showUpperCase"></span>
This doesn't change the characters entered, only shows them as upper-case.
That means that if you're handling input via a textBox, you'll have to
change to upper-case server-side as well. This is not an additional
chore, since you have to be wary of client-side handling and da a server-side verification, regardless of what the client does
I know that this is an embarassingly easy question, but I can't figure out the problem, and that's why I'm asking the question, so please don't reiterate this point.
Anyway, I'm just working on something here, and when I tested my page to see how things were going, I realized that my calculate() method isn't clearing text input like I want it to.
Here is the markup and the script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculate(){
var valuea = document.form1.variablea.value;
var valueb = document.form1.variableb.value;
var valuec = document.form1.variablec.value;
document.form1.variablea.value = "";
document.form1.variableb.value = "";
document.form1.variablec.value = "";
}
</script>
</head>
<body>
<form name="form1">
a:<input name="variablea" value="" type="text">
<br/>
b:<input name="variableb" value="" type="text">
<br/>
c:<input name="variablec" value="" type="text">
<br/>
<input name="calculate" value="Calculate!" type="button" onClick="calculate()">
</form>
</body>
</html>
Please tell me if you see anything.
You might want to try using another name. I tried to call the "calculate" function but it keeps on giving me an error saying "calculate" is not a function. But when I call the function "calculateQuad" and change the onClick event to call "calculateQuad" it works.
Not very sure, but if you don't want to move to jQuery here's what you could try:
function calculate() {
var inputa = document.getElementById('inputa');
inputa.value = '';
}
Just test this, having an id "inputa" on one of the input boxes. I only know how to get elements by id, name or tag in raw Js. Of course, you could then extend your code to what you want using one of these methods to get your form elements.
Inside the onclick method is there a reference to the item you clicked. It is named the same as the name you put on the item, "calculate". This results in that "calculate" does not refer to the function, but the input tag.
To resolve this by either typing
onclick = "window.calculate()"
or rename the name of either the input-tag or the function.
change the name of the input button to something else:
<input name="calcul" value="Calculate!" type="button" onClick="calculate()">
and it works. Since the calculate function is residing directly under the global object, I have a weird feeling your name attribute is somehow overwriting it.
Just throwing this out there. I will take a deeper look at why this is happening though.