Limit the number of children in a form using Javascript - 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;
}

Related

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

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

Disable textbox based on input entered

I have 7 input textboxes.Based on the input enter i need to disable them accordingly.For eg if i enter input as 4 out the first four text boxes should be diabled accordingly(input is restricted to less than 7),and this is to be done using Jquery
This is a simple example on how to do that:
$("input").on("change", function()
{
$("input:lt(" + $(this).data("index") + ")").prop("disabled", "disabled");
});
Fiddle.
Using data attributes I set the index of each element(you can use index() in some cases, but it is more complex). So, when any element is changed I get all inputs with index less than the changed one (input:lt(index)) and disable it setting its property disabled.
I hope it is clear.
for (i = 0; i < contract; i++)
{
$('#tblTest').find('tbody').find('tr').find('.Year')[i].disabled = false;
var samtes = $('#tblTest').find('tbody').find('tr').find('.Year')[0].disabled = false;
}

How do we implement a cancel in plain Javascript?

I have a page and I display data in a table.
In each table I have a column with a checkbox which if is checked the user can modify the specific row via Javascript.
This is done as its td encapsulates either an input or a select and I make these editable for the user.
The user modifies the row and presses save and the changes are saved. So far ok.
My problem is how do I implement a cancel?
The user could choose many row i.e. check boxes and modify them but the user could also press cancel. On cancel the original values should be displayed (and the rows become non-editable again).
But how is a cancel operation implemented in Javascript? Do we store data in some global datastructures? Which would be this in Javascript?
Ok, after the addition of informations you provided I suggest you setup the following mecanism:
function getDatas() {
var oXhr;
//get datas from database:
oXhr = new XMLHttpRequest();
oXhr.onreadystatechange = function() {
if (oXhr.readyState == 4 && (oXhr.status == 200)) {
g_oData = (new DOMParser()).parseFromString(oXhr.responseText, "text/xml");
}
}
oXhr.open("POST", "yourphpscriptthatreturnsthexmldatas.php", true);
oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
oXhr.send();
}
function populateGrid() {
//use g_oData to populate your grid, but at first totally clean the body
var mygrid = document.getElementById("mygridid");
//mygrid.innerHtml = "<table><tr><td>...</td></tr></table>";
//use the xml library to parse g_oData and fill up the table:
var xmlRows = g_oData.getElementsByTagName("TAG");
var xmlRow;
iLen = xmlRows.length;
for (var i=0;i<iLen;i++) {
xmlRow = xmlRows[i];
//use xmlRow->textContent to build each cell of your table
}
}
function revertChange() {
//on cancel, revert the changes by populating the grid.
//it will use the global xml/json object loaded directly from database, to refill everything.
populateGrid();
}
I did it myself many times to refresh some datas in a page. That's basically what you're doing except that you're not requesting anything to the database, you just refill the fields.
You can just access the original value attribute of the input to get the defaultValue. Sample implementation:
$("table").on("dblclick", "td", function(e) {
var val = $(this).html();
$(this).empty().append($("<form/>").append(
$("<input/>", {type:"text"}).attr("value", val),
// ^^^^
// set the *attribute*, as if it was present in the parsed HTML
$("<button/>", {type:"reset"}).text("Reset"),
$("<button/>", {type:"button", class:"cancel"}).text("Cancel"),
$("<button/>", {type:"submit"}).text("Submit")
));
}).on("submit", "form", function(e) {
var val = $(this).find("input:text").val();
// ^^^^^
// which is equivalent to .prop("value")
/* then do something with val, e.g. send it to server via ajax */
$(this).parent().html(val);
e.preventDefault();
}).on("click", "button.cancel", function(e) {
var $form = $(this).parent(),
$input = $form.find("input:text"),
oldval = $input.attr("value");
// ^^^^^^^^^^^^^
// or .prop("defaultValue"), but not .val()!
if (oldval == $input.val() || confirm("Do you really want to discard your changes?"))
$(this).parent().html(oldval);
e.preventDefault();
});
(Demo at jsfiddle.net)
A maybe more simple solution might be to use the dblclick-handler that creates the form as a closure and just store the original html in a local variable there.
Here is a pretty simple way:
Don't replace the cell content with the form element. Keep the value (the text) in a span element and hide it when you show the form element. Then you don't have to do anything on cancel. Just show the span again and hide or remove the form element. Only update the span when the user wants to save the value.
Here is an example. The showing and hiding is all done with CSS.
<tr>
<td>
<span>value</span>
<input type='text' value='' />
</td>
<td>
<button class="save">Save</button>
<button class="revert">Revert</button>
</td>
</tr>
JS:
var rows = document.querySelectorAll('table tr');
for(var i = 0, l = rows.length; i < l; i++) {
rows[i].addEventListener('click', function(event) {
// all value display elements in the row
var spans = this.querySelectorAll('span');
// all form elements in the row
var inputs = this.querySelectorAll('input');
// handle click on save button
if (event.target.className === 'save') {
[].forEach.call(inputs, function(input, i) {
spans[i].innerHTML = input.value;
});
this.className = '';
}
// handle click on revert button
else if (event.target.className === 'revert') {
// not much to do
this.className = '';
}
else {
// update form element values
[].forEach.call(inputs, function(input, i) {
input.value = spans[i].innerHTML;
});
this.className = 'edit';
}
});
}
DEMO
You can use the HTML5 data- attributes to implement a revert function. This way, each <input> would hold it's original value in case a revert button would be used.
Here's how it'd look:
<table>
<tr>
<td><input type='text' value='change me' data-original='change me' /></td>
<td><input type='text' value='change me2' data-original='change me2' /></td>
<td><input type='button' value='revert' onclick='revert(this)'/></td>
</tr>
<table>
And the code that reverts:
function revert(btn) {
var parentTr = btn.parentNode.parentNode;
var inputs = parentTr.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text') {
inputs[i].value = inputs[i].getAttribute('data-original');
}
}
}
The data-original attribute could be generated:
By the server-side app who serves the page (see (1) demo fiddle here); or
by a JavaScript function that is executed as soon as the DOM is ready (see (2) demo fiddle for this here).
As a side solution, you could store the original values in a map object. Here's the (3) demo for this (notice I added the id for each input, so it can be used as key to the map).
Keep in mind, though, neither solutions (2) or (3) require changing in server side code (the 3 assuming your inputs have ids). And (2) feels clearer.
About the defaultValue attribute: The defaultValue attribute can be a solution only if the value to be reverted never changes and if the fields involved are text inputs.
Firstly, changing the "default value" is rather awkward and may break something else aling the page (one would expect the browsers make the defaultValue attribute read-only, but that does not seem to be the case). Secondly, you would be limited to inputs of the text type.
Still, if none of that is a problem, the code above can be quickly adapted to use them instead of data- attributes.

How do I pass form elements to a javascript validation function?

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?
This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.
You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}

Categories