Sherly Kim Sherly Kim - 4 months ago 11
Ajax Question

ajax get text of the option value in html

I have a code that lists all the values i want written :

<option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}"


and I have setSelectedName in my .js file

function setSelectedName() {
$('#NameForTypeSearch').ready(function() {
$("#NameForSearch").change(function(){
$.ajax({
type: 'POST',
data: {keyname:$('#NameForSearch option:selected').text()}
});
});
});


I have text box named
NameForTypeSearch
and everytime the user selects an option, I want to use ajax to automatically input the selected text in
NameForTypeSearch
. I can't get to work on my html..

Answer

Try using the jquery val function to get the value of the option element, as well as to set the value of the input element.

$('#sel').change(function(){
    $('#output').val($(this).find('option:selected').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="text" id="output"/>