Reputation: 1093
In my Ruby-on-Rails project, I want to add a string from the bootstrap datepicker to a hidden field. I need to reference a input class, but I don't know how.
This is my form:
<%= simple_form_for([@event, @dateevent]) do |f| %>
<%= hidden_field_tag(:date, @datelist) %>
<%= f.input :date, :as => :hidden, :input_html => { :value => "placeholder" } %>
<%= f.button :submit %>
<% end %>
This is my implementation of the bootstrap datepicker:
<input type="text" class='datepicker' >
<script type="text/javascript">
$(document).ready(function(){
$('.datepicker').datepicker({
multidate: true,
format: 'dd-mm-yyyy'
});
});
</script>
I created a button, that adds the chosen dates to the hidden field:
<button class="btn3">Add dates to the hidden field</button>
<script>
$(document).ready(function(){
$(document).on('click', ".btn3", function () {
var datelist = $(".listb").text();
document.getElementById('date').value = datelist;
});
});
</script>
To check, if the button really works, I did this:
<div class="listb">2016-2-2</div>
And when I press the button, 2016-2-2 is getting added to the hidden field, it is working.
Then I opened Firebug in Firefox and clicked on the field, where the bootstrap datepicker puts the chosen dates, it looks like this:
<input class="datepicker" type="text"></input>
In my Javascript code of the button, I tried these lines of code, but neither worked:
var datelist = $(".datepicker").text();
var datelist = $(".datepicker").val();
What do I need to type in, so the string of the field from bootstrap datepicker is added to datelist? Any ideas? Thanks in advance!
This is the full page:
<h2>Neuer Event</h2><br>
<input type="text" class='datepicker' >
<script type="text/javascript">
$(document).ready(function(){
$('.datepicker').datepicker({
multidate: true,
format: 'dd-mm-yyyy'
});
});
</script>
<br>
<div class="listb">2016-2-2</div>
<button class="btn3">Add dates to the hidden field</button>
<%= simple_form_for([@event, @dateevent]) do |f| %>
<%= hidden_field_tag(:date, @datelist) %>
<%= f.input :date, :as => :hidden, :input_html => { :value => "placeholder" } %>
<%= f.button :submit %>
<% end %>
<script>
$(document).ready(function(){
$(document).on('click', ".btn3", function () {
var datelist = $(".listb").text();
document.getElementById('date').value = datelist;
});
});
</script>
Upvotes: 1
Views: 7158
Reputation: 1093
Interestingly, this works:
var datelist = $("input.datepicker").val();
Upvotes: 0
Reputation: 420
you can use
//this version
var datepicker = $('.datepicker').datepicker()
.on('changeDate', function(e) {
$('#date').val($(e.currentTarget).val());//1
$('#date').val(datepicker.getDate());//2
});
//or bootstrap 3
var datepicker = $('.datepicker').datepicker()
.on('dp.change', function(e) {
e = {
date, //date the picker changed to. Type: moment object (clone)
oldDate //previous date. Type: moment object (clone) or false in the event of a null
}
});
Upvotes: 2