Search code examples
javascriptjqueryhtmloutputitalic

how to make part of an output in italic - JavaScript


There quite a few questions on the web and on this website about making italic fonts, but non mentions how to italic only part of a string.

In my case, there is a form I enter the book title, the author's name and the number sold. After clicking a button I want author's name and the number sold be normal but the book title to be in italic in the text area (output).

Coding for form:

<label for="txtName">Author Name</label>
<input type="text" id="txtName" size="50" placeholder="Eg, Darwin" maxlength="50">

<label for="txtTitle">Book Title</label>
<input type="text" id="txtTitle" size="40" placeholder="Eg, The Origin of Species" style="font-style:italic" maxlength="100">

<label for="txtNumber">Number Sold</label>
<input type="text" id="txtNumber" size="4" placeholder="Eg, 50000" maxlength="9">

When the user enters the book title, as they type title looks italic but the value will not stay in italic. After the required calculations is done at the end I want the title, author and the number shown in this order:

bTitle = bookForm.txtTitle.value;
bName = bookForm.txtName.value;
bNumber = bookForm.txtNumber.value;

concatBook = bTitle+" by "+bName+" sold "+bNumber+" Copies."

This concatBook will be shown in a text area via a function.

The only thing I want to be in italic is bTitle.

Thanks for reading my question


Solution

  • To add italic style (or wathever you want) you need to wrap the text you want to style in span tags. But you can't insert HTML inside a textarea. You should use a <div contenteditable="true"></div> instead.

    Take a look at this minimal demo.

    HTML:

    <div contenteditable="true"></div>
    

    CSS:

    span{
        font-style: italic;
    }
    

    JavaScript:

    var concatBook = "<span>by</span> sold Copies."
    $('div').html(concatBook);