Saya memiliki HTML berikut:

<input type="date" name="order_date" id="order_date"/>

Setelah memperbarui bidang, saya ingin menampilkan nilai bidang itu dalam teks biasa di dua tempat lain pada halaman HTML yang sama, secara waktu nyata, saat tanggal bidang diperbarui. Bagaimana?

JS mencoba:

<p>The date selected was <span id="place_one"></span></p>
<p>And using the date of <span id="place_two"></span></p>

$(document).ready(function(){
    $("#order_date").change(function(){
        $('#place_one').text($("#order_date").val());
        $('#place_two').text($("#order_date").val());
    });
})
-1
Dennis 28 Oktober 2019, 18:16

2 jawaban

Jawaban Terbaik
let orderDate = document.getElementById('order_date');
orderDate.addEventListener ("change", function () {
  let showHeres = Array.from(document.getElementsByClassName('show_here'));
  let value = this.value;
  showHeres.forEach(function(showHere) {
     showHere.innerText = value;
  });
});
<input type="date" name="order_date" id="order_date"/>

<p>The date selected was <span class="show_here"></span></p>
<p>And using the date of <span class="show_here"></span></p>

EDIT: Solusi Anda juga berfungsi:

$(document).ready(function(){
    $("#order_date").change(function(){
        $('#place_one').text($("#order_date").val());
        $('#place_two').text($("#order_date").val());
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="order_date" id="order_date"/>

<p>The date selected was <span id="place_one"></span></p>
<p>And using the date of <span id="place_two"></span></p>
1
Mischa 28 Oktober 2019, 15:36

Dengan asumsi Anda ingin memformat nilai daripada menampilkannya sebagai tanggal unix, Anda dapat memformatnya ke lokal tertentu.

MISALNYA:

$(function(){
  $("#order_date").on("input",function(){
    var $input = $(this),
    val = $input.val(),
    date = new Date(val),
    longformat = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
    $(".live_order_date").each(function(){
      var locale = $(this).data("locale") || "en-GB",
      verbose = $(this).data("verbose"),
      opts = (verbose)?longformat:{};
      $(this).text(date.toLocaleDateString(locale,opts));
    })
  });
});
span {color:#666699;
font-style:italic;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="order_date" id="order_date"/>
<p>The date selected was <span class="live_order_date" data-locale="en-GB" data-verbose="true">...</span></p>
<p>And using the date of <span class="live_order_date" data-locale="en-GB">...</span><br/>
(or <span class="live_order_date" data-locale="en-US">...</span> if you're in the US)</p>
<p>What's that? you need it in Hindi <span class="live_order_date" data-locale="hi-IN" data-verbose="true">...</span>
1
Moob 28 Oktober 2019, 15:49