gtilflm gtilflm - 5 months ago 7
jQuery Question

Removing a class from value in an <input> tag

I have an

<input>
tag with some HTML as the value. I want to remove any
<span>
s that have the class of "emphasis", but still retain the content in the
<span>
. I also don't want any other
<span>
s removed.

Example Below:

This:

<input type="hidden" name="answer" id="answer" value="<span class="emphasis"><div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div></span>"


should end up as:

<input type="hidden" name="answer" id="answer" value="<div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div>"`


I've tried using jQuery with this fiddle (https://jsfiddle.net/0xgx04pq/4/)...



function remove_emphasis_class (){
var content = $('#answer').val(answer);
var content_after = content.filter('span.emphasis').contents().unwrap();
$('#answer').val(content_after);
alert(content_after);
}

.emphasis {
background: orange;
font-weight: bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" value="2 + 5 = <span class='emphasis'>7</span>" name="answer" id="answer">
<br><br>
<button onclick="remove_emphasis_class();">Remove Class</button>





...but it's not working.
content_after
ends up coming back as "[object Object]" Any ideas?

Answer

Basic idea

//using string instead of reading value of the input aka var str = $(".foo").val();
var str = "2 + 5 = <span class='emphasis'>7</span>";
//convert the string to html
var temp = $("<div>").html(str);
//find the span and unwrap it
temp.find(".emphasis").contents().unwrap();
//get the html string without the span
var updated = temp.html();
//display it
console.log(updated);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

other option is to just read .text() instead of .html() and it will strip all html.