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;
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>
I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE
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>
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)
i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/