Reputation: 9301
Trying to change text attribute of an option using its value as a variable.
My trying doesn't work, any help, pls.
Expecting result is:
<option value = 2>earth</option>
var x = 2
var str = 'earth';
$('button').on('click', function(){
$('#sela:option[value = ' + x + ']').attr('text', str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='sela'>
<option value = 1>lorem</option>
<option value = 2>ipsum</option>
</select>
<br><br>
<button>CLICK</button>
Upvotes: 0
Views: 42
Reputation: 26854
You have to use $('#sela>option[value = ' + x + ']')
to select the direct option
child of #sela
.
And use text()
to update the option text.
var x = 2
var str = 'earth';
$('button').on('click', function() {
$('#sela>option[value = ' + x + ']').text(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='sela'>
<option value=1>lorem</option>
<option value=2>ipsum</option>
</select>
<br><br>
<button>CLICK</button>
Upvotes: 1