Reputation: 43
How can I automatically show the Day in the text when choose in the drop down options using the .attr() in jquery?
This is my HTML code:
<select id="time">
<option day="M-W-F">07:00 - 08:00 am</option>
<option day="T-Th">08:30 - 10:00 am</option>
<option day="Saturday">7:00 - 10:00 am</option>
</select>
<input type="text" id="day" placeholder="Day" />
Jquery:
<script>
$(document).ready(function(){
$("#time").on('change', function(){
$("#day").val() == $("#time").val().attr('day');
})
})
</script>
Upvotes: 0
Views: 48
Reputation: 1
Additional notes
Because :selected is a jQuery extension and not part of the CSS specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :selected to select elements, first select the elements using a pure CSS selector, then use .filter(":selected").
jquery
<script>
$(document).ready(function(){
$("#time").on('change', function(){
$("#day").val($("#time option:selected").attr('day'))
})
})
</script>
Upvotes: 0
Reputation: 133403
You need to to pass the value to .val()
method and use :selected
to target the selected option
then use .attr()
$("#day").val($("#time option:selected").attr('day'))
I would recommend you to use data-*
custom attributes to store arbitrary data
$("#time").on('change', function() {
$("#day").val($("#time option:selected").data('day'))
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="time">
<option data-day="M-W-F">07:00 - 08:00 am</option>
<option data-day="T-Th">08:30 - 10:00 am</option>
<option data-day="Saturday">7:00 - 10:00 am</option>
</select>
<input type="text" id="day" placeholder="Day" />
Upvotes: 2