简体   繁体   中英

How do I add an HTML element to this line of javascript code?

I have the following line of code in my javascript:

$('form #fullvalue').val('Monthly Payment: '+fullvalue2+'pm');

What I need to do is wrap the words "Monthly Payment" in a span element.

I coded it like this (see below), but then it doesn't pick up that it's an html element, it outputs the html as text:

$('form #fullvalue').val('<span>Monthly Payment: </span>'+fullvalue2+'pm');

* UPDATE * Sorry for the confusion, but I'm not trying add a span to a text field. It's for a line of text inside my form, but not a text or text area field - it's just a normal line of text that appears inside the form. The "fullvalue2" javascript code outputs a result from a calculator in the form. And I'm simply trying to add the text "Monthly Payment", which should be wrapped in a span, before "fullvalue2"

You can't.

The value of a form control can only be plain text.

If you need markup, then you need to use something more complicated (such as a div with contentEditable set and a pile of JS to read it back when you want to use the data).

To set HTML of a node, use $.html , $.val is for form fields.

 $('button').click(function(){ var fullvalue2 = $('#val').val(); $('form #fullvalue').html('<span>Monthly Payment: </span>'+fullvalue2+'pm'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id="val" value="123.34"/> <span id="fullvalue">Original value</span> </form> <button>Change HTML</button> 

使用label元素在form包含有关inputtextarea元素的描述性文本, for使label元素的属性引用与label元素关联的inputtextarea id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM