Add/remove content to/from textarea

Hello all,
I want to make like the toggle to add the content if it’s not there and delete it if it’s already there. I think it should be some function like this:
if ( content found ) {
delete it;
} else {
add it;
}, but i don’t know how to express “content found” in javascript… In PHP that would look like
if ( str_replace(re, “”, $string, $count) > 0) {
delete it;
} else {
add it;
}
What should i change in my script?


<script type="text/javascript">		
    function attachMe(elem) {
	var txt = $("#post");
	var re = new RegExp(elem, 'gi');
	txt.val( txt.val().replace(re, ''));
	txt.val( txt.val() + elem);
	return false;
}
</script>
<form action="<?= $url; ?>" method="POST">
<label for="heading">Antrašt&#279;</label>
<br />
<input type="text" name="heading" id="heading" value="<?= htmlspecialchars($data['heading']); ?>" />
<br />
<label for="post">Turinys</label>
<br />
<textarea type="text" id="post" name="post"><?= htmlspecialchars($data['post']); ?></textarea>
<br />
<input type="submit" name="submit" value="Išsaugoti" />
</form>
<a href="#" onClick="return attachMe('<?= $row['url']; ?>');">Add/remove</a>

Thank you for any help!

Hi, welcome to sitepoint :slight_smile:

All strings in javascript have match and replace functions which work with regular expressions. You can use match to check if the substring is present and replace to remove it.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>eggsample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" charset="utf-8">
function attachMe(text) {
	var elm = document.getElementById('content');
	var re = new RegExp(text, 'gi');
	if (elm.innerHTML.match(re)) {
		elm.innerHTML = elm.innerHTML.replace(re, '');
	}
	else {
		elm.innerHTML += text;
	}
}
</script>
</head>
<body>
	<p id="content">This is just a simple EXAMPLE.</p>
	<a href="#" onclick="attachMe('EXAMPLE');">Add/remove</a>
</body>
</html>

Hope it helps,

Thanks a lot! I have already done this by having two separate functions but this is a lot better!:slight_smile: