I was trying to get date picker on clone rows in the table.But it is not happening
my table code as follows:
<input type="text" class="form-control dp4 dob4" autocomplete="off" name="date[]" required>
<input type="button" class="btn btn-default addButton" value="Add" />
and javascript for clone row as follows:
$(function() {
$("#table-data").on('click', 'input.addButton', function() {
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length - 1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function() {
var el = $(this).find(':first-child');
var id = el.attr('id') || null;
if (id) {
var i = id.substr(id.length - 1);
var prefix = id.substr(0, (id.length - 1));
el.attr('id', prefix + (+i + 1));
el.attr('name', prefix + (+i + 1));
}
});
$clone.find('input:text').val('');
$tr.closest('table').append($clone);
});
$("#table-data").on('change', 'select', function() {
var val = $(this).val();
$(this).closest('tr').find('input:text').val(val);
});
});
and my date picker code as follows:
$('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
Please help to solve this issue.
Thanks.
There is workaround to it,
How it Works:
Need to remove the class hasDatepickerfrom the cloned elements,because this is what is preventing the datepicker from getting attached to the specific element.
Need to remove the id attribute from each of the cloned elements else .datepicker() will assume that datepicker is added to this element.
After that call .datepicker() on cloned element.
JS Code:
$("#table-data").on('click', 'input.addButton', function () {
...
$clone.find('.dob4').removeAttr('id').removeClass('hasDatepicker');
$clone.find('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
...
});
Live Demo # JSFiddle
Related
I don't understand why when I use the condition value like a > b but it doesn't work properly, maybe because of the value a = decimal. following my code:
HTML
<input type="text" class="form-control" name="numberdays" id="numberdays" value="10.0/>
<input type="text" name="cutii" id="cutii" value="9.0">
<button class="btn btn-primary waves-effect" id="subcut" type="submit" disabled>
SCRIPT
cutifrom.addEventListener('input',()=>{
if (cutii.value > numberdays.value) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
the result is that my button is disabled, it shouldn't be.
here's my js. actually number days I use the datepicker and generate numbers that are automatically generated. maybe because it's the condition that I use the operator is not detected.
JS for datepicker
<script type="text/javascript">
$(document).ready(function(){
let $fromDate = $('#fromdate'),
$toDate = $('#todate');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
});;
});
$(function() {
let $fromDate = $('#fromdate'),
$toDate = $('#todate'),
$numberDays = $('#numberdays'),
$numberCuti = $('#cuti');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
$numberDays.val(calculateDateDiff($toDate.val(), $(this).val()));
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
$numberDays.val(calculateDateDiff($(this).val(), $fromDate.val()));
});
cutifrom.addEventListener('input',()=>{
if (parseFloat(cuti.value) >= parseFloat(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
function calculateDateDiff(endDate, startDate) {
if (endDate && startDate) {
let e = moment(endDate),
s = moment(startDate);
return e.diff(s, "days");
}
return null;
}
});
</script>
Your value is a String type and the comparison is not like Number, try converting the value to a number and see if it works.
You need to change the code to this form:
cutifrom.addEventListener('input',()=>{
if (Number(cutii.value) > Number(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
Good Luck :)
I have this problem when I'm trying to display a number of fields (tests, date, time), and onclick on those datepicker is supposed to run and disable the past dates, if I put the code outside the JavaScript it works just fine, so there must be something wrong with how I $.each loop it or with the append, but somehow I am not getting it to work
<script type = "text/javascript" >
$(document).ready(function() {
$("#select_test").change(function() {
var optionVal = [];
$.each($("#select_test option:selected"), function() {
if ($.inArray($(this).text(), optionVal) == -1) {
optionVal.push($(this).text());
}
});
var myselect = $('<select>');
var mydiv = $('<div>');
$.each(optionVal, function(index, key) {
mydiv.append("<tr><td><h5 class='wizard-title'>" + key + "</h5></td><td> <div class='col-sm-10'><div class='input-group date' data-provide='datepicker' data-date-format='dd-mm-yyyy'><input type='text' class='form-control datepicker dates' id='data-date' placeholder='Enter Test Date' name='testdate[]' value=''><div class='input-group-addon'><span class='glyphicon glyphicon-th'></span></div></div></div></td><td><div class='col-sm-12'><select name='testtime[]' class='form-control'><option value=''>Select Time</option><option value='0:00'>0:00</option><option value='1:00'>1:00</option><option value='2:00'>2:00</option><option value='3:00'>3:00</option><option value='4:00'>4:00</option><option value='5:00'>5:00</option><option value='6:00'>6:00</option><option value='7:00'>7:00</option><option value='8:00'>8:00</option><option value='9:00'>9:00</option><option value='10:00'>10:00</option><option value='11:00'>11:00</option><option value='12:00'>12:00</option><option value='13:00'>13:00</option><option value='14:00'>14:00</option><option value='15:00'>15:00</option><option value='16:00'>16:00</option><option value='17:00'>17:00</option><option value='18:00'>18:00</option><option value='19:00'>19:00</option><option value='20:00'>20:00</option><option value='21:00'>21:00</option><option value='22:00'>22:00</option><option value='23:00'>23:00</option></select></div></td></tr>");
});
$('#testsdetails').empty().append(mydiv.html());
});
});
</script>
I have called datepicker in below script.
<script>
$(document).on('click', '.dates', function() {
var dateToday = new Date();
$(this).datepicker({
minDate: 0
}).focus();
$(this).removeClass('datepicker');
});
</script>
I have been unable to replicate an issue with the code you provided.
$(document).ready(function() {
$("#select_test").change(function() {
var optionVal = [];
$.each($("#select_test option:selected"), function() {
if ($.inArray($(this).text(), optionVal) == -1) {
optionVal.push($(this).text());
}
});
var myselect = $('<select>');
var mydiv = $('<div>');
$.each(optionVal, function(index, key) {
mydiv.append("<tr><td><h5 class='wizard-title'>" + key + "</h5></td><td> <div class='col-sm-10'><div class='input-group date' data-provide='datepicker' data-date-format='dd-mm-yyyy'><input type='text' class='form-control datepicker dates' id='data-date' placeholder='Enter Test Date' name='testdate[]' value=''><div class='input-group-addon'><span class='glyphicon glyphicon-th'></span></div></div></div></td><td><div class='col-sm-12'><select name='testtime[]' class='form-control'><option value=''>Select Time</option><option value='0:00'>0:00</option><option value='1:00'>1:00</option><option value='2:00'>2:00</option><option value='3:00'>3:00</option><option value='4:00'>4:00</option><option value='5:00'>5:00</option><option value='6:00'>6:00</option><option value='7:00'>7:00</option><option value='8:00'>8:00</option><option value='9:00'>9:00</option><option value='10:00'>10:00</option><option value='11:00'>11:00</option><option value='12:00'>12:00</option><option value='13:00'>13:00</option><option value='14:00'>14:00</option><option value='15:00'>15:00</option><option value='16:00'>16:00</option><option value='17:00'>17:00</option><option value='18:00'>18:00</option><option value='19:00'>19:00</option><option value='20:00'>20:00</option><option value='21:00'>21:00</option><option value='22:00'>22:00</option><option value='23:00'>23:00</option></select></div></td></tr>");
});
$('#testsdetails').empty().append(mydiv.html());
});
$(document).on('click', '.dates', function() {
var dateToday = new Date();
$(this).datepicker({
minDate: 0
}).focus();
$(this).removeClass('datepicker');
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="select_test">
<option></option>
<option>1</option>
</select>
<div id="testsdetails"></div>
If you're still having an issue, please comment and provide more details. Let us know if you see any errors from Console. I suspect that this is a BootStrap page based on your HTML.
Hope that helps.
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
I am new to web issues and asking for advice. What I am trying to do is here:
1 - There is a Datepicker in the page with several javascript posts
2 - When the page is opened first time, the post methods should be called with initial values
3 - When I changed the date interval from Datepicker and press Submit button, the page should refresh with the new values and so the posts should be triggered again with the new values.
4 - When the page is refreshed with new values, I want the datepicker input parts (there are 2 of them) to show the updated values.
5 - Currently, there are no initial values. Also, the 4th item on this list is missing.
I am aware that there are a couple of basic things missing here, but I can't find out through the questions because of not knowing how the system works. Can anyone please fix my code a little?
Here is Datepicker and its JS part:
<li>
<div class="input-daterange input-group" id="datepicker" style="margin-top: 10px; align-content:center">
<input type="text" class="input-sm form-control" id="startDate" value="07/01/2015" maxlength="10" name="start" style="width:90px" />
<span class="input-group-addon">ile</span>
<input type="text" class="input-sm form-control" id="endDate" value="07/05/2015" maxlength="10" name="end" style="width:90px" />
</div>
</li>
<li>
<button id="goster" type="button" class="btn btn-default" onclick="goster()"
style="background-color:#C71F45;color:white;
margin-top:10px; margin-left:10px">
Göster
</button>
</li>
<script>
function goster() {
startDate = document.getElementById('startDate').value;
endDate = document.getElementById('endDate').value;
var url = "http://localhost:50523/Home/Index?startDate=" + startDate + "&endDate=" + endDate;
window.location.replace(url);
}
</script>
<script>
$(document).ready(function () {
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
$('.input-daterange').datepicker({
format: "mm/dd/yyyy",
autoclose: true,
language: "tr",
orientation: "top auto",
todayHighlight: true
});
var startDate = QueryString.startDate;
var endDate = QueryString.endDate;
$.post(
"/api/getUserTotalExp?startDate=" + startDate + "&endDate=" + endDate,
{ data: {} },
function (data) {
$('#totaluserexp').html(data + " saat");
}
);
$.post(
"/api/getUserExpDaily?startDate=" + startDate + "&endDate=" + endDate,
{ data: {} },
function (data) {
...
}
);
});
</script>
Only need a single onReady (you did that)
Put the code in the code and not in the markup (goster() call)
Since $.post is really an ajax shortcut, I will break that out a
bit so we can deal with the data a bit more elegantly perhaps. (I
used it to put the .done promise on the jqXHR to use (runs when
the ajax completes with success)
Odd that the datepicker is not on the inputs? Perhaps I do not know
something but I would put them ON the inputs (how you handle that in
reality is up to you.
Get the CSS/style out of the markup (leave that to you)
Address the issue with the post/page refresh - put that in a cookie (google that, suggest the $.cookie plugin perhaps?)
Markup and code:
<li>
<div class="input-daterange input-group" id="datepicker" style="margin-top: 10px; align-content:center">
<input type="text" class="input-sm form-control" id="startDate" value="07/01/2015" maxlength="10" name="start" style="width:90px" /> <span class="input-group-addon">ile</span>
<input type="text" class="input-sm form-control" id="endDate" value="07/05/2015" maxlength="10" name="end" style="width:90px" />
</div>
</li>
<li>
<button id="goster" type="button" class="btn btn-default" style="background-color:#C71F45;color:white;
margin-top:10px; margin-left:10px">Göster</button>
</li>
and code:
$(document).ready(function () {
$('#goster').on('click', function () {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
goster(startDate, endDate);
});
$('input.input-sm').datepicker({
format: "mm/dd/yyyy",
autoclose: true,
language: "tr",
orientation: "top auto",
todayHighlight: true
});
function goster(startDate, endDate) {
PostUserExp(startDate, endDate);
}
function PostUserExp(startDate, endDate) {
//var startDate = $('#startDate').val();
//var endDate = $('#endDate').val();
var myajaxExp = $.ajax({
url: "/api/getUserTotalExp",
data: {
"startDate": startDate,
"endDate": endDate
}
});
myajaxExp.done(function (data, textStatus, jqXHR) {
// what to do with data
$('#totaluserexp').html(data + "saat");
});
var myajaxDaily = $.ajax({
url: "/api/getUserExpDaily",
data: {
"startDate": startDate,
"endDate": endDate
}
});
myajaxDaily.done(function (data, textStatus, jqXHR) {
// what to do with data
$('#totaluserexp').html(data + "saat");
});
}
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
PostUserExp(startDate, endDate)
});
$.post("/api/getUserExpDaily",
{
'startDate': startDate,
'endDate': endDate
},
function (data) {
....
});
EDIT: data: { ... } was a typo. Oh well.
This will alway jQuery to format your dates. Now if you server is expecting JSON then it's a slightly different problem. However, the code above should work for your case.
https://developer.chrome.com/devtools
The Network tab will allow you to inspect your post. If you looked for the line getUserExpDaily POST. Then you can inspect the values, format, and response from your code.
I have an input field that asks user to pick a date and if the date is less than 30 days form today it will display some other contents. I am using jQueryUI datapicker and knockout.js for data binding and here is what I have so far JSFiddle but it's not working. What am I missing?
$(document).ready(function() {
$("#datepicker").datepicker();
});
$(document).ready(function() {
var viewModel = function() {
var self = this;
self.request_due_date = ko.observable();
self.request_due_date_rush = ko.observable(false);
self.request_due_date_rush_reason = ko.observable();
self.request_due_date.subscribe(function(dd) {
var cur = new Date(),
rush_date = cur.setDate(cur.getDate() + 30);
if (dd < rush_date) {
self.request_due_date_rush(true);
}
});
};
ko.applyBindings(new viewModel());
});
<div>Due Date:
<input id="datepicker" data-bind="text: request_due_date" type="text" />
</div>
<div data-bind="visible: request_due_date_rush">Reason For Rush:
<input data-bind="text: request_due_date_rush_reason" />
</div>
it's because when you create the datepicker object, the underlying input element gets moved around in the DOM, breaking the binding. Consider writing your own binding handler, like seen here:
jQuery UI datepicker change event not caught by KnockoutJS
You need to bind value, not text.
<input id="datepicker" data-bind="value: request_due_date" type="text" />
Also the value dd is a string and must be parsed to date, for example using moment.js
var days = moment().diff(moment(dd, "MM/DD/YYYY"), "days");
See updated fiddle
Thanks to #MaxBrodin for the insight (to bind value, not text) and this post I found the following solution to be working. Here is also the updated Fiddle
$(document).ready(function() {
$("#datepicker").datepicker();
});
$(document).ready(function() {
var viewModel = function() {
var self = this;
self.request_due_date = ko.observable();
self.request_due_date_rush = ko.observable(false);
self.request_due_date_rush_reason = ko.observable();
self.request_due_date.subscribe(function(dd) {
var date1 = new Date(dd);
var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var days = Math.ceil(timeDiff / (1000 * 3600 * 24));
self.request_due_date_rush(days < 30);
});
};
ko.applyBindings(new viewModel());
});
<div>Due Date:
<input id="datepicker" data-bind="value: request_due_date" type="text" />
</div>
<div data-bind="visible: request_due_date_rush">Reason For Rush:
<input data-bind="text: request_due_date_rush_reason" />
</div>