Skip to content Skip to sidebar Skip to footer

Strip Html From Textarea On Button Click And Store The Stripped Text

I try to load the value of a textarea into a variable on button click, then stripe all html tags except of the html tags br and strong then save the new value into another variab

Solution 1:

One complete jQuery plugin would be:

jQuery.fn.extend({
    stripHtmlTags: function() {
        function getDivContent(input) {
        	return $('<div></div>').html(input.val());
        };
        function addCheckboxes(input) {
        	var div = getDivContent( input );
            input.siblings('.tags-checkboxes').remove();
            var tagsCheckboxes = $('<div class="tags-checkboxes"></div>');
            var fake = getDivContent(input);
            var allTags = [];
            fake.find('*').each(function(i) {
            	var thisTag = $(this).prop("tagName").toLowerCase();
                if( $.inArray(thisTag, allTags)==-1 ) {
                	allTags.push( thisTag );
                };
            });
            $.each(allTags, function(t, tag) {
            	var uniqueId = tag + '-' + Math.round(new Date().getTime() + (Math.random() * 100));
                tagsCheckboxes.append('<span class="strip-tags-option"><input type="checkbox" id="' + uniqueId + '" value="' + tag + '" checked="checked" /> <label for="' + uniqueId + '">' + tag + '</label></span>');
            });
            input.after( tagsCheckboxes );
            return tagsCheckboxes;
        };
        function addStripButton(input) {
        	var button = $('<button class="strip-tag-button">STRIP TAGS</button>');
            input.next().after( button );
            return button;
        }
        function strip(input, checkboxes) {
            var fake = getDivContent(input);
            var tagsArray = [];
            checkboxes.find('input').each(function(i) {
            	var thisCheckbox = $(this);
                if( thisCheckbox.is(':checked') ) {
                	tagsArray.push( thisCheckbox.val() );
                };
            });
            var tags = tagsArray.join(', ');
            console.log( tags );
            fake.find(tags).contents().unwrap();
            fake.find(tags).remove();
            input.val(fake.html());
            addCheckboxes(input);
        };
        return this.each(function() {
            var thisInput = $(this);
            if( !thisInput.hasClass('initialized') ) {
            	var checkboxes = addCheckboxes( thisInput );
                var stripButton = addStripButton( thisInput );
                stripButton.on('click', function(e) {
                    e.preventDefault();
                    strip(thisInput, checkboxes);
                });
                thisInput.on('input', function(e) {
                    checkboxes.remove();
                    checkboxes = addCheckboxes( thisInput );
                });
                thisInput.addClass('initialized');
            };
        });
    }
});
var message = $('#message');
message.val("\
<div>\n\
    <strong>Hello Universe</strong>\n\
    <a href='#' title='Test'>Test link</a>\n\
    <br><p>Spread good Vibes :)</p>\n\
</div>\
");
message.stripHtmlTags();
.strip-tags-option {
    display: inline-block;
    margin-right: 10px;
}
.strip-tag-button {
    border: 1px solid black;
    text-align: center;
}
.strip-tag-button:hover {
    cursor: pointer;
    color: white;
    background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    <textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea>
</p>

Also on JSFiddle.

Credits to this answer.


Solution 2:

I found the solution, there were two problems.

1. I had to append the created DIV to the DOM.

2. I returned already before the first cycle.

Now it works, and basically I just developed the equivallent from the PHP function strip_tags ;) Credits to karim79 for his contribution.

//init the textarea value for this example
$("textarea#message").val
(
  "<div>\n"+
  "<strong>Hello Universe</strong>\n"+
  "<br><p>Spread good Vibes :)</p>\n"+
  "</div>"
);

$("div#mybutton").on
(
  "click",
  function()
  {
    var textarea   = document.getElementById("message");
    var allText    = textarea.value;
    var newText    = strip_tags(allText, "br");
  
    //now do something with the new text
    textarea.value = newText;
  }
);

//strips all html tags from a string except the tags from the whitelist, and returns the new string. (this function works exactly as the PHP equivalent strip_tags  http://php.net/manual/de/function.strip-tags.php) 
function strip_tags(str, whitelist)
{  
    console.log("TEXT BEFORE STRIPE: (whitelist: "+whitelist+")\n\n"+ str);
    //Create a temporary div and initialize it with the value from the first param
    var tmp         = document.createElement("DIV");
    tmp.id          = "tmp";
    tmp.innerHTML   = str;
    
    document.body.appendChild(tmp);
    
    //Strip tags and return the whole stripped text
    $("#tmp *").not(whitelist).each(function(){
        if ($(this).is("br"))
        {
            $(this).remove();
        }
        var content = $(this).contents();
        $(this).replaceWith(content);
    });
    
    var newText = tmp.innerHTML;
    tmp.remove();
    
    console.log("----------------------------------------------------------");
    console.log("TEXT AFTER STRIPE: (whitelist: "+whitelist+")\n"+ newText);
    return newText;
}
div#mybutton {
  border: 1px solid black;
  width: 80px;
  text-align: center;
}

div#mybutton:hover {
  cursor: pointer;
  color: white;
  background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <textarea  id='message' autofocus maxlength="500" rows="4" cols="50"></textarea>
  <div id="mybutton"> PRESS </div>
</div>

Solution 3:

You can use regex for that

$(function() {
  var html = $('textarea').val();
  console.log(html.replace(/<(?!strong|br\/?)[^>]+>/g, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea><strong>foo</strong><br/><div>hello</div></textarea>

and if you want to have tags in variable you can use this code:

$(function() {
  var tags = ['strong', 'br\\/?'];
  var regex = new RegExp('<(?!'+tags.join('|')+')[^>]+>', 'g');
  var html = $('textarea').val();
  console.log(html.replace(regex, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea><strong>foo</strong><br/><div>hello</div></textarea>

Post a Comment for "Strip Html From Textarea On Button Click And Store The Stripped Text"