georgia georgia - 2 months ago 8
HTML Question

jquery show data taken by select after removing parenthesis

I have an

html
select
and a
div
where I want to show a message depending on the select option. The
<select id='select1'>
shows options like
"Player1(Mike)"
and I want only the
"Player1"
to show up in the
<div id='logId1'></div>
.
I wrote the following code

<script>
$(document).ready(function(){

$("#select1").on("change", function() {
$("#logId1").html($(this).find(":selected").text(function(_, text) {
return text.replace(/\(.*?\)/g, "");
}));

});
});
</script>


It shows what I want but the result
"Player1"
shows up like it is selected.
I'm a newbie in jquery so any ideas are welcome.

Answer

Currently you are modifying the text of selected option, when you use .text(fn) method.

You need to get the .text() and then perform the desired operation.

$("#select1").on("change", function() {        
    $("#logId1").html($(this).find(":selected").text().replace(/\(.*?\)/g, ""));
});
Comments