반응형

 

[javascript] 현재 시간 select로 잡기


시간을 select로 직접 선택할 수 있게끔 하는 방법도 있지만 select를 이미 현재 시간으로 선택 되게끔

설정하는 방법도 있습니다. 먼저 html에 해당 내용을 넣어주세요.



<select class="hour"></select>시
<select class="minute"></select>분
<script src="https://code.jquery.com/jquery-3.5.1.min.js"><script>


그리고 각 select에 들어갈 소스를 <script></script> 사이로 아래 내용을 넣어주세요.


 

var html = '';
for (var i = 0; i < 60; i++) {
  html += "<option value = '" + i + "' >" + i + "</option>";
}
$('.minute').append(html);

var htm = '';
for (var j = 0; j < 24; j++) {
  htm += "<option value = '" + j + "' >" + j + "</option>";
}
$('.hour').append(htm);




이렇게 하면 option값을 별도로 넣지 않아도 option 값이 자동으로 들어가는데요, 

여기에 이제 현재 시간을 자동적으로 선택할 수 있게끔 소스를 수정해줍니다. 



 

var html = '';
for (var i = 0; i < 60; i++) {
  html += "<option value = '" + i + "' >" + i + "</option>";
}
$('.minute').append(html);
var d = new Date();
var n = d.getMinutes();
$(".minute").val(n);

var htm = '';
for (var j = 0; j < 24; j++) {
  htm += "<option value = '" + j + "' >" + j + "</option>";
}
$('.hour').append(htm);
var dt = new Date();
var h = dt.getHours();
$(".hour").val(h);

$(".hour option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == h;
}).attr('selected', true);

$(".minute option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == n;
}).attr('selected', true);



위 소스를 넣고 화면에 구현해보면 현재 시간에 셀렉트가 맞게 들어가있는 것을 확인하실 수 있습니다. 




반응형