I am somewhat a beginner to jquery. I am having trouble creating a function to fill a textbox with the current date when a checkbox is clicked. I have the routine working on its own, but i would like to wrap it in a function so i can call it multiple times on the page. I have included the code here as well as a jsfiddle link
jsFiddle Link
html:
<span id="ContentPlaceHolder1_Label8">Start Date:</span>
<input name="ctl00$ContentPlaceHolder1$startdateSrvcTXT" type="text" id="ContentPlaceHolder1_startdateSrvcTXT" disabled="disabled" class="aspNetDisabled" />
<span id="ContentPlaceHolder1_Label11">Check to Start</span>
<input id="ContentPlaceHolder1_StartFillCHK" type="checkbox" name="ctl00$ContentPlaceHolder1$StartFillCHK" />
javascript:
/*----This works------
$('#ContentPlaceHolder1_StartFillCHK').click(function () {
if (this.checked) {
var myDate = new Date();
var prettyDate = (myDate.getMonth() + 1) + '.' + myDate.getDate() + '.' +
myDate.getFullYear();
$('#ContentPlaceHolder1_startdateSrvcTXT').val(prettyDate);
} else { //if not checked
$('#ContentPlaceHolder1_startdateSrvcTXT').val('');
}
});
*/
//this doesnt
function fillclick(txtid,checkid){
$("'" + checkid + "'").click(function () {
if (this.checked) {
var myDate = new Date();
var prettyDate = (myDate.getMonth() + 1) + '.' + myDate.getDate() + '.' +
myDate.getFullYear();
$("'" + txtid + "'").val(prettyDate);
} else { //if not checked
$("'" + txtid + "'").val('');
}
});
}
fillclick("#ContentPlaceHolder1_startdateSrvcTXT","#ContentPlaceHolder1_StartFillCHK");
You're querying by ID; you need to use # selectors:
$("#" + checkid).click
and
$("#" + txtid).val
Edit: You're already using them. There's no need to quote anything, they're already strings:
$(checkid).click
and
$(txtid).val
.
function fillclick(txtid,checkid){
$("#" + checkid).click(function () {
if (this.checked) {
var myDate = new Date();
var prettyDate = (myDate.getMonth() + 1) + '.' + myDate.getDate() + '.' + myDate.getFullYear();
$("#" + txtid).val(prettyDate);
} else { //if not checked
$("#" + txtid).val('');
}
});
}
I won't say anything about the function to get the current time. I will try to help you to do the next things.
You have a checkbox and a text box like these:
<input type="checkbox" id="ch1" name="ch1" />
<input type="text" id="current_time" name="current_time">
Now, use this code to do what you need:
$(document).ready(function() {
var myTime = getTime(); // getTime() is your own function to get the current time.
if ($('#ch1').is(':checked')) {
$('#current_time').val(myTime);
}
});
I hope I could help you.
Related
I'm getting a syntax error, but mainly because of my own not knowing how to write it.
I have tried, but I have become really stuck. Whilst I feel I am close.
My code is the following :
function hourselect_link_field(source_select, target_select){
var source_value = $('#' + source_select + ' :selected').val();
var time = parseInt(source_value.replace(":", ""));
var time_values = $("#" + target_select + " option").map(function () {
return this.value;
}).get();
$.each(time_values, function (index, value) {
var set_time = parseInt(value.replace(":", ""));
if (set_time <= time) {
$("#" + target_select + " option[value*= + value + ]").prop('disabled', true);
$("#" + target_select + " option[value*= + value + ]").addClass('disabled');
}
});
// console.log('time values = ' + time_values);
//alert(time);
}
And my problem basically lies
$("#" + target_select + " option[value*= + value + ]").prop('disabled', true);
$("#" + target_select + " option[value*= + value + ]").addClass('disabled');
And to be even more specific :
option[value*= + value + ]"
I seem not to be able to get the right syntax for this.
I want if value has : '00:00' that this should be set as disabled.
But it isn't working.
I get this syntax error
When trying :
$("#" + target_select + " option[value*= " + value + "]").prop('disabled', true);
It also doesn't work.
So what am I missing?
Edit : Answer
The solution as provided by #Casper & #Bilal Siddiqui
$.each(time_values, function (index, value) {
var set_time = parseInt(value.replace(":", ""));
if (set_time <= time) {
$(`#${target_select} option[value*='${value}']`).prop('disabled', true);
$("#" + target_select + " option[value*='" + value + "']").prop('disabled', true);
}
});
You can use old method or ES6 template literals.
let select1 = 'sel1';
let select2 = 'sel2';
let val = '00:00';
$(`#${select1} option[value*='${val}']`).prop('disabled', true).addClass('disabled');
$("#" + select2 + " option[value*='" + val + "']").prop('disabled', true).addClass('disabled');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
<option value="10">00:10</option>
<option value="00:00">00:00</option>
</select>
<select id="sel2">
<option value="10">00:10</option>
<option value="00:00">00:00</option>
</select>
Why not to try String Literals:
$(`#${target_select} option[value*='${value}']`).prop('disabled', true);
$(`#${target_select} option[value*='${value}']`).addClass('disabled');
Another approach
$("#" + target_select + " option").each(function () {
var set_time = parseInt(this.value.replace(":", ""));
if (set_time <= time) {
$(this).prop('disabled', true);
$(this).addClass('disabled');
}
});
Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I'm trying to format some json dates in a table to a more readable format. The string returned from the json looks like this "2015-06-29T10:00:00.000Z".
The time is not important, I just want to show the date as dd/mm/yyyy.
I have tried using new date(detestring) but i might have got this wrong, as its not working. Here is the full code.
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + new Date(this.starts_at) + "</td></tr>");
});
});
});
Any help much appreciated.
You have to create your own function which achieve your target.
function formatDate(stringDate){
var date=new Date(stringDate);
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
}
Your code:
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + formatDate(this.starts_at) + "</td></tr>");
You could use MomentJs to parse the first input and then format it to your desired format. Something like :
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + moment(this.starts_at).format("DD/MM/YYYY") + "</td></tr>");
});
});
});
See Format date to MM/dd/yyyy in javascript
First, parse it to a date with
var date = new Date(this.starts_at);
Second, print your date as desired
var dateStr = (date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear())
You will get "6/29/2015"
For your specific instance, it would be something like
$(document).ready( function() {
$.getJSON( 'opp.php', function(data) {
$.each(data.opportunities, function() {
var date = new Date(this.starts_at);
var dateStr = (date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear())
$("table#outtodaytomorrow").append("<tr><td>" + this.number + "</td><td>" + dateStr + "</td></tr>");
});
});
});
Breaking up the component into different pieces of memory such as "date" and "dateStr" makes it easier to read and understand.
I am trying to write a program that submits text on my website and I am having a lot of trouble trying to do a line break after the text because break line is being written as a string.
var main = function() {
var today = new Date();
var month = parseInt(today.getMonth() + 1);
var day = parseInt(today.getDate());
var year = parseInt(today.getFullYear());
$(".btn").click(function() {
var post = $(".status-box").val();
$("<li>").text(post + "<br>" + month + "/" + day + "/" + year).prependTo(".posts");
$(".status-box").val("");
$(".counter").text("140");
$(".btn").addClass("disabled");
});
$(".status-box").keyup(function() {
var postlength = $(this).val().length;
var charactersLeft = 140 - postlength;
$(".counter").text(charactersLeft);
if (charactersLeft < 0) {
$(".btn").addClass("disabled");
} else if (charactersLeft === 140) {
$(".btn").addClass("disabled");
} else {
$(".btn").removeClass("disabled");
}
});
$(".btn").addClass("disabled");
};
$(document).ready(main);
You are using .text() which will ALWAYS html-encode the text provided...use .html() instead
$("<li>").html(post + "<br>" + month + "/" + day + "/" + year).prependTo(".posts");
I am trying to make a ajax load of a table. I have 2 buttons "Free Cars", "Reservations". When click "Free Cars" load all info from database and on click of tr it redirects to an url.
$('.cars_table').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Then on click of "Reservations" I change the class of tbody :
$('#cars_table').removeClass('cars_table').addClass('res_made');
But it doesn't perform the script which
$('.res_made').on('click', 'tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
Instead it performs the first script and on click of reservations rows it goes to the .cars_table redirect url. With inspect element it shows that the class has changed but then it doesnt performs the script for that class. What is happening?
Event bindings happen on the DOM elements themselves. If you try to bind an event on all .res_made elements before there are any elements with this class, no events will be bound.
To solve your problem, you could bind your event once and check inside the handler which class is currently set.
You should dynamically bind the click events, because the class of the table can dynamically change. So to make it work in your case, you should change your javascript to the following:
$(document).on('click', '.cars_table tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'rental/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
$(document).on('click', '.res_made tr', function() {
var values = $(this).find('td').map(function() {
return $(this).text();
});
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
window.location.href = 'reservations/create/' + values[0] + '~' + startdate + ' ' + starttime + '~' + enddate + ' ' + endtime + '';
});
See this FIDDLE for an example. Of course, as an alternative, you could also bind the event once and check for the class of the table in the event handler, like Martin Denk suggested.