Append HTML to a form field using jQuery - javascript

Lets say I have a form field and I want to append a span tag to it. Is it possible to do this with jQuery?
I tried this code:
$("input").append("<span>My HTML to append</span>");
Or would I have to use something else to append HTML.
So it would be something like this:
<input><span>My HTML to append</span></input>
But that wouldn't work.
Something like when you add tags to the question on StackOverflow each tag is a block.
Edit: How did StackOverflow do it when adding tags to the question.

input elements cannot have any child elements, so you can't use append on them.
You can set their value by using jQuery's val method.
They won't render HTML in any case, if you set the value to <span>My HTML to append</span>, that's exactly what you'll see in the input.
Re your edit:
So it would be something like this:
<input><span>My HTML to append</span></input>
That's invalid HTML. Again input elements cannot have content, they're "void" elements. This is why you can't use append on them.
Re your comment below:
How did StackOverflow do it when adding tags to the question.
They don't. Instead, there's an input and when you complete a tag in the input, they remove it and put it in a span in front of the input, so you end up with:
<span>
<span class="post-tag">tag</span>
<span class="post-tag">another-tag</span>
</span>
<input type="text">
In any modern browser, right-click the tags input field and choose "Inspect element" to see this live.
Here's an very quick-and-dirty example of doing this (but there are lots of plugins out there for doing it — tagit, select2 [which one of my clients uses and loves], ...): Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Tags-Like Input</title>
<style>
.input-wrapper {
border: 1px solid #aaa;
}
.post-tag {
border: 1px solid #00a;
margin-right: 2px;
}
</style>
</head>
<body>
<div class="input-wrapper">
<input type="text" id="theInput">
</div>
<script>
(function() {
$("#theInput").on("keypress", function(e) {
if (e.which === 32) {
e.preventDefault();
addTag($.trim(this.value));
this.value = "";
}
});
function addTag(tag) {
$('<span class="post-tag"></span>')
.text(tag)
.insertBefore("#theInput");
}
})();
</script>
</body>
</html>

An input element cannot have any child nodes, so no, you can't.
You could set the value (using the .val() method) to a string of HTML if you like.
You could concatenate that string with the existing value.
var $in = $("input");
$in.val(
$in.val() + "<span>My HTML to append</span>"
);

As other's have pointed out input element cannot have a child element.
So in a tagging system the common approach is to use a input element to select a tag once you do that add it to a container element which is placed next to the input element and style it such a way that they look like a single control.
In a very crude way you can use .after()/.before() to do it like
$("input").after("<span>My HTML to append</span>");
But there are already many plugins available to do it, so I would recommend using one of them like select2

Related

How to find active tag formats using jQuery?

I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});

change visibility of span using jquery

I work on a durandal project.
I have span and button elements in html.
The span elements are hidden and I want to show these on button click.
My problem is that when I hide the span from html- it can't show it from javascript.
I saw this question (on link change visibility of label tag using jquery) and I tried all of the answers- nothing helped me.
(I tried using:
in html:
<span id="mySpan" hidden = "hidden">aaa</span>
or:
<span id="mySpan" style= "visibility:collapse">aaa</span>
or:
<span id="mySpan" style= "display:none">aaa</span>
in javascript:
$("#mySpan").show();
or:
$("#mySpan").css('visibility', 'visible');
I tried all of the optional combinations
)
Note: I want you to know that when I'm not hiding the span from the HTML, and try using toggle(), hide(), show() - it works well.
Example that does not work:
on html page:
<span id="mySpan" hidden = "hidden">aaa</span>
on javascript page:
$("#mySpan").show();
Your HTML is not OK!
Remember, spans are closed <span></span> this way, and not the way you are closing them! That way, only self-closing elements such as: input, img etc are closed!
Try to write this:
<span id="mySpan">Some text!</span>
The CSS would be:
#mySpan {
display: none; // you're using diaplay!
}
Now using jQuery either use this:
$('#mySpan').show()
Or this:
$('#mySpan').css('display', 'block');
Well, your code is all wrong.
The id attribute should only be used once per page. It is meant to be unique so that you can refer to it as a single point in the document. You should change it to class="mySpan" and then select them using $(".mySpan").
visible:collapse is invalid CSS. You probably meant to use visibility, yes?
diaplay:none is also invalid CSS. Probably a typo of display, yes?
There is a hidden attribute in the newest HTML spec (usually called HTML5). I am not sure if you are aware of it; if you are, and you are trying to use it, then you should put the following in your CSS file so that it works in browsers that have not yet implemented it:
*[hidden] {
display: none;
}
Follow-up:
Okay, you want to be able to toggle a span on and off by clicking on a button. This will do it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button id="myButton">Show/hide the span</button><br>
<span id="mySpan" style="display:none">This is a span with some text in it</span>
<script>
$(function() {
$("#myButton").click(function() {
$("#mySpan").toggle();
});
});
</script>
Seems to be an error in "diaplay"? Try to change:
<span id="mySpan" style="diaplay:none"/>
to:
<span id="mySpan" style="display:none"/>

Append data to css class - jQuery string operation

Please take a look at the following html.
EDIT: UPDATED THE HTML PART
<div id="html_editor">
<head>
<style type="text/css" >
.blog
{
border:2px solid grey;
width:auto;
}
<style>{customcss}</style>
</style>
</head>
</html>
</div>
Please take a look at the Css Class 'blog',i want to add some other values to that class through js/jQuery.
Actually it is a HTML editor ,on the body tag user selecting a the 'blog' element,so that time i want to give the user to set CSS for the blog,user changing the CSS on a text area,after that i want to append/rewrite the data to that 'blog' class.
Ex : user setting the class like the following
width:250px;
background:red;
key:value..etc..
so after that i want to change that 'blog' css class to
.blog
{
width:250px;
background:red;
key:value..etc..
}
How can i achieve this ? is there any way by using jQuery ??
UPDATE : Please check this image.
Thank you.
For an HTML like this:
<style id="mycss" type="text/css" >
.blog
{
border:2px solid grey;
color:black;
}
</style>
<div class="blog">This is a blog</div>
Try this js:
var style = document.getElementById("mycss");
newrule = document.createTextNode('.blog { color:red;}');
style.appendChild(newrule);
This isn't very efficient as it overrides the previous rule, but you can get the general method.
JSFiddle here
I went ahead and did the following test because I haven't done JavaScript in a while and I wanted to give it a go. The first method uses String.split to parse the textarea input and the second some basic regex. The regex will fail if there's more than one statement per line. They both put a syntax burden on the user greater than native CSS, so:
I think you should do what nikan suggested.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", '1.6.4');
console.debug('loading');
google.setOnLoadCallback(function() {
var input = $('#userinput').val();
var statements = input.split(';');
for (var statement in statements){
var style = statements[statement].split(':');
var name = $.trim(style[0]);
var value = $.trim(style[1]);
$('#target').css(name, value);
}
var very_basic_css_matching = /^ *([^:]+): *([^;]+);/gm;
while (matches = very_basic_css_matching.exec(input)){
$('#target').css(matches[1], matches[2]);
}
});
</script>
</head>
<body>
<textarea id="userinput">
width:250px;
height:10px;
background:red;
</textarea>
<div id="target">
</div>
</body>
</html>
With jquery is easy to access the current style and modify it:
http://jsfiddle.net/jedSP/7/
Try writing "color:white" or "background:green" in the text area, works in all browsers. When the user is done just use $("#style").html() to get the current CSS.
EDITED: Updated link... like this?
if you want this to happen in real time, its as easy as taking the value of the textarea and parsing it in javascript, and then applying the values with jquery like so
$('.blog').css({'property1':'value1','property2':'value2'});
now if you want to save these changes permanently, you will need to send the new css values to your server and store them in a database or something.
EDIT: to save it on the database...
You can get the value from the textfield like so.
var cssVal = $('#textfieldid').val();
And then use the jQuery ajax function to send the new value to your server.
http://api.jquery.com/jQuery.ajax/
I'm not going to go into all of the details of this, you can find database tutorials everywhere online, but then you want to take the value of that textfield that you sent to your server using jQuery, and save it in your database table that stores the css rule properties.
Then when you regenerate the page, you will just retrieve the new css value from your database.

jQuery .append() not appending to textarea after text edited

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();

Html/Javascript: Add Attribute to an HTML Control

Need: Find a way to add a valid tag/attribute/property to a normal html control.
What I have is some javascript/jquery adding a click event to a link that will show or hide a div. The idea is to do this using $(document).ready and an anonymous method to create the method called by onClick at the page load. When clicked, a div will be shown with some text. This is all well and good except I can't figure out how to set up the text so that this can be done on the page load. What I'd like is something like:
HI
so that I can do this:
$(document).ready
(
function()
{
$("..showItLink").click
(
function(event)
{
var containerPosition;
var createdDiv;
//see if the div already exists
createdDiv = $(this).children(".postComment");
if (createdDiv.length == 0)
{
//This is where the attribute is used so that the CreateDiv
//method can take the textToShow and fill the div's innerText
//with it V V V V V V
createdDiv = CreateDiv(this.textToShow, "postComment");
$(this).append(createdDiv);
$(this).children(".postComment").hide();
}
$(createdDiv).toggle();
event.preventDefault();
}
);
}
);
Now besides not being xhtml valid (meh), this only works in IE. Firefox just says it doesn't exist. (this.textToShow) I could use something like rel or rev, but that seems just as hackish. I was wondering if there is a valid way of doing this.
Solution from answer below
comment = $(".showItLink").attr("comment");
...
createdDiv = CreateDiv(comment, "postComment");
Paired with:
<a href="http://www.theironical.com" class="showItLink" comment="hihihi" >HI</a>
If you're using JQuery, just get and set the attributes with .attr().
Get: this.attr("textToShow")
Set: this.attr("textToShow", value)
The way you add an attribute to an html control is by using the
element.setAttribute("attributeName", "attributeValue") where "element" is the element you want to add the attribute to.
To get an attribute you use getAttribute("attributeName");
You can't get away with adding custom attributes to HTML elements whilst still being valid. It will generally work in current browsers, but it's a bit fragile in that if you happen to pick a name that is in use (now or in the future) as an HTML or JavaScript property by any browser, the clash will stop it from working.
HTML5 proposes attributes whose names start with “data-​” as valid extension mechanisms. You could also consider namespaced elements in XHTML; this still isn't technically “valid XHTML” by the DTD but at least it is safe from collisions.
<a href="..." class="showItLink" textToShow="This is the text to show">HI
I suggest using the ‘title’ attribute for this particular purpose.
The best way to do this kind of thing is to hide the text in another element and then toggle that element. Try something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>clear test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#show-it").click(function() {
$("#message").toggle();
});
});
</script>
</head>
<body>
<div>
<a id="show-it" href="javascript:void(0);">show it</a>
<div id="message" style="display:none;"> hidden message</div>
hello world
</div>
</body>
</html>
If your textToShow attribute was an expando property, then this.textToShow would not return undefined, but since it is a custom attribute, you need to use jQuery's this.attr("textToShow") or the standard DOM this.getAttribute("textToShow").

Categories