简体   繁体   中英

Superscript in input field of text type

I have a HTML input field like this:

<input id="op" type="text" value="0" />

I want to update the value of this field dynamically with some string containing superscript. It did not work and I tried this.

document.getElementById("op").value="a<sup>3</sup>" //don't work
document.getElementById("op").innerHTML="a<sup>3</sup>" //don't work

How can I get this to work? I could have tried to figure the rest myself but since I am already forced to ask this, I would like to tell what I am planning to do.

 var x=3; var y=2;
 document.getElementById("op").innerHTML="a<sup> x-y </sup>";

How about a plugin:

$.fn.superScript = function() {
    var chars = '+−=()0123456789AaÆᴂɐɑɒBbcɕDdðEeƎəɛɜɜfGgɡɣhHɦIiɪɨᵻɩjJʝɟKklLʟᶅɭMmɱNnɴɲɳŋOoɔᴖᴗɵȢPpɸrRɹɻʁsʂʃTtƫUuᴜᴝʉɥɯɰʊvVʋʌwWxyzʐʑʒꝯᴥβγδθφχнნʕⵡ',
        sup   = '⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ᴬᵃᴭᵆᵄᵅᶛᴮᵇᶜᶝᴰᵈᶞᴱᵉᴲᵊᵋᶟᵌᶠᴳᵍᶢˠʰᴴʱᴵⁱᶦᶤᶧᶥʲᴶᶨᶡᴷᵏˡᴸᶫᶪᶩᴹᵐᶬᴺⁿᶰᶮᶯᵑᴼᵒᵓᵔᵕᶱᴽᴾᵖᶲʳᴿʴʵʶˢᶳᶴᵀᵗᶵᵁᵘᶸᵙᶶᶣᵚᶭᶷᵛⱽᶹᶺʷᵂˣʸᶻᶼᶽᶾꝰᵜᵝᵞᵟᶿᵠᵡᵸჼˤⵯ';

    return this.each(function() {
        this.value = this.value.replace(/<sup[^>]*>(.*?)<\/sup>/g, function(x) {
            var str = '',
                txt = $.trim($(x).unwrap().text());

            for (var i=0; i<txt.length; i++) {
                var n = chars.indexOf(txt[i]);
                str += (n!=-1 ? sup[n] : txt[i]);
            }
            return str;
        });
    });
}

called like:

$('input').superScript();

Could probably be bound to keyup etc as well, and rather easily converted to plain javascript and not jQuery, but I just made it, so if it works, modify it to suit your needs ?

FIDDLE

<input> is not a container, and so does not 'contain' any html.

The value attribute of <input> must be plain text, so no you can't do what I believe you're attempting.

There are workarounds however, of varying usefulness, depending on what you really need to do. See Superscript text in HTML <input type="submit" />

Further, you might also find the use of 'editable' content in a <div> to be of value. See https://developer.mozilla.org/en-US/docs/Web/HTML/Content_Editable

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