Create Unique Hidden Field IDS from Select Menu options - javascript

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

Related

jQuery Chose plugin how to remove selected item from drop down

I im using jquery choose plugin that is using two input boxes when page loads...and a need like in this example when i select number 1 in first box that this number is removed from second input box....this works fine...but problem is when i add dynamically input box i can't get item number 1 removed from added dynamic input box.
So question is: how can i remove selected values from input box when selecting other input boxes that is added dynamically and selected items in each select box is not visible in all selected box that exists and is added dynamically?
Here is jsfiddle:
[http://jsfiddle.net/dq97z/640/][1]
And here is picture what i need:
Maybe this will help you out
http://jsfiddle.net/s9r73qjm/
//an array to save selections
var selectedVals = [];
//push to the array when we have selected
selectedVals.push(selectedValue);
//check on the values when building the drop down
$( "#btn_newrow" ).click(function() {
var newList = document.createElement("select");
newList.dataset.placeholder = "Number row 3";
newList.style.width = "350px";
var newListData = new Option("placeholder", "placeholder");
for (var i = 0; i < 6; i++){
if (selectedVals.indexOf(i.toString()) == -1){
//then it hasn't been selected
newListData = new Option(i.toString(), i.toString());
newList.appendChild(newListData);
}
$( ".wrapper" ).append(newList);
}
});

Removing options from a dependent dropdown based on dropdown selection

Could someone please help me handle this issue in jQuery
I have a requirement where I have two dropdowns:
The no of floors of the flat (numberOfFloors)
The flat where the user stays (whichFloorYouStay)
I need to remove all the invalid options from the second dropdown. How do I achieve this?
For example:
If a user select the numberOfFloors option as 3, then I should remove options 4 and 5 from whichFloorYouStay dropdown and just load 1,2,3 as whichFloorYouStay options.
Similarly, if a user select the numberOfFloors option as 1, then I should remove options 2,3,4,5 from whichFloorYouStay dropdown and just load 1 as whichFloorYouStay option.
Please find my JSBin link:
http://jsbin.com/sibufive/1/edit?html,js,output
Try this:
$(document).ready(function () {
//NEW CODE:
var floorsvals = new Array();
var lastvalue = Number.MAX_VALUE; //Useful for checking whether we need to append or remove elements - Initialize this with an arbitrarily large number
//Fill possible floor vals with value of <option>'s
$("#numberOfFloors option").each(function () {
floorsvals.push($(this).val());
});
//NOTE: If you already know the values of the numberOfFloors array, you can just add those values straight into the "floorsvals" array
//The above loop is just handy if you are dynamically generating a <select> list and don't already know the values
$("#numberOfFloors").change(function () {
alert($("#numberOfFloors").val());
var value = $("#numberOfFloors").val();
//NEW CODE:
//If we need to append...
if (value > lastvalue) { //This value is larger than the last value we just had
for (i = 0; i < floorsvals.length; i++) {
if (floorsvals[i] <= value && $('#whichFloorYouStay option[value=' + floorsvals[i] + ']').length === 0) { //Floor value is less than the selected maxvalue and an option with this floor value doesn't already exist...
$('<option value="' + floorsvals[i] + '">' + floorsvals[i] + '</option>').appendTo("#whichFloorYouStay"); //...So add that floor value
}
}
} else { //Otherwise, we need to remove
//OLD CODE:
$('#whichFloorYouStay option').each(function () { //Go through each option
if ($(this).val() > value) { //If this option's value is greater than the numberOfFloors value, remove it
$(this).remove();
}
});
}
//NEW CODE:
lastvalue = value; //Update last value chosen with this value
});
});
Here's a demo: http://jsbin.com/sibufive/40/edit
var value = $("#numberOfFloors").val();
should become
var value = $("#numberOfFloors").val();
value-=1
I would also suggest adding a value 0 to the first set of options one so you never have a user begin at 1 and try to move to the second menu

Error in IE when looping

Lets clarify my question,
I want to make an element which the element contains 5 fields so I dont want the user should be able to put in a new element if the old one is null, so I made the alert when looping through the old element and see if there is some strings, if not then dont put a new element and make an alert please fill out all fields
Here again my code
function addEvent() {
var ni = document.getElementById('discount'); // Takes the a div named discount
var discountForm = document.getElementById('discountForm'); // Takes the a form named discountForm
var numi = document.getElementById('theValue'); // Takes the a hidden input field named theValue
var num = (document.getElementById("theValue").value -1)+ 2; // Start counting to set the new divs form numbers
numi.value = num;
var divIdName = "my"+num+"Div"; // the new divs will be named
var allDivTags = discountForm.getElementsByTagName('div'); // take all div tags
var numOfDivs = (allDivTags.length -1); // take the number of the old div
var oldDivIdName = document.getElementById(allDivTags[numOfDivs].id); // old div id
var newdiv = document.createElement('div'); //the new div
newdiv.setAttribute("id",divIdName);
newdiv.innerHTML = "Company <select name=\"company[]\"><option value=\"\"></option><option value=\"ZI\">Avis</option><option value=\"ET\">Enterprise</option><option value=\"ZE\">Hertz</option><option value=\"ZD\">Budget</option><option value=\"ZR\">National</option><option value=\"AL\">Alamo</option></select> Discount Type <select name=\"type[]\"><option value=\"CD\">Discount Number</option><option value=\"PC\">Coupon Number</option></select> Code <input name=\"code[]\" type=\"text\"> Title <input name=\"title[]\" type=\"text\"> Remove"; // creating the fileds in the new div
ni.appendChild(newdiv);
for(i=0; i<discountForm.elements.length;i++){ // loop through the divs
if(numOfDivs != i-1){ // if tho old div exist and if the old div fields are empty
if(oldDivIdName.children[i].value.length == 0){
removeElement(divIdName); // then dont put the new one
alert('Please enter all fields');
}
}
}
}
But my problem is that in IE comes out an error children[...].value.length is null or not an object so I trying to figure how to fix it,
I hope its more clearly for you now.
It's very hard to tell from the information you've given us. But my first guess is the following:
for(i=0; i<discountForm.elements.length;i++){
if(numOfDivs != i-1){
if(oldDivIdName.children[i].value.length == 0){
removeElement(divIdName);
alert('Please enter all fields');
}
}
}
Above you're doing:
oldDivIdName.children[i]
But i is defined as the number of elements in the form from what I can see... not the number of children of the oldDivIdName. If there are more elements in the form than there are in oldDivIdName then the value of oldDivIdName.children[i] will be null. And "value" is not defined on null.
It's very hard to tell from the information you've given us. But my first guess is the following:
When you first call this method, allDivTags.length whether is null or negative, and results
not got element:
var oldDivIdName = document.getElementById(allDivTags[numOfDivs].id);

Limit the number of children in a form using Javascript

I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}

Setting dropdown to first value

I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it:
Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue());
Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have:
var displayedValue = Global.getComponent("ddlVehicleType").getRawValue();
if (IsNumeric(displayedValue)) {
}
Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page:
var newId = 0;
var firstId = 0;
var typeStore = Global.getComponent("ddlVehicleType").getStore();
firstId = typeStore.getAt(0).get('LookupID');
typeStore.each(function(rec) {
if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue())
{
newId = Global.getComponent("DefaultVehicleTypeId").getValue();
}
});
if (newId != 0) {
Global.getComponent("ddlVehicleType").setValue(newId);
} else {
Global.getComponent("ddlVehicleType").setValue(firstId);
}

Categories