13

How can i put a div inside text field of a html form

<h2>Skills</h2>
<label for="skills">Choose your skills</label>
<input id="skills" type="text"/>

Please note my english is not good. So i can't tell you more.

I just want to render each skill in each div.

my jquery code(separated by comma) is :

$("input#skills").keydown(function(e){
   if(e.which===188){
      var skbl = $.trim($("input#skills").val());
      $("input#skills").append("<div style='background:green;'>"+skbl+"</div>");
});
1

4 Answers 4

24

You can't place any element inside an input. An input does not contain any HTML.


Explanation

In HTML, an input element is a void element, which means it does not have a closing tag and cannot contain any other elements inside it. This is because an input element is used to input data, such as text or numbers, and not to hold other HTML elements.

Consider this:

<input type="text" placeholder="Enter your name">

The <input> tag does not (and cannot) close with </input>, therefore it cannot contain any HTML. Neither does the value-attribute allow any HTML inside of it, only plain text.

5

The way to do that is to put the input and the wanted div inside a wrapper div, which should look like the input - the wanted width, length of the input and should have border. The input inside should be inline-block, without border and with smaller width and the div inside should be again inline-block, without border and with width, filling the rest of the width of the outside div. In this way you can make an image in input - the image is in the inside div, or clickable button inside the input.

See here: Clickable icon inside input field

4

You can not place any other element within an input element, see html-spec: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4

<!ELEMENT INPUT - O EMPTY -- form control -->

2

If you want to add the div inside the text field such as input or textarea then try this:

$("input#skills").val("<div style='background:green;'>"+skbl+"</div>");

This will update the whole field. You can try out this:

$("input#skills").append(new_val); 

Note:

You can use HTML value in a input. But you will get other server side issues. So that's why I guess Colandus was asking you not to write it there, however his idea is good to. Because you won't get to know how to edit it, and the browser would mess up the UI!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.