The Codesee The Codesee - 6 months ago 16
jQuery Question

html elements only appear after space

I am using Javascript's

onkeyup
event to type the text entered into a
contenteditable
div into an input field.

When the user types into the div, they have the option to make the selected text bold or italic (this is done by highlighting the desired text and clicking one of the buttons).


  • If the user types 'hello' into the div and makes the text bold, it will display as
    hello
    in the input field (without
    <br>
    tags around the word).

  • If the user types 'hello' into the div and makes the text bold, then presses the spacebar, it will display as
    <b>hello</b>
    in the input field.



How do I make it so that html tags automatically appear around the words without having to press the spacebar?

<form method="post">
<button type="button" id="bold"><b>B</b></button>
<button type="button" id="italic"><i>I</i></button>
<div id="post" style="border: 1px solid;" contenteditable></div>
<input type="text" name="hiddenTextarea" id="hiddenTextarea">
<input type="submit">
</form>

<script>
$(document).ready(function() {
$('#bold').click(function() {
document.execCommand('bold');
});
});

$(document).ready(function() {
$('#italic').click(function() {
document.execCommand('italic');
});
});

var contentText = document.getElementById('post');
var hiddenInput = document.getElementById('hiddenTextarea');

// copy the text to input when the user writes in contentText div
contentText.onkeyup = function() {
hiddenInput.value = this.innerHTML; // 'this' is pointing to contentText
};
</script>


Here's a JsFiddle so you can see the issue for yourself: https://jsfiddle.net/u6oeu9dL/1/

Answer

The input only gets updated on keyup, you should instead move the code that updates the input to a named function so that you can call it on keyup and on style button click.

$(document).ready(function() {
  $('#bold').click(function() {
    document.execCommand('bold');
    updateInput();
  });
});

$(document).ready(function() {
  $('#italic').click(function() {
    document.execCommand('italic');
    updateInput();
  });
});

var contentText = document.getElementById('post');
var hiddenInput = document.getElementById('hiddenTextarea');

function updateInput () {
  hiddenInput.value = contentText.innerHTML
}

// copy the text to input when the user writes in contentText div
contentText.onkeyup = updateInput;

https://jsfiddle.net/u6oeu9dL/5/ (simplified)