Derp Derp - 3 months ago 8
jQuery Question

Jquery .text() concatenates instead of replaces

I have the following piece of code:

var customer = $('#customer');

customer.on('change', function(){
var dom = $(customer.find('option'));
var txt = dom.text();

$('#settingsoption1label').show().find('span.mdl-radio__label').text(txt);
});


Whenever I change
#customer
dropdown which is using the Select2 plugin, then the text from the
customer
element concatenates instead of replaces. I also tried adding
empty()
or
html('')
but nothing so far seems to work. I want the string to be replaced with the selected value instead of concatenated. Right now, when I change the dropdown, the value of the dropdown just adds to the end of the
span
element.

edit

Here's my HTML. I'm using Laravel.

<div class="form-group" >
@if(Auth::user()->is(3) || Auth::user()->is(1))
<label for="customer">Klant<br></label>
<select id="customer" name="customer" class="searchselect searchselectstyle searchgroup1">
@if(Request::old('customer') != NULL)
<option value="{{Request::old('customer')}}">{{$customers->where('id', intval(Request::old('customer')))->first()->name}}</option>
@endif
</select>
@endif
</div>

Answer

.text(): ...The result of the .text() method is a string containing the combined text of all matched elements. ....

So, you may try to get only the selected option:

    var customer = $('#customer');

    customer.on('change', function(){
        var dom = customer.find('option:selected');
        var txt = dom.text();

        $('#settingsoption1label').show().find('span.mdl-radio__label').text(txt);
    });
Comments