How to find duplicate id's in a form? - html

I've created a form with about 800 fields in it. Unknowingly I've given same id for few fields in the form. How to trace them?

The http://validator.w3.org/ will be the handy solution. But using jquery you can do something like this:
//See your console for duplicate ids
$('[id]').each(function(){
var id = $('[id="'+this.id+'"]');
if(id.length>1 && id[0]==this) {
console.log('Duplicate id '+this.id);
alert('duplicate found');
}
});
Hope this helps.

This might help you
Source: Finding duplicate ID’s on an HTML page
Finding duplicate ID’s on an HTML page
Written by Eneko Alonso on May 6, 2011
Looks like sometimes we forgot element ID’s
are meant to be unique on a HTML page. Here is a little bit of code I
just wrote to find duplicate ID’s on a page (run the code on your
browser’s javascript console):
var idList = {};
var nodes = document.getElementsByClassName('');
for (var i in nodes) {
if (!isNaN(i) && nodes[i].id) {
idList[nodes[i].id] = idList[nodes[i].id]? idList[nodes[i].id]+1:1;
}
}
for (var id in idList) {
if (idList[id] > 1) console.log("Duplicate id: #" + id);
}

I've created an example for you to have a look at, it finds all of the duplicate IDs within a form/element on a page and prints the duplicates ID names to the console.
The array contains method was taken from this post.
<html>
<body>
<form id="frm">
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />
<input type="text" id="a" />
<input type="text" id="h" />
<input type="text" id="i" />
<input type="text" id="j" />
<input type="text" id="d" />
<input type="text" id="l" />
</form>
</body>
<script type="text/javascript">
Array.prototype.contains = function(obj) { //Add a 'contains' method to arrays
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
frm = document.getElementById('frm'); //Get the form
els = frm.getElementsByTagName('input'); //Get all inputs within the form
ids = new Array(els.length); //Create an array to hold the IDs
for(e = 0; e < els.length; e++) { //Loop through all of the elements
if(ids.contains(els[e].id)) //If teh array already contains the ID we are on
console.log('Duplicate: '+els[e].id); //Print 'Duplicate: {ID}' to the console
ids.push(els[e].id); //Add the ID to the array
}
</script>
</html>
The above code will output the following:
Duplicate: a
Duplicate: d

One-ish liner using just array methods:
[].map.call(document.querySelectorAll("[id]"),
function (e) {
return e.id;
}).filter(function(e,i,a) {
return ((a.lastIndexOf(e) !== i) && !console.log(e));
})
Logs every duplicate and returns an array containing the ids if any were found.

There is a Chrome extension named Dup-ID which if you install, you just need to press the button to check duplicated ids.
Link of install: https://chrome.google.com/webstore/detail/dup-id-scans-html-for-dup/nggpgolddgjmkjioagggmnmddbgedice

By defualt Notepad++ has syntax highlighting that if you double click one word to select it, it will highlight all other occurences of the same word. You are going to have to do some (probably a lot) of manual work renaming things, I mean since fields can't come up with their own unique name.

Related

Stop chrome auto filling / suggesting form fields by id

Ok so...like many other posts this is driving me nuts. Chrome is continually offering autocomplete suggestions for fields that I would rather it not be on. It, along with the soft keyboard take up the whole page which blocks the view for the user / the form is not intended to fill our the users data but rather a new address that would be previously unknown.
So far I've got these both on
<form autocomplete="off">
and
<input autocomplete="randomstringxxx">
Their effect is noticed and chrome is no longer filling the whole form - but it STILL wants to suggest single field suggestions for each element in my form.
I've finally realised that its now picking up the id/name fields from my form elements.
i.e the below will give me a list of names I have used before.
<input id="contact_name" name="contact_name">
Can anyone suggest a way to stop this without renaming the elements? They are tied to fields in my database and ideally I would not have to manually rename and match up these together.
example -
https://jsfiddle.net/drsx4w1e/
with random strings as autocomplete element attribute - STILL AUTOCOMPLETING
https://jsfiddle.net/drsx4w1e/1/
with "off" as autocomplete attribute. - STILL AUTOCOMPLETING
https://jsfiddle.net/6bgoj23d/1/
example no autocomplete when labels / ids/ name attr are removed - NOT AUTOCOMPLETING
example
I know this isn't ideal because it changes the name of the inputs but it only does it temporarily. Changing the name attribute is the only way I found that completely removes the autocomplete.
This solution is all in JS and HTML but I think it would be better if it was implemented with a server side language such as PHP or Java.
I found autocomplete="none" works best for chrome but it doesn't fully turn off auto complete.
How it works
So, on page load this solution adds a string of random characters to each input name.
eg. 'delivery_contact_name' becomes 'delivery_contact_nameI5NTE'
When the form is submitted it calls a function (submission()) which removes the random character that were added. So the submitted form data will have the original names.
See solution below:
<html>
<body>
<form autocomplete="none" id="account_form" method="post" action="" onsubmit="return submission();">
<div class="my-2">
<label for="delivery_contact_name" class="">*</label>
<input autocomplete="none" class="form-control" id="delivery_contact_name" maxlength="200" minlength="2" name="delivery_contact_name" required="" type="text" value="">
</div>
<div class="my-2">
<label for="delivery_telephone" class="">Telephone*</label>
<input autocomplete="none" class="form-control" id="delivery_telephone" maxlength="200" minlength="8" name="delivery_telephone" required="" type="tel" value="">
</div>
<div class="my-2">
<label for="delivery_address_1" class="">Delivery Address*</label>
<input autocomplete="none" class="form-control" id="delivery_address_1" maxlength="50" minlength="2" name="delivery_address_1" required="" type="text" value="">
</div>
<div class="my-2">
<label for="delivery_address_2" class="">Delivery Address*</label>
<input autocomplete="none" class="form-control" id="delivery_address_2" maxlength="50" minlength="2" name="delivery_address_2" required="" type="text" value="">
</div>
<div class="my-2">
<label for="delivery_address_3" class="">Delivery Address</label>
<input autocomplete="none" class="form-control" id="delivery_address_3" name="delivery_address_3" type="text" value="">
</div>
<div class="my-2">
<label for="delivery_address_4" class="">Delivery Address</label>
<input autocomplete="none" class="form-control" id="delivery_address_4" name="delivery_address_4" type="text" value="">
</div>
<div class="my-2">
<label for="delivery_address_postcode" class="">Delivery Postcode*</label>
<input autocomplete="none" class="form-control" id="delivery_address_postcode" maxlength="10" minlength="6" name="delivery_address_postcode" required="" type="text" value="">
</div>
<input type="submit" name="submit" value="Send">
</form>
</body>
<script>
//generate a random string to append to the names
const autocompleteString = btoa(Math.random().toString()).substr(10, 5);
//get all the inputs in the form
const inputs = document.querySelectorAll("input");
//make sure script calls function after page load
document.addEventListener("DOMContentLoaded", function(){
changeInputNames();
});
//add random characters to input names
function changeInputNames(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("name", inputs[i].getAttribute("name")+autocompleteString);
}
}
//remove the random characters from input names
function changeInputNamesBack(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("name", inputs[i].getAttribute("name").replace(autocompleteString, ''));
}
}
function submission(){
let valid = true;
//do any additional form validation here
if(valid){
changeInputNamesBack();
}
return valid;
}
</script>
</html>
Thanks to #rydog for his help. I've changed it into a function that I've put into a my js file as I didn't want to manually add to each page / fire on every page - I have also added the submit event handler with js rather than adding to the on submit of the form.
GREAT SOLUTION by Rydog
function stop_autofill() {
//generate a random string to append to the names
this.autocompleteString = btoa(Math.random().toString()).substr(10, 5);
this.add_submit_handlers = () => {
document.querySelectorAll("form").forEach(value => {
value.addEventListener("submit", (e) => {
this.form_submit_override(e)
})
})
}
//add random characters to input names
this.changeInputNames = () => {
for (var i = 0; i < this.input_elements_arr.length; i++) {
this.input_elements_arr[i].setAttribute("name", this.input_elements_arr[i].getAttribute("name") + this.autocompleteString);
}
}
//remove the random characters from input names
this.changeInputNamesBack = () => {
for (var i = 0; i < this.input_elements_arr.length; i++) {
this.input_elements_arr[i].setAttribute("name", this.input_elements_arr[i].getAttribute("name").replace(this.autocompleteString, ''));
}
}
this.form_submit_override = (e) => {
e.preventDefault()
this.changeInputNamesBack()
e.currentTarget.submit()
return true
}
this.setup_form = () => {
//get all the inputs in the form
this.input_elements_arr = document.querySelectorAll("input");
this.changeInputNames();
this.add_submit_handlers();
}
//make sure script calls function after page load
this.init = () => {
if (document.readyState === "complete") {
this.setup_form()
} else {
let setup_form = this.setup_form
document.addEventListener("DOMContentLoaded", function (e) {
setup_form()
})
}
}
}
on the page that needs it
<script>
af = new stop_autofill()
af.init()
</script>

Using javascript to create a for loop which loops over text fields, and concatenates the input, and has an add input button

This program has 6 text fields and when a user inputs into the text fields, the text result box will concatenate the input text. I am struggling to get a button to work which will add a 7th text field and then also add the user input together. I have tried to append it but not sure where I am going wrong.
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="button" value="Get"><br>
<input type="button" name="button" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let x = document.querySelectorAll('.textFields .text');
let button = document.querySelector('.textFields input[type="button"]');
let result = document.querySelector('#textResult');
button.onclick = function() {
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
button.onclick = function() {
var textField = document.createElement("INPUT")
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("textInput")
container.appendChild(textField)
}
</script>
</body>
</html>
When you run this in a browser, the following error is reported in the console when you click the Get button:
Uncaught ReferenceError: id is not defined
at HTMLInputElement.button.onclick (test.html:53)
Ignore the error for now, you can see that the error in actually in the second function, but for Get you were probably expecting the first funtion. To fix this issue, do not assign the second function, at least not to the button you have selected.
Notice how you have named both buttons the same name, this will make them hard to target, but also you are not using that name in the querySelector. So lets change that first, give each button a unique name and use it to select each button:
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
...
getButton.onclick = ...
...
addButton.onclick = ...
Now, when you click on the Get button there is no error, and it appears to function as you have described, clicking Add still raises the original error.
You have used a variable called id but you have not yet declared what that variable is yet. I would assume you probably want to make it 'textX' where x is the next number.
So add the following lines inside the button click function to declare the Id:
You need to put this logic inside the function because you need it to be re-evaluated each time the button is clicked. Other valid solutions would include incrementing the value instead or re-querying for x, but this will work.
let x = document.querySelectorAll('.textFields .text');
let id = 'text' + (x.length + 1);
Save and Run, you will see the next issue in the console:
Uncaught ReferenceError: container is not defined
at HTMLInputElement.addButton.onclick
As with id, you have not defined the variable container, here I will again assume you meant to reference the .textFields div, so following your querySelector style, we can create a variable called container:
let container = document.querySelector('.textFields');
That will start appending your text boxes to the page, but they are still not being picked up by the Get button.
Another assumption here, but you have assigned a class .textResult to the new texboxes. If instead you assigned the class .text to them, then you would almost pick them up in the selector
textField.classList.add("text");
The reason that they aren't picked up is back to where the value of x is evaluated that the Get button is using. Because it is evaluated the first time in the main script, but never re-evaluated when the button is clicked the new text boxes are not included in the array stored in x.
As with the advice above for requerying x to get the updated count, Simply fix this by moving the line to initialise x into the first function.
Overall, your page with the embedded script could not look something like this:
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
let result = document.querySelector('#textResult');
let container = document.querySelector('.textFields');
getButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
addButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
var textField = document.createElement("INPUT")
let id = 'text' + (x.length + 1);
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("text")
container.appendChild(textField)
}
</script>
</body>
</html>
Have a look at some of the guidance in this post for further simple examples: How do I add textboxes dynamically in Javascript?

Google sheets sidebar form - set default values

I am trying to make a spreadsheet sidebar that allows a user to input data to create records, as well as edit them. So far I understand how to create the sidebar and display it. I've got a working form that can submit values.
What I am struggling with is how to pre-populate the forms. Form instance some records are associated with others, and I'd like to have a hidden field to store and eventually submit the associated id. Eventually users should also be able to edit records and I'd like to use the same form and just populate the fields and reuse the same submission flow.
I've tried a few different things found on here and other places, but nothing seems to work.
Here is the HTML for the sidebar template
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<!-- The CSS package above applies Google styling to buttons and other elements. -->
<style>
</style>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
$('#accountId').val(<? data.accountId ?>);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(alertSuccess).createContact(formObject);
}
function alertSuccess(message) {
var div = document.getElementById('alert');
div.innerHTML = "<p>" + message + "</p>";
google.script.host.close();
}
</script>
</head>
<body>
<p>Enter Contact Info</p>
<form id="contact" onsubmit="handleFormSubmit(this)">
Account Id: <br>
<input type="number" name="accountId" value="0" id="accountId" /><br>
Name:<br>
<input type="text" name="name"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Email:<br>
<input type="email" name="email"/><br>
Contact Type:<br>
<input type="radio" name="type" value="emergency" checked> Emergency<br>
<input type="radio" name="type" value="guardian" checked> Guardian<br>
<input type="radio" name="type" value="other" checked> Other<br>
<input type="submit" value="Submit" />
</form>
<div id="alert"></div>
</body>
</html>
And the accompanying .gs file:
var AlternativeContact = ObjectModel("AlternativeContacts");
function newContact() {
var htmlOutput = HtmlService.createTemplateFromFile("new_contact");
var id = ACCOUNT_MANAGER.getRange("M4").getValue();
htmlOutput.data = {accountId: id};
UI.showSidebar(htmlOutput.evaluate());
}
function createContact(contactJSON) {
var newContact = new AlternativeContact(contactJSON);
newContact.save();
return "Success!";
}
The first line that uses ObjectModel is creating and ORM around the data sheet.
Thanks for the help!
Couple changes and it seems to be working in a basic way.
First, in the scriptlet, i needed to us the printing tag. so use in stead of . This was causing the value to not be used in the rendered template.
Second, I changed my jQuery to:
$(document).ready(function () {
$("input#accountId").val(<?= data.accountId ?>);
});
If anyone is able to answer, I'd be curious why using the $(document).ready is needed. Doesn't everything in the get run? is it an order of operation thing?

Submit form using dynamicallly added fields with the same name in ASP.NET

I have a ASP.net Web page using VB as the language, I have created a form where it asks for 3 different input fields as follows, but the user has the option to add these three fields again for multiple form inputs to make their lives easier and this task faster.
<label>Test Number: <input type="text" id="test_number.1" name="test_number.1" value=""/>
</label>
<label>
Score: <input type="text" name="score.1" id="score.1" placeholder="Required" value="" />
</label>
<label>Comments:<input type="text" name="comments.1" id="comments.1" value="," placeholder="Comments Necessary for future reference" size="70" />
Looking at the submission of the data via firebug this is what it's posting to the serve if you submit only one set of fields.
test_number.1=12555&score.1=75&comments=testing
Looking at the submission of the data via firebug this is what it's posting to the serve if you submit multiple set of fields.
test_number.1=12555&score.1=75&comments=testing&test_number.1=12555&score.1=75&comments=testing&test_number.1=12555&score.1=75&comments=testing
Now I need to insert these values into a database, I know how to do this via PHP utilizing [] and then dealing with it on the backend. But I'm still learning asp.net and seem to be having some major issues on how to get this to work. If anyone can help that would be great.
Solution can be:
1st set of controls:
<input type="text" name="testnumber" />
<input type="text" name="testscore" />
<input type="text" name="testcomments" />
add next set
<input type="text" name="testnumber" />
<input type="text" name="testscore" />
<input type="text" name="testcomments" />
and so one.
On server side:
var testnumbers = Request["testnumbers"];// comma seperated values
var testscores = Request["testnumbers"];// comma seperated values
var testcomments = Request["testcomments"]; // comma seperted values.
split all values by comma. you will get array of values for each
string[] testnoList = testnumbers.split(',');
string[] testscoresList = testscores .split(',');
string[] testcommentsList = testcomments .split(',');
for(int i=0; i<testnoList.Lenght; i++)
{
var testno = testnoList[i];
var score = testscoresList[i];
var comments = testcommentsList[i];
// do whatever you want here
}

Is there a way to capture multiple checkboxs and select box items?

a I have a very large form with a lot of ckeckbox and a select multiple list.
All this options are like something like this:
<input type="checkbox" name="chk1" id="chk1" />chk1<br />
<input type="checkbox" name="chk2" id="chk2" />chk2<br />
<input type="checkbox" name="chk3" id="chk3" />chk3<br />
<input type="checkbox" name="chk4" id="chk4" />chk4<br />
<input type="checkbox" name="chk1_group2" id="chk1_group2" />A<br />
<input type="checkbox" name="chk2_group2" id="chk2_group2" />B<br />
<input type="checkbox" name="chk3_group2" id="chk3_group2" />C<br />
<input type="checkbox" name="chk4_group2" id="chk4_group2" />D<br />
My idea is to take al the values and save them in one sigle value like this:
String chk = "chk1, chk2, chk3";
String chk_group2 = "A,B,D";
I'm looking for a loop that can take all the vaules from the request and put the values in a sigle string. I'm tried whith List but it's not working.
I'm using JSP and a Oracle 10g DB
THK
I would first give every checkbox a "group" attribute (or something equally distinguishing), to specify what group it should represent, like so :
...
<input type="checkbox" group="group1" name="chk4" id="chk4" />chk4<br />
<input type="checkbox" group="group2" name="chk1_group2" id="chk1_group2" />A<br />
...
then parse them with something like this:
var group1 = [];
var group2 = [];
function parseSelected(){
// maybe a more specific query for this
var checkboxes = document.getElementsByTagName("input");
for (var i=0; i<checkboxes.length; i++) {
var checkbox=checkboxes[i];
// if its not checked, continue...
if(!checkbox.checked) continue;
if(checkbox.getAttribute("group")=="group1"){
group1.push(checkbox.getAttribute("name"));
} else if(checkbox.getAttribute("group")=="group2"){
group2.push(checkbox.getAttribute("name"));
}
}
}
and on some event somewhere (form submit possibly?)
parseSelected();
var strGroup1 = group1.join(', ');
var strGroup2 = group2.join(', ');
Since I stumbled upon this question.. even though it's been posted a long time, others may find it helpful as well.
You can access the checkboxes easily using jquery.each; e.g:
$(document).ready(function () {
$('th input[type=checkbox]').each(function() {
$(this).click(function (e) {
var table = $(e.target).closest('table');
$('td input:checkbox', table).prop('checked', this.checked);
});
});
});