简体   繁体   中英

How to get value of date input and put it in innerHTML in javascript

Hi there i'm trying to get the input value of a date input in Javascript/Jquery so i can put it in an innerHTML.

I have the following code;

$("#input").change(function()
  {
    document.getElementById('output').innerHTML = document.getElementById("input").value ;
  });

Where as 'input' is the ID of the date select. And output is the ID of the in which i want the selected date to be visible.

It works with text field inputs but it doesn't work with the date select. Does anybody know a solution, preferably in JQuery. Thanks

Not a solution - but a slightly different approach for when you do get the value sorted - you are already using jQuery and you are using the change event handler - this means you can tidy up the code a bit:

$("#input").change(function()
  {
    $('#output').html($(this).val());
  });

But I would suggest that .text() is what you should be using to change the content of the output since you are trying to change the content not a HTML element.

$("#input").change(function()
  {
    $('#output').text($(this).val());
  });

And the other suggestion would be to check that you don't have elements with duplicate (#input) id's in your code.

You can achieve that using the jQuery approach below:

<script>
$("#input").change(function() {
    $('#output').append($('#input').html());
});
</script>

Achieving same result using JavaScript only:

<script>
document.getElementById("input").onchange = function() {
    updateValue()
};

function updateValue() {
    var input = document.getElementById("input").innerHTML;
    document.getElementById("output").innerHTML = input;
}
</script>

Oke i fixed this issue myself. Based on the console outputs i came to the conclusion that Ruby on Rails automatically assigns id's to the date select fields.

Based on those id's i made the following JQuery code:

 $("#date_3i").change(function()
  {
    $('#output').text(($(this).val()) + ' ' + ($("#date_2i").find(":selected").text()) + ' ' +  ($("#date_1i").val()) ) ;
  });
  $("#date_2i").change(function()
  {
    $('output').text( ($("#date_3i").val()) + ' ' + ($(this).find(":selected").text()) + ' ' + ($("#date_1i").val()) ) ;
  });
  $("#date_1i").change(function()
  {
    $('output').text( ($("#date_3i").val()) + ' ' + ($("#date_2i").find(":selected").text()) + ' ' + ($(this).val()) ) ;
  });

Case closed, thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM