简体   繁体   中英

How to change the “selected” text to “bold / unbold” which is present in input tag “using html and JavaScript” only

I am trying to select a text/character from an input tag and when i press a bold button, selected text should change to bold and when the button is pressed again the selected text should change to normal.

here is my code but its not working.

<body>
<input type="text" name=inp id="inp">

<button onclick="getSelectedText();"><b>B</b></button>


<script>
    document.getElementsByTagName('input').mouseup(function(){
    getSelectedText().style.fontWeight="bold";
});

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
</script>

i think: the function returns a string, it is not an element in the document and has no style attribute

I think this is what you are trying to do.

 <input type="text" name=inp id="inp"> <button onclick="bold()"><b>B</b></button> <script> function bold() { var inp = document.getElementById('inp'); inp.style.fontWeight = inp.style.fontWeight == 'bold'? 'normal': 'bold'; } </script>

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