javascript datepicker not activating - javascript

My problem is that my datepicker does not work when I create my input field through javascript.
I have a button which will generate the fields needed for the input. One of these is a datepicker. I have a function which brings up a small calendar for the user to pick from. It works for input fields that aren't created by the javascript function.
this is the javascript function to create an input field:
<script lang="javascript">
TestNo = 1; // This is input files added by default.
TestMax = 50;
TestMin = 1;
function Test_Addchild() {
if (TestNo <= TestMax) {
var div = document.createElement("div");
div.id = 'divfiles' + TestNo;
//div.style.width = "100px";
//div.style.height = "100px";
//div.style.background = "red";
//div.style.color = "white";
div.innerHTML = '<input size="35" type="text" id="Test' + TestNo + 'D" name="Test' + TestNo + 'D" value="Date ' + TestNo + '" class="form-control selector" autocomplete="off">';
document.getElementById('Tests').appendChild(div);
TestNo++;
$('#<%= NoOfTests.ClientID %>').val(TestNo-1);
return false;
}
else {
alert('Maximum ' + TestMax + ' Files are Allowed.');
return false;
}
}
function Test_Delchild() {
if (TestNo > TestMin) {
cnt = TestNo - 1;
element = document.getElementById('divfiles' + cnt);
element.parentNode.removeChild(element);
TestNo--;
$('#<%= NoOfTests.ClientID %>').val(TestNo-1);
return false;
}
else {
alert('All tests removed');
return false;
}
}
</script>
These are the buttons creating and deleting the input field:
Add more tests<br>
Remove tests<br>
And lastly the datepicker function
<script>
$(function () {
$(".selector").datepicker({
showOtherMonths: true,
selectOtherMonths: true
});
});
</script>
How do I get the datepicker function to work for dynamically created input fields?
Thank you in advance.

Related

Change label to match numeric part from ID

I have this HTML code:
<div id="wrapper">
<div class="row">
<label for="additional_1">Additional #1 :</label>
<input type="text" id="additional_1" name="pnr_remarks_modify[additional][]">
New - Remove
</div>
</div>
And I am adding (cloning) / removing the complete '.row' element with this code:
var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function() {
// clone the div
var row = $(".row").last();
var clone = row.clone();
// change all id and name values to a new unique value
$("*", clone).add(clone).each(function() {
if (this.id) {
this.id = (this.id).slice(0, -1) + cloneCntr;
}
if (this.name) {
this.name = this.name;
}
});
++cloneCntr;
$('#wrapper').append(clone);
});
$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
})
Every time I click on New I got a clone from the previous object but changing its ID. For example:
First Click on New
Additional #1 :
New - Remove
Second Click on New
Additional #1 :
New - Remove
But as you can see the for attr and the label text remain the same. I need to change them to (on each new clone):
for needs to be the same as the new ID
label text needs to be Additional # + cloneCntr
But I don't know how to achieve this part, can I get some help?
Here is the jsFiddle where I am playing around this
You can loop through all the rows each time one is added or removed and update based on row index. Use one function that gets called within both event handlers
$('#wrapper').on('click', '.addInput', function() {
var clone = $(".row").last().clone();
clone.find('input').val(''); // clear value on clone input
$('#wrapper').append(clone);
updateCounts();
});
$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
updateCounts();
});
function updateCounts() {
$('#wrapper .row').each(function(i) {
var num = i + 1,
$row = $(this),
inputId = 'additional_' + num;
$row.find('label').text('Additional #' + num + ' :').attr('for', inputId);
$row.find('input').attr('id', inputId)
});
}
DEMO
You can use another function to generate html with new id and for attribute like following.
function getRow(index){
return '<div class="row">' +
'<label for="additional_'+index+'">Additional #'+index+' :</label>' +
'<input type="text" id="additional_' + index + '" name="pnr_remarks_modify[additional][]">' +
'New - Remove' +
'</div>';
}
var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function () {
var clone = getRow(cloneCntr);
++cloneCntr;
$('#wrapper').append(clone);
});
DEMO

jQuery price calculator function is not working with tabs

I have been trying to get this working from last couple of days without any success. I have this price calculator function developed by a freelancer who is not reachable from last few weeks.
This function works fine without any JavaScript tabs but not quite right with them. I need to have tabs on page because there are tons of options in this calculator.
This is the jQuery function.
$(document).ready(function() {
// For tabs
var tabContents = $(".tab_content").hide(),
tabs = $("ul.nav-tabs li");
tabs.first().addClass("active").show();
tabContents.first().show();
tabs.click(function() {
var $this = $(this),
activeTab = $this.find('a').attr('href');
if (!$this.hasClass('active')) {
$this.addClass('active').siblings().removeClass('active');
tabContents.hide().filter(activeTab).fadeIn();
}
return false;
});
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#cost_calc_total_cost').html(messageHTML);
$('.addons-box').hide();
} else {
$('#cost_calc_total_cost').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
You can see this working on jsfiddle without tabs. I can select options from multiple sections and order box will update selected option's price and details dynamically.
But when I add JavaScript tabs, it stop working correctly. See here. Now if I select option from different sections, order box resets previous selection and shows new one only.
I think the problem is with calculator somewhere.
You are removing the active class from hidden elements. This means that when you move to the second tab you disregard what you've done in the first.
line 120 in your fiddle:
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
I haven't taken the code in depth enough to tell if you can just remove this.

Using jQuery with meteor giving errors

Omitting the keydown input : function(event) { and } gives me an error along the lines of
"While building the application:
client/client.js:33:11: Unexpected token ("
which is basically the starting. I'm wondering why I need the javascript function right at the start. To not get the error. This is an issue especially because I don't want the click function to run every time the key is pressed. In any case it would be great to either figure out how I can just use jQuery instead of javascript here or change the keydown input.
Template.create_poll.events = {
'keydown input' : function(event) {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
}
}
Template.create_poll.events expects an eventMap which is:
An event map is an object where the properties specify a set of events to handle, and the values are the handlers for those events. The property can be in one of several forms:
Hence, you need to pass in the 'keydown input' : function (event, templ) { ... } to make it a valid Javascript object.
In this case, you should follow #Cuberto's advice and implement the events using Meteor's event map:
Template.create_poll.events = {
'press input' : function(event) {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
},
'click #poll_create' : function (event) {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
}
}
However, if you want to use certain jQuery specific events, then you can attach them in the rendered function:
Template.create_poll.rendered = function () {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
};

Move items between two ListBoxes in ASP.Net using JQuery

I want to move items between two Listboxes in ASP.Net using JQuery/Javascript and below is my code which is working perfectly.
function AddItems() {
var totalItemsSelected = 0;
var CurrentItems = 0;
var MessageLabel = document.getElementById('<%=lblITProgrammingMessage.ClientID%>');
var selectedOptions = jQuery('#<%=ListITProgramming.ClientID %> option:selected');
if (selectedOptions.length == 0) {
MessageLabel.innerHTML = "Please select skill(s) to add.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
jQuery('select[name$=ListMyITProgramming] > option').each(function () { CurrentItems++; });
if (CurrentItems == 30) {
MessageLabel.innerHTML = "Maximum limit (30) is reached. You cannot add any more skills.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
totalItemsSelected = CurrentItems + selectedOptions.length;
if (totalItemsSelected > 30) {
MessageLabel.innerHTML = "You can only select " + (30 - CurrentItems) + " item(s) more.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
if (selectedOptions.length == 1) {
if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + selectedOptions.val() + "']").length > 0) {
}
else {
jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(selectedOptions).clone());
}
}
else if (selectedOptions.length > 1) { jQuery(selectedOptions).each(function () { if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + this.value + "']").length > 0) { } else { jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(this).clone()); } }); }
jQuery(selectedOptions).remove();
var hdn2 = "";
jQuery('select[name$=ListMyITProgramming] > option').each(function () { hdn2 += jQuery(this).attr('value') + ','; });
jQuery("#<%= listMyITProgrammingValues.ClientID %>").val(hdn2);
return false;
}
But this code is limited for only one set of ListBoxes as I have hard coded the ListBox names 'ListITProgramming' and 'ListMyITProgramming'.
Can anyone make this dynamic with two parameters in existing function?
Enclose the list control in an old-fashioned HTML tag with a known, hardcoded ID. Example:
<DIV id="List1Container">
<ASP:ListBox runat="server" id="list1"/>
</DIV>
In your Javascript, access the list control using the div's ID (List1Container) and jquery's ":first-child" selector. Ta da! You can now reference the list control without knowing its ID at all, so you don't have to do that messy code injection any more.
Bonus: Using this technique, you can now write fully static .js files, which means you can use minification and caching and greatly improve performance.

Previewing form using javascript in lightbox popup

please I need some help in previewing a form in popup. I have a form, quite big, so I added the option of preview to show as popup. The lightbox form popup works well, but the problem I now have is function passform() passing the inputs(textfield, select, checkbox, radio) into the popup page for preview on Click().
Below are my javascript and html codes. I left the css and some html out, because I think they're not necessary. I will appreciate your help. Thank you
The Javascript
function gradient(id, level)
{
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display="block";
return;
}
function fadein(id)
{
var level = 0;
while(level <= 1)
{
setTimeout( "gradient('" + id + "'," + level + ")", (level* 1000) + 10);
level += 0.01;
}
}
// Open the lightbox
function openbox(formtitle, fadin)
{
var box = document.getElementById('box');
document.getElementById('shadowing').style.display='block';
var btitle = document.getElementById('boxtitle');
btitle.innerHTML = formtitle;
if(fadin)
{
gradient("box", 0);
fadein("box");
}
else
{
box.style.display='block';
}
}
// Close the lightbox
function closebox()
{
document.getElementById('box').style.display='none';
document.getElementById('shadowing').style.display='none';
}
//pass form fields into variables
var divexugsotherugsexams1 = document.getElementById('divexugsotherugsexams1');
var exugsotherugsexams1 = document.form4.exugsotherugsexams1.value;
function passform()
{
divexugsotherugsexams1.innerHTML = document.form4.exugsotherugsexams1.value;
}
The HTML(with just one text field try):
<p><input name="submit4" type="submit" class="button2" id="submit4" value="Preview Note" onClick="openbox('Preview Note', 1)"/>
</p>
<div id="shadowing"></div>
<div id="box">
<span id="boxtitle"></span>
<div id="divexugsotherugsexams1"></div>
<script>document.write('<PARAM name="SRC" VALUE="'+exugsotherugsexams1+'">')</script>
Close
</div>

Categories