Adding/Removing rows from a form. Resetting entire form - javascript

These three functions all work on Chrome, but not IE or Firefox. The first functions adds a cloned row. The second function removes a cloned row. The third function resets the entire field. All three are well commented. Does anything obvious stick out to you? I am baffled.
Could it have something to do with the cloned rows using ID's and not classes?
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#CloneRow' + num).clone().attr({'id': 'CloneRow' + newNum}).addClass('addedRow').fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
/* This is where we manipulate the name/id values of the input inside the new, cloned element
Below are examples of what forms elements you can clone, but not the only ones.
There are 2 basic structures below: one for an H2, and one for form elements.
To make more, you can copy the one for form elements and simply update the classes for its label and input.
Keep in mind that the .val() method is what clears the element when it gets cloned. Radio and checkboxes need .val([]) instead of .val('').
*/
// Hour - select
newElem.find('.input_hr').attr('id', 'ID' + newNum + '_hour').attr('name', 'ID' + newNum + '_hour').val('0');
// Minute - select
newElem.find('.input_min').attr('id', 'ID' + newNum + '_min').attr('name', 'ID' + newNum + '_min').val('0');
// Activiy - text
newElem.find('.input_act').attr('id', 'ID' + newNum + '_act').attr('name', 'ID' + newNum + '_act').val('');
// Category - select
newElem.find('.input_cat').attr('id', 'ID' + newNum + '_cat').attr('name', 'ID' + newNum + '_cat').val('');
// Insert the new element after the last "duplicatable" input field
$('#CloneRow' + num).after(newElem);
$('#ID' + newNum + '_title').focus();
// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel').attr('disabled', false);
// Right now you can only add 13 sections, for a total of 15. Change '13' below to the max number of sections you want to allow.
if (newNum == 20)
$('#btnAdd').attr('disabled', true).prop('value', "That's all, folks!"); // value here updates the text in the 'add' button when the limit is reached
});
$('#btnDel').click(function () {
// Confirmation dialog box. Works on all desktop browsers and iPhone.
// if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
{
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#CloneRow' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "add section");});
}
return false; // Removes the last section you added
});
// Enable the "add" button
$('#btnAdd').attr('disabled', false);
// Disable the "remove" button
$('#btnDel').attr('disabled', true);
// Reset the entire form
$('#btnRes').click( function () {
{
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Do you really want to reset the form? All data will be lost."))
{
document.getElementById("BudgetFormEng").reset();
$('.addedRow').remove();
$('#output').empty();
};
return false;
};});
I am not receiving any errors from IE or Firefox.

The answer to this question is that I am an idiot. In my html I had <button><span id="btnRes/btnAdd/btnDel"></span></button>. The code was working but you had to click directly on the glyphicon span and not the white space of the button.

Related

Datepicker repeate on dynamic fields

I am using the clone script of tristandenyer.
$('#btnAdd_4').click(function () {
var num = $('.clonedInput_4').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#date' + num).clone().attr('id', 'date' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
// H2 - section
newElem.find('.label_date').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Date #' + newNum);
// date - text
newElem.find('.label_date').attr('for', 'ID' + newNum + '_date_number');
newElem.find('.input_date').attr('id', 'ID' + newNum + '_date_number').attr('name', 'ID' + newNum + '_date_number').val('');
// Insert the new element after the last "duplicatable" input field
$('#date' + num).after(newElem);
$('#ID' + newNum + '_title').focus();
// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel_4').attr('disabled', false);
// Right now you can only add 4 sections, for a total of 5. Change '5' below to the max number of sections you want to allow.
// This first if statement is for forms using input type="button" (see older demo). DELETE if using button element.
if (newNum == 5)
$('#btnAdd_4').attr('disabled', true).prop('value', "You've reached the limit"); // value here updates the text in the 'add' button when the limit is reached
// This second if statement is for forms using the new button tag (see Bootstrap demo). DELETE if using input type="button" element.
if (newNum == 5)
$('#btnAdd_4').attr('disabled', true).text("You've reached the limit"); // value here updates the text in the 'add' button when the limit is reached
});
$('#btnDel_4').click(function () {
// Confirmation dialog box. Works on all desktop browsers and idate.
if (confirm("Are you sure you wish to remove this date number? This cannot be undone."))
{
var num = $('.clonedInput_4').length;
// how many "duplicatable" input fields we currently have
$('#date' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel_4').attr('disabled', true);
// enable the "add" button. IMPORTANT: only for forms using input type="button" (see older demo). DELETE if using button element.
$('#btnAdd_4').attr('disabled', false).prop('value', "Add date");
// enable the "add" button. IMPORTANT: only for forms using the new button tag (see Bootstrap demo). DELETE if using input type="button" element.
$('#btnAdd_4').attr('disabled', false).text("Add date");});
}
return false; // Removes the last section you added
});
// Enable the "add" button
$('#btnAdd_4').attr('disabled', false);
// Disable the "remove" button
$('#btnDel_4').attr('disabled', true);
I can repeate any part with that but date picker no.
How we can repate the datepicker also with this plugin.
I have tried different method but my coding experience not soo big so i need your help.
Thanks in advance.
We have solved this issue by adding
newElem.find("input[type=text]").datepicker();
and for not having a problem for closing datepicker after selection we added autoclose: true.
And last form of the code is like this.
newElem.find("input[type=text]").datepicker({autoclose: true});

Create Unique Hidden Field IDS from Select Menu options

I have a modal that displays stock information for a specific item that has multiple locations within a warehouse. The user selects the locations and quantities from each menu and clicks confirm, the information from this modal needs to then be imported on a pick list which is printed out.
To do this I was planning to use arrays to transport the data to the pick list.
I have a hidden field for each row, containing the values of the Location and the Qty Picked from there.
Location 1 + Qty 1 = Hidden Field 1
Location 2 + Qty 2 = Hidden Field 2
I now want to be able to put those hidden fields into an array once a button is clicked.
Hidden Field 1 + Hidden Field 2 = Array.
I can create the hidden fields just fine, its when I go to make the final array that contains all the data, it only seems to want to add the newest hidden field to be created into it.
Dialog - Pick Quantity Button (Used to confirm the selections):
//PICK QUANTITY Button
'Pick Quantity': function() {
jQuery('.ui-dialog button:nth-child(1)').button('disable');
//Disables the current selection, so that it cannot be editted
$('#AddLocQtyPick'+Picker).prop ('disabled', true);
//Disables the current selection, so that it cannot be editted
$('#LocationPickerSelect'+ Picker).prop ('disabled', true);
//Adds Unique Number to the ID of the input fields
Picker++;
//For Loop that helps to total up the quanities being selected in each picker
total=0;
for (i = 0; i<Picker; i++) {
total= total + $('#AddLocQtyPick'+i).val() * 1.0;
}
//Variable decides max value of pick on appends using previous selection
QtyReqTot= QtyReq - total;
//"Pick Another location" button is enabled whilst Qty Req has not been met
if (total !== QtyReq){
jQuery('.ui-dialog button:nth-child(2)').button('enable');
}
//"Pick Quantity", "Pick Another Location" are disabled, whilst "Confirm" button is enabled when total reaches Qty Req
if (total == QtyReq){
jQuery('.ui-dialog button:nth-child(2)').button('disable');
jQuery('.ui-dialog button:nth-child(1)').button('disable');
jQuery('.ui-dialog button:nth-child(3)').button('enable');
}
//Pick Another Location button is disabled if no more locations to pick from
if (length == 1){
jQuery('.ui-dialog button:nth-child(2)').button('disable');
}
if (total !== QtyReq && length == 1){
jQuery('.ui-dialog button:nth-child(1)').button('disable');
$(":button:contains('Cancel')").focus();
}
//Create Hidden Field - Location
//for loop that creates the fields
for (i = 0; i<Picker; i++){
HiddenSelection = [$('#LocationPickerSelect'+i).val(),$('#AddLocQtyPick'+i).val()];
var appendHiddenSelection = '<input type="hidden" class="HiddenSelection'+ i +'" value='+HiddenSelection+'>';
$('#AddLocationPicker').append(appendHiddenSelection);
alert(appendHiddenSelection +'This is SelectionField'+i);
}
},
Confirm Button - Used to Generate the Final Array containing previous arrays:
'Confirm': function() {
//Reset the length loop
length = undefined;
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
//Checks "Multiple Location" icon for existence and adds Pick List button when all hidden.
$('img[id^=icon]:visible').length || $('#ProcessPickList').show();
//Change text colour back to blue to have visual confirmation that item is ready for picking
$('#Desc'+id).css('color', '#0000FF');
$('#QtyReq'+id).css('color', '#0000FF');
$('#QtyinStock'+id).css('color', '#0000FF');
//Create Total Array
TotalHiddenArray = [HiddenSelection]
alert (TotalHiddenArray);
$(this).dialog('close');
},
I think I need to be able to create unique IDS for the input fields and show how get them to all be added to the array.
You can try replacing
HiddenArray = [appendHiddenQty, appendHiddenLocation]
By
HiddenArray[HiddenArray.length] = [appendHiddenQty, appendHiddenLocation]
This way, instead of overwriting HiddenArray within the loop, you just add [appendHiddenQty, appendHiddenLocation] at the end of HiddenArray.
EDIT1:
Replace
HiddenSelection = [$('#LocationPickerSelect'+i).val(),$('#AddLocQtyPick'+i).val()];
by
HiddenSelection[HiddenSelection.length] = [$('#LocationPickerSelect'+i).val(),$('#AddLocQtyPick'+i).val()];
Or, you also can use push :
HiddenSelection.push([$('#LocationPickerSelect'+i).val(),$('#AddLocQtyPick'+i).val()]);
Please see this quickly made Fiddle
EDIT2:
Ok, so let's try to replace the whole loop by:
var HiddenSelection = new Array;
for (i = 0; i<Picker; i++){
HiddenSelection = [$('#LocationPickerSelect'+i).val(),$('#AddLocQtyPick'+i).val()];
var appendHiddenSelection = '<input type="hidden" class="HiddenSelection'+ i +'" value='+HiddenSelection+'>';
$('#AddLocationPicker').append(appendHiddenSelection);
alert(appendHiddenSelection +'This is SelectionField'+i);
TotalHiddenArray.push([HiddenSelection]);
}
You just have to remove this from your confirm function :
//Create Total Array
TotalHiddenArray = [HiddenSelection]
You also have to delcare TotalHiddenArray as new array outside any function (at the very top of your JS code for exemple, because I guess you are trying to access TotalHiddenArray from another function than the loop) like this :
var TotalHiddenArray= new Array;
Another Fiddle

Validation -- Only when checkbox is checked and Radio button checked

The DEMO
should be pretty explanatory.
There are rows with radio buttons and a check box at the end.
Help 1. What I would like is when ONLY the check box is checked, the values of the checked radio button and along with the value of the textarea and dropdown (if Missing radio button is clicked) to be populated in the text area which is at the bottom?
Help 2. Right now when the radio button is clicked, all the checked radio buttons value are showing. Where am I going wrong ?
To help you understand, from the text area, the data which is separated by ~ and | gets passed over to the next stage when the save all button is clicked. Initially when the page loads the radio buttons are pre-checked depending on the previous page but nothing needs to be populated in the bottom text area.
We use jquery 1.6.4
function updateSummary($this){
$this.closest('[id]').find('.r-title, .m-notes-wrapper, .up-arrow, .down-arrow').hide();
var totalRd = $('table').find('input:radio:checked').length;
// Array of clicked items
var clicked = [];
// Set number of selected items
$("#totalRd .rd-count").html(totalRd);
// Show the title and notes next to the radio button
$this.siblings('.r-title, .m-notes-wrapper, .up-arrow, .down-arrow').show();
// Find checked radio buttons that has been clicked
$('table').find("input[type=radio]:checked:enabled").each(function () {
// Find closest ancestor with an id
// See if we have a text box, if so use the text
var $text = $(this).parent().find('textarea.m-notes:visible');
var missingReason = $(this).parent().find('.reason').val();
var selectedId = $(this).closest('[id]').attr('id');
var value = selectedId + "~" + $(this).val();
if ($text.length)
{
value += "~" + missingReason +"~" + $text.val();
}
clicked.push(value);
}); //checked
// Display the selected ids
$("#inputhere").val(clicked.join('|'));
}
// Radio selection changes selected options
$("input:radio").click(function () {
updateSummary($(this));
});
$('textarea.m-notes').bind('keyup', function () {
updateSummary($(this).siblings(':radio'));
});
$('select.reason').change (function () {
updateSummary($(this).siblings(':radio'));
});
$("input:checkbox").change(function(){
updateSummary($(this));
});
Thanks for your help.
You could add a condition when updating your textarea :
if($('table').find("input[type=checkbox][name='" + $(this).attr('name') + "']").is(':checked')) {
var $text = $(this).parent().find('textarea.m-notes:visible');
var missingReason = $(this).parent().find('.reason').val();
var selectedId = $(this).closest('[id]').attr('id');
var value = selectedId + "~" + $(this).val();
if ($text.length)
{
value += "~" + missingReason +"~" + $text.val();
}
clicked.push(value);
}

Clone jquery mobile input field with data-clear-btn="true"

Using jquery and jquery mobile I try to make a dynamic form. Input fields are created or removed so that always one empty input field is left.
This is my jquery code to achieve this (try it here:
http://jsfiddle.net/SR864/17/):
$(document).ready(function() {
var total = 1;
// add new field
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
});
$("#bar").on("input", ".input", function() {
// remove empty field
if ($(this).val() == "") {
$(this).closest("p").remove();
}
});
});
I also would like to have "delete-buttons" inside of the input fields to remove the text from the input fields. jquery mobile provides data-clear-btn="true" for that. However, somehow the behavior of data-clear-btn="true" only works for the first input field - the new (cloned) ones don't get the clear button.
Question
How can I have the clear-buttons for the cloned input fields?
Bonus question
What is necessary to have input fields deleted when they are empty after the clear button is pressed?
jQM wraps input fields in a div ui-input-text. You need to clone input itself - not the wrapping div - change its' id, name, val()...etc. Then add it to form and enhance it using .textinput() function.
Moreover, you should wrap code in pagecreate event.
$(document).on("pagecreate", function () {
var counter = 0;
$("#bar").on("input", function (e) {
if ($(e.target).val().length === 1) { /* after 2 characters add a new input */
counter++;
var id = "input-" + counter;
var input = $(e.target).clone().prop({
id: id,
name: id
}).val("");
$(e.target).closest(".ui-input-text").after(input);
$("#" + id).textinput();
}
});
});
Demo
I had a check at the problem. By default the cross button (which is an tag) has a class 'ui-input-clear-hidden' which keeps it hidden till you type. Though you are cloning the element after you start typing, the duplicate element also has this class which keeps it hidden (may be cloning is done before the class 'ui-input-clear-hidden' is removed). So I suggest removing the class 'ui-input-clear-hidden' from your cloned object explicitely as shown below.
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
/* New line Added for Fix*/
newFields.find('a').removeClass('ui-input-clear-hidden');
});

problem when clone - jquery

i am using this plugin
Now i am doing a way to clone the select dropdown. A button to add cloned divs.
So, an user have a initial dropdown, but he can add more. The div is cloned.
The main problem is that when i clone the div, the dropdown is associated to initial dropdown and no to the new, that is cloned. The result is: all dropdowns of the new cloned divs have the event to open the select associated to the first.
Script to call the plug in
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".mydds").msDropDown();
})
</script>
script to clone
<script type="text/javascript">
$(document).ready(function() {
$('#adicionar').live('click', function(){
var num = $('.linguas').length;
var newNum = new Number(num + 1);
var newElem = $('#copiar' + num).clone(true).prop('id', 'copiar' + newNum);
newElem.children(':text').prop('name', "myformdata[languages" + newNum + "]").prop('languages', 'languages' + newNum).val('');
$('#copiar' + num).after(newElem);
$('#apagar').prop('disabled', '');
});
</script>
Any idea to solve the problem?
Basically i think the event associated to dropdown is not copied...
thanks
Assuming you have only one dropdown per cloned element, you can use
$('#adicionar').live('click', function(){
var num = $('.linguas').length;
var newNum = new Number(num + 1);
var newElem = $('#copiar' + num).clone(true, true).attr('id', 'copiar' + newNum);
var id = newElem.find('select').msDropDown().data('dd').get('id');
newElem.find('[id]').each(function(){
$(this).attr('id',this.id.replace(id,'customid_' + newNum,'g') );
});
$('#copiar' + num).after(newElem);
newElem.find('select').msDropDown();
});
The problem is that the plugin gives an id to the initial select element, and uses that id to create other elements and also to refer to its related select.
You will need to modify all those ids as well as the reference.. (the code above does just that..)
demo http://jsfiddle.net/gaby/CXBZR/3/
In your script you are calling .clone(true). This true parameter is cloning the events and data.
From the API
.clone( [ withDataAndEvents ] )
withDataAndEvents: A Boolean indicating
whether event handlers should be
copied along with the elements. As of
jQuery 1.4, element data will be
copied as well.
If you remove this, or set it to false, this will stop the events from being cloned onto your new divs.

Categories