Drobne poprawki i ... CodePen [Edit]
<body>
<form action="" method="POST">
<fieldset>
<legend>Dodaj post</legend>
<div>
<div>
<input type="button" class="przycisk_post" value="B" id="bold">
</div>
<div>
<textarea name="post" cols="80" rows="30" id="post"></textarea>
</div>
<div>
<input type="submit" value="Dodaj">
</div>
<div>
</fieldset>
</form>
<script>
const b_bold = document.getElementById("bold");
const post_textarea = document.getElementById("post");
b_bold.addEventListener("click", () => {
// https://stackoverflow.com/questions/34968174/set-text-cursor-position-in-a-textarea
const start = post_textarea.selectionStart;
const end = post_textarea.selectionEnd;
const text = post_textarea.value.substring(start,end);
const text_before = post_textarea.value.substring(0, start);
const text_after = post_textarea.value.substring(end);
post_textarea.value = `${text_before}[b]${text}[/b]${text_after}`;
post_textarea.focus();
post_textarea.selectionEnd = end + 3; // "[b]".length
})
</script>
</body>
może to będzie przydatne CodePen [Edit]
<style>
.przycisk_post {
font: 1em monospace;
width: 20px;
text-align: center;
padding: 0;
cursor: pointer;
}
input[id="bold"].przycisk_post {
font-weight: bold;
}
input[id="italic"].przycisk_post {
font-style: italic;
}
input[id="underline"].przycisk_post {
text-decoration: underline;
}
</style>
<body>
<form action="" method="POST">
<fieldset>
<legend>Dodaj post</legend>
<div>
<div>
<input type="button" class="przycisk_post" value="B" id="bold">
<input type="button" class="przycisk_post" value="I" id="italic">
<input type="button" class="przycisk_post" value="U" id="underline">
</div>
<div>
<textarea name="post" cols="80" rows="30" id="post"></textarea>
</div>
<div>
<input type="submit" value="Dodaj">
</div>
<div>
</fieldset>
</form>
<script>
const b_posts = document.querySelectorAll(".przycisk_post");
const post_textarea = document.getElementById("post");
b_posts.forEach((b_post) => {
b_post.addEventListener("click", ({target}) => {
let code_open = [];
switch (target.id) {
case "bold":
code = ["[b]","[/b]"];
break;
case "italic":
code = ["[i]","[/i]"];
break;
case "underline":
code = ["[u]","[/u]"];
break;
}
// https://stackoverflow.com/questions/34968174/set-text-cursor-position-in-a-textarea
const start = post_textarea.selectionStart;
const end = post_textarea.selectionEnd;
const text = post_textarea.value.substring(start,end);
const text_before = post_textarea.value.substring(0, start);
const text_after = post_textarea.value.substring(end);
post_textarea.value = `${text_before}${code[0]}${text}${code[1]}${text_after}`;
post_textarea.focus();
const set_cursor_position = end + code[0].length;
post_textarea.selectionEnd = set_cursor_position;
})
})
</script>
</body>