I just started learning Javascript, but I really thought I knew this. I can't figure out why it won't work. I need it to insert "this text" formatted as a level 2 header into theDiv when the button is clicked. I've tried every way, even with a function. This example seems like the way it should work, but doesn't. I have to make this work with Javascript only, no JQuery - I don't know any yet.
<html>
<h1 id="header">Header in progress</h1>
<body>
<p>
<input type="button" id="theButton" value="click me!" onclick="document.getElementById('theDiv').innerHTML('This is new.')">
</p>
<h3><div id="theDiv"></div></h3>
</body>
</html>
document.getElementById("theDiv").textContent = 'This is dynamically added text';
Use document.getElementById('theDiv').innerHTML = 'This is new.'
You need to pass id of div with in ''(quotes) and innerHTML is property not a function
Demo
first step: get your button, and your html elements.
2nd step : add click listener to the button
3th step: add text into your html element.
const btn = document.getElementById('theButton');
const myText = document.getElementById('theDiv');
btn.addEventListener('click', function(){
const myInsertText = 'Hello World !';
myText.innerHTML = myInsertText;
});
<button id='theButton'>bouton</button>
<p id="theDiv"></p>
Related
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>
Okay, so I'm using Skulpt to program Python on a webpage.
I would like the text in the interpreter change once a button is clicked.
But no matter how I try, the code in the text area doesn't change.
However, if I 'alert' the value of the text area, it brings up the changed version, indicating that the button works.
I've also found this question:
Set value of textarea in jQuery
but nothing in here helped in my case :(
Here is how I try it:
<textarea id="theTextArea">print 'Hello World!'</textarea>
<div id="controls">
<button type="button" onclick="replaceCode()">Replace</button>
<button type="button" onclick="testAlert()">Alert Me</button>
</div>
<script>
function replaceCode(){
document.getElementById('theTextArea').value = "print 'Thats new code'";
};
function testAlert(){
alert(document.getElementById('theTextArea').value);
};
</script>
Also I've tried changing .innerHTML, .text and nothing actually replaced the text in the textarea.
If anyone thinks it could help, I could add the full HTML document with the whole Skulpt setup for online python interpreter, in case it somehow doesn't let me change the value of the textarea in a regular way. But I prefer not to have a wall of code for now if it's not needed for now.
You forgot brackets in your onclicks. You should use HTMLTextAreaElement.innerHTML to change the textarea's content
function replaceCode(){
document.getElementById('theTextArea').innerHTML = "print 'Thats new code'";
};
function testAlert(){
alert(document.getElementById('theTextArea').innerHTML);
};
<textarea id="theTextArea">print 'Hello World!'</textarea>
<div id="controls">
<button type="button" onclick="replaceCode()">Replace</button>
<button type="button" onclick="testAlert()">Alert Me</button>
</div>
So it turns out Skulpt was getting in my way of modifying python code on a button click. I needed to use a function which was defined probably in one of the imported documents which come with Skulpt. The function looks like this:
editor.setValue("print 'Thats new code'");
And then it actually changes in the textarea :)
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;
I'm just trying to do this from the chrome console on Wikipedia. I'm placing my cursor in the search bar and then trying to do document.activeElement.innerHTML += "some text" but it doesn't work. I googled around and looked at the other properties and attributes and couldn't figure out what I was doing wrong.
The activeElement selector works fine, it is selecting the correct element.
Edit: I just found that it's the value property. So I'd like to change what I'm asking. Why doesn't changing innerHTML work on input elements? Why do they have that property if I can't do anything with it?
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
value applies only to objects that have the value attribute (normally, form controls).
innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).
They are not equivalent or replaceable. Depends on what you are trying to achieve
First understand where to use what.
<input type="text" value="23" id="age">
Here now
var ageElem=document.getElementById('age');
So on this ageElem you can have that many things what that element contains.So you can use its value,type etc attributes. But cannot use innerHTML because we don't write anything between input tag
<button id='ageButton'>Display Age</button>
So here Display Age is the innerHTML content as it is written inside HTML tag button.
Using innerHTML on an input tag would just result in:
<input name="button" value="Click" ... > InnerHTML Goes Here </input>
But because an input tag doesn't need a closing tag it'll get reset to:
<input name="button" value="Click" ... />
So it's likely your browsers is applying the changes and immediatly resetting it.
do you mean something like this:
$('.activeElement').val('Some text');
<input id="input" type="number">
document.getElementById("input").addEventListener("change", GetData);
function GetData () {
var data = document.getElementById("input").value;
console.log(data);
function ModifyData () {
document.getElementById("input").value = data + "69";
};
ModifyData();
};
My comments: Here input field works as an input and as a display by changing .value
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and
closing tag. By changing an element's innerHTML after some user
interaction, you can make much more interactive pages.
JScript
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
HTML
<p>Welcome to Stack OverFlow <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
In the above example b tag is the innerhtml and dude is its value so to change those values we have written a function in JScript
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
For instance:
document.getElementById("example").innerHTML = "my string";
This example uses the method to "find" an HTML element (with id="example") and changes the element content (innerHTML) to "my string":
HTML
Change
Javascript
function change(){
document.getElementById(“example”).innerHTML = “Hello, World!”
}
After you clicked the button, Hello, World! will appear because the innerHTML insert the value (in this case, Hello, World!) into between the opening tag and closing tag with an id “example”.
So, if you inspect the element after clicking the button, you will see the following code :
<div id=”example”>Hello, World!</div>
That’s all
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
Example.
HTML
Change
Javascript
function FunctionName(){
document.getElementById(“example”).innerHTML = “Hello, Kennedy!”
}
On button Click, Hello, Kennedy! will appear because the innerHTML insert the value (in this case, Hello, Kennedy!) into between the opening tag and closing tag with an id “example”.
So, on inspecting the element after clicking the button, you will notice the following code :
<div id=”example”>Hello, Kennedy!</div>
Use
document.querySelector('input').defaultValue = "sometext"
Using innerHTML does not work on input elements and also textContent
var lat = document.getElementById("lat").value;
lat.value = position.coords.latitude;
<input type="text" id="long" class="form-control" placeholder="Longitude">
<button onclick="getLocation()" class="btn btn-default">Get Data</button>
Instaed of using InnerHTML use Value for input types
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)