I'm new to jquery and javascript, so maybe this is a silly question but i'm having problems setting the value obtained from a selected option in select2 to a text input. This is my code:
<head>
<!-- stylesheets -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<!-- scripts -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(function(){
// turn the element to select2 select style
$('.select2').select2({
placeholder: "Select a state"
});
var data = $(".select2 option:selected").text();
$("#test").val(data);
});
</script>
</head>
<body>
<p>select2 select box:</p>
<p>
<select class="select2" style="width:300px">
<option> </option>
<option value="AL">Alabama</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</select>
</p>
<input type="text" id="test">
</body>
</html>
Any ideas of what i'm doing wrong?
Thanks!
simply you can do this:
$('#your-select-id').on("change", function(e) {
console.log($("#your-select-id").val())
});
As per the docs https://select2.org/programmatic-control/events#event-data
$('.select2').on('select2:select', function (e) {
var data = e.params.data;
$('#test').val(data.text);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With