Take the following page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"/>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"/>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$(".hashtag").click(function() {
var txt = $.trim($(this).text());
$("#text-box").append(txt);
});
});
</script>
</body>
</html>
The behavior I would expect, and that I want to achieve is that when I click on one of the divs with class hashtag their content ("#one" and "#two" respectively) would be appended at the end of the text in textarea text-box.
This does happen when I click on the hash tags just after the page loads. However when I then also start editing the text in text-box manually and then go back to clicking on any of the hashtags they don't get appended on Firefox. On Chrome the most bizarre thing is happening - all the text I type manually gets replaced with the new hashtag and disappears.
I probably am doing something very wrong here, so I would appreciate if someone can point out my mistake here, and how to fix that.
Thanks.
2 things.
First, <textarea/> is not a valid tag. <textarea> tags must be fully closed with a full </textarea> closing tag.
Second, $(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.
So you want to set the value, you don't want to append. Use jQuery's val() method for this.
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
var box = $("#text-box");
box.val(box.val() + txt);
});
});
Working example:
http://jsfiddle.net/Hhptn/
Use the val() function :)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"></textarea>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
$("#text-box").val($("#text-box").val() + txt);
});
});
</script>
</body>
</html>
Does that help?
The reason append does not seem to work is because the value of the textarea is made up of the child node, but by treating it as multiple seperate nodes the screen won't update, according to my Firebug. Firebug will show me the updated child nodes, but NOT the text I typed manually into the textarea, whereas the screen shows me the manually typed text but not the new nodes.
You can reference by value of textarea.
$(document).ready(function () {
window.document.getElementById("ELEMENT_ID").value = "VALUE";
});
function GetValueAfterChange()
{
var data = document.getElementById("ELEMENT_ID").value;
}
works fine.
if(data.quote) $('textarea#message').val($('textarea#message').val()+data.message +' ').focus();
Related
I have been trying to practice some exercises using Javascript. Here are some challenges I have been facing. Please suggest if there is a mistake or something that I am missing.
Note: I do not want to use Jquery at this stage.
Exercise:
Ask the user to input some text. On the click of a button, the entered text needs to be displayed as rotating.
The first approach I took gets me the result the first time. But if I enter a new text, and click the button, the rotation fluctuates between the old text and new. I am not sure if I am explaining it right. Here's the first attempt:
Test the result: http://learningharvest.co.in/
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Enter the text to be reversed</p>
<div id="texttoberotated">
<input type="text" id="texttobeRot"></p>
</div>
<div>
<button id="rotateText">Rotate Text</button>
<p id="rotatedText"></p>
</div>
<script>
document.getElementById("rotateText").onclick=function (){
var text=null;
text= document.getElementById("texttobeRot").value;
var finaltext=text;
document.getElementById("rotatedText").innerHTML=finaltext;
setInterval(rotatetext, 500);
var numberofRotations=0;
var length=0;
length=text.length;
var i=0;
function rotatetext(){
i=length;
if(numberofRotations<=text.length){
getText();
}else{
numberofRotations=0;
length=text.length;
i=length;
preText=null;
postText=null;
finaltext=null;
getText();
}
}
function getText(){
preText=text.slice(length);
postText=text.slice(0,i);
i--;
finaltext=preText+" "+postText;
numberofRotations++;
length--;
document.getElementById("rotatedText").innerHTML=finaltext;
}
}
</script>
</body>
2. The second attempt I am making is using the childNodes method. However, I am unable to get the nodeValue of the input tag. The nodeValue is working if I try with any other element, but not with the input element.
Also, the function rotatetext is being executed on page load and not when the button is clicked. Works well if I add the onclick event inline in the button tag itself.
Here's the error i get in console:
Rotate text parent child method.html:27 Uncaught TypeError: Cannot read property 'nodeValue' of undefined
at rotatetext (Rotate text parent child method.html:27)
at Rotate text parent child method.html:23
Here's the body content I have drafted so far. At this stage, I am just trying to replace the text "Show Rotated Text here" with the text entered by the user.
<body>
<p>Enter the text to be reversed</p>
<input type="text" id="texttobeRot">
<button id="rotateText">Rotate Text</button>
<p id="rotatedText">Show Rotated Text here</p>
<script>
document.getElementById("rotateText").onclick= rotatetext();
function rotatetext(){
var element=document.getElementById("texttobeRot");
var textNode=element.childNodes[0];
var text=textNode.nodeValue;
var texttobeRotated;
texttobeRotated= text;
document.getElementById("rotatedText").innerHTML=texttobeRotated;
};
Look forward to all of your inputs.
Using the first approach if you add
document.getElementById("texttoberotated").onkeyup = function() {
text = '';
}
to the bottom of your script it will clear the text value when you begin to type and you can enter a new word without the issue of them being jumbled together as you described.
I put a working example of your code at https://codepen.io/chaosmaths/pen/LrwrpQ
What I'm trying to do is have a window prompt / alert box pop up with a text input. I want the value of the text in my jQuery code to be used in place of the word YOU in the a tag in my html document.
jQuery code I'm using
$(document).ready(function() {
var userName = window.prompt("Please Enter Your Name", "Text");
});
My html
<body>
<center><h1 class="Logo">Welcome to<br>an epic story adventure<br>starring <a>YOU!</a></h1></center>
<p></p>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/name.js"></script>
</body>
so basically, I wanna replace YOU! with the input value of the window prompt
You'd just need to add this line after the userName JavaScript line you have:
$('h1.Logo a').text(userName);
On a side note, don't use the <center> element; it's not valid anymore. Use CSS instead. Also, a <span> might be more appropriate than an <a> tag in your example.
Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.
I am trying to make a similar bit of code like at the bottom of this page to leave a comment. I have the basic code but the output does not register new lines (or HTML, but that isn't important). I have the function below called on key-up on the text field. Any help would be greatly appreciated. Thanks
Here is the whole page (Now working)
<html>
<body>
<form>
<textarea id="text" onkeyup="outputText()"></textarea>
</form>
<div id="outputtext" style="width:500px;">
</div>
</body>
<script type="text/javascript">
function outputText()
{
var text = document.getElementById('text').innerHTML;
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
}
</script>
</html>
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
Have you tried getting the textarea contents as
var text = document.getElementById('text').value; instead?
I think it's good for you to take a look at how tools like jQuery can make your live easier in this kind of cases. Your particular question is a bit unclear however...can you give us more details?
You can use the <pre> (preformatted) tag so that html and carriage returns are represented without doctoring the field input
html:
<input id="text" type="text" />
<pre id="outputtext"></pre>
jQuery:
$(document).ready(function () {
$('#text').keyup(function () {
$('#outputtext').html($(this).val());
});
});
here's an easy one (that I'm struggling with)! I have a textarea, a button, and an empty div. All I want to do is insert the updated contents of the textarea into the div onClick of the button. Here's what I've got so far:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function get_text() {
$("#preview").replaceWith( $("#editor").val() );
}
</script>
</head>
<body>
<form>
<textarea name="editor" id="editor">GrumbleCakes</textarea>
<input type="button" value="Preview" onclick="get_text();" />
</form>
<div id="preview"></div>
</body>
</html>
It works the first time you click the button... with the value that was in the textarea on page load ("GrumbleCakes"), but that's it. It won't work with any updated text.
You can set the innerHTML or text content of the preview div by using the html or text functions:
$("#preview").html($("#editor").val());
.replaceWith actually replaces the DOM element. So the div is removed and replaced with the text. Subsequent calls to the function will no longer find the div, since it's been removed.
I think you want to use
.html($("#editor").val()).
Both
$('#preview").html($("#editor").val())
and
$("#preview").text( $("#editor").val())
should work.
However, .html will allow anyone to inject html or javascript into your site leaving it wide open for cross-site scripting attacks...
jikes!!
man you are replacing div with the contents of the textarea. use this function instead:
function get_text(){
var t=$("editor").val();
$("#preview").text(t);
}