How to disable file input text box in IE? - html

Is it possible to prevent a user from typing in a file input text box in IE? The reason I ask is that if a user enters text that does not look like a file system path (eg. doesn't start with something like c:...) then when the user clicks the submit button nothing will happen.
I would either like to not allow the user to type in the box or have the form submit as normal.
I have found that the same question was asked here with no answer:
http://www.webmasterworld.com/html/3290988.htm
And this person came up with a hack which I can use if there is no other suitable answer:
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
EDIT: To clarify - if the user types "not a file path" in the text box next to the "Browse" button and clicks submit, in IE nothing will happen. The form will not submit - IE does not allow a form to be submitted when a <input type="file"> box does not have a real file path.

How about this one? You can't type, or right click and paste.
<input type="file" name="file" onKeyDown="this.blur()" onContextMenu="return false;">

This may be a bad idea to begin with. What if the user is not using a Windows OS and wants to upload the file /home/user/example.txt?
This type of check might be better implemented server side.

I solved this with another way using a button rather than a submit and using JavaScript to check the value before submitting.
<input type="file" name="inputFile">
<input type="button" onclick="if(fileHasValidPath()) { submitForm(); }" value="Submit">
function fileHasValidPath() {
if (isIE()) {
var inputFile = document.forms[0].inputFile;
if (inputFile.value != "" && /^(\w:)|(\\)/.test(inputFile.value)) {
alert("File is not a valid file. Please use the Browse button to select a file.");
inputFile.select();
inputFile.focus();
return false;
}
}
return true;
}
function submitForm() {
document.forms[0].submit();
}
I realise there still needs to be server-side validation for the file but this is only to prevent a user clicking on the Submit button and not seeing anything happening. Also, it assumes IE using a Windows OS.

one way is to put a little javascript code in the buttons onsubmit. The idea being to validate the box and either stop submission or allow it.
However, you are probably better off just validating the file contents server side and rendering the appropriate error back to the client.

the input type=file element's value property is readonly as for security issue. You can read this property and do a check. If it is not correspond with your rules, you will give a warn and let person to modify it.
The other way use outerHTML property override it.
for example:
HTML input file element called objInputFileElement.
objInputFileElement.outerHTML="";

Couldn't you use
<input ... disabled>
EDIT:no, actually that prevents submission as well... but in HTML 4 apparently
<input ... readonly>
should work. http://htmlhelp.com/reference/html40/forms/input.html

I found the option that solves your issue. Is the contentEditable option as follows:
<input type="file" name="name" contentEditable="false"/>

Here is a demonstration of the contentEditable option:
<input type="file" name="name" contentEditable="false" />

I based my solution on this thread.
So, considering this file field:
<input type="file" id="file_field">
I got it to work with something like this in jquery:
$(document).ready( function() {
$('#file_field').bind("keydown", function(e) {
e.preventDefault();
});
});
NOTE: You must use keydown instead of keypress as it covers DEL and BACKSPACE as well as any print key.

Related

How to disable Chrome autofill (after 2020)

I've stumbled across this issue a couple of times in the last while, where Chrome ignores autocomplete="false" and autocomplete="off". It will now even ignore autocomplete="whatever" or anything you do to trick it, if someone has submitted a form with that random "hack" in it before.
In trying to solve this issue, I came across this StackOverflow question, which doesn't solve the problem if you've submitted a form containing this field before.
EDIT: This is NOT for password fields.
I had this issue with a field that has "number" in the name and this triggering the CreditCard Autocomplete Dialog. This solution helped me get rid of it.
Even though this is not the intended use of the option, I think this is unlikely to break and works without JavaScript Hacks. A one time code won't trigger an autocomplete so I treat the fields that are not supposed to autocomplete as one time codes.
<input type="text" name="number" autocomplete="one-time-code" />
This did the trick for me. I tested it in Chrome 87.0.4280.141 and it works fine.
autocomplete="new-password" and set placeholder attribute with some text works for me.
<input name="name1" placeholder="Nº" type="text" autocomplete="new-password" />
Everytime I found a solution Chrome throws a spanner in the works again.
No longer working
autocomplete="new-*"
add an offscreen positioned bogus input element style="position: fixed;top:-100px;left:-100px;" as first <form> element
set <form autocomplete="off">
use <textarea> and style it as a field
Working solution (15 jul 2021)
Append a dummy <input> without a name attribute and make the original <input> type="hidden"
HTML
<input type="hidden" name="myfield" class="no-autofill"> <input>
Note that any events, (click, blur, focus) that show your custom
autofill should be added to the visible <input> element.
Then add a change event to sync the value to the hidden input.
const fields = document.querySelectorAll('input.no-autofill');
for (const field of fields) {
const dummy = field.nextElementSibling;
dummy.addEventListener('change',e => {
field.value = e.target.value;
});
}
Ow, before implementing. Make sure you visit the Chromium bug tracker
and tell the Chrome Developers why following the standard is important. So one day we might be able to just use:
<input name="myfield" autocomplete="off">
its work in my local machine try it...
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" readonly onfocus="this.removeAttribute('readonly');" style="background-color: white;">
It's November 2021, and none of the non-javascript solutions mentioned worked for my address-related field. What did work was actually changing the text in the label.
The Autocomplete dialog in Chrome was shown if:
The word "Address" is in the label at the start or end; and
There are at least two other address fields (seemingly anywhere in the page)
EDIT: If you put a zero-width joiner character entity in the middle of the word 'Address' in the label, the autocomplete dialog is suppressed!
i.e. set the label to Addres‍s
html, body {
font-family: 'Helvetica', Sans-Serif;
font-weight: 200;
line-height: 1.5em;
padding: 1em;
}
<div class="addressDiv">
<div>
<label>Focus on this field...Address</label>
<div>
<input autocomplete="off" type="text" aria-autocomplete="none" autocapitalize="none" />
</div>
</div>
<div>
<label>State</label>
<div>
<input autocomplete="address-level1" type="text" value="">
</div>
</div>
<div>
<label>City</label>
<div>
<input autocomplete="address-level2" type="text" value="">
</div>
</div>
</div>
<p>
See this JSFiddle
</p>
Read the note at the bottom before using this method
After struggling for a long time, I made it work reliably this way:
It is important that your input type is 'text'!!
define a css class
input.hidden-password {
-webkit-text-security: disc;
}
Then in your form, set autocomplete off, input types = 'text' and add the class to the input.
<form autocomplete="off">
<input
type = "text" // <----This is important
class = "hidden-password"
/>
</form>
C'mon Google, let us take control over our inputs! My client requires passwords to be changed very often and auto fill IS A BIG NO NO!
IMPORTANT NOTE Do not use this for login or any other place where security is required. I used this for a form within my app where the user was already authenticated and security was not required.
For Me, the problem only occurs, if I have multiple fields with the same value for autocomplete. If I set the value to a random number (Math.random()), no autocomplete is happening. I think it would also be possible to use an otherwise unique string.
To prevent 'manage addresses' level of of chrome popup: autocomplete='chrome-off'
To prevent autosuggest popup, if you can swing it: EXCLUDE name and id attributes.
Try to make your input readonly, enable it after focus
<input readonly="readonly" onfocus="this.removeAttribute('readonly');" type="text" value="test">
here is JS solution that works at this point in time for me:
<input name="name" type="text"
onfocus="this.__name = this.getAttribute('name'); this.removeAttribute('name')"
onblur="this.setAttribute('name',this.__name)"
>
The above js code stores input name to this.__name and removes the name onfocus later onblur name is restored so forms can work as expected, but chrome does not autofill.
No known attribute value is working in form tag. I have tried them all: do-not-show-ac, chrome-off, new-password, off...
The only way i found is by adding autocomplete='new-password' to every input component. To do it globaly, i am using this jquery:
<script>
$('input').attr('autocomplete', 'new-password');
</script>
The best way is to use JavaScript to skip browser's behavior, disableautofill.js does this.
You can try https://github.com/terrylinooo/disableautofill.js
<script src="https://cdn.jsdelivr.net/npm/disableautofill#2.0.0/dist/disableautofill.min.js"></script>
Usage:
var daf = new disableautofill({
'form': '#testForm', // Form id
'fields': [
'.test-pass', // password
'.test-pass2' // confirm password
],
'debug': true,
'callback': function() {
return checkForm(); // Form validator
}
});
daf.init();
How about just never submit the form? Nothing to remember!
Your app probably doesn't work without javascript anyway, right?
In fact, don't use a form at all, just collect the input values, serialize and do an ajax call.
$('#mybutton').on('click', function (e) {
$.ajax({
type: "POST",
url: 'mybackend',
data: $('#formdiv input').serialize(),
success: function (data) ...
Mind you, this is not a well tested idea, just something I have observed when I wanted autofill, and which I have not seen suggested in any of the many threads dealing with this issue.
I just resolved a related issue - it was forcing Chrome Autofill on an address field (Google Places Autocomplete, specifically) and no other solutions were working.
Eventually, we changed the nearest label to it from saying "Business Address" to being blank and set its text via CSS
#gmapsSearchLabel:after {
content: "Business Address";
}
And without a nearby label "saying" address, it stopped forcing Autofill.
A solution that works for me is to place a zero-width-white-space character into the placeholder text, so for example:
placeholder="Enter your address" becomes
placeholder="Enter your a[ZWSP]ddress"
Chrome is then unable to find "address" and skips autocomplete suggestions.
You can copy the character ( don't use the html entity etc. ) over at CSS Tricks. Here is the word "address" with the ZWSP character after the letter "a":
a​ddress
Dirty answer ,
edit "selectorForYourInputs" and works just fine, cross browser tested, max overhead 50ms, user never notice any performance lag:
counter = 0;
emptySearchboxInterval = setInterval(() => {
$(selectorForYourInputs).val("");
counter++;
counter == 100 ? clearInterval(emptySearchboxInterval) : null;
}, 20);

HTML input type=“file” in Google Chrome not showing popup window

I'm having a problem with the HTML tag <input type="file" /> in Google Chrome.
The 'Browse' button appears on the page as expected, but when I click it in order to select a file, the pop-up dialog window from the browser doesn't open at all.
I 've tested my form and in Firefox and works correct. Any ideas what's wrong and how can I fix it ?
Here is also the code:
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<label for="imgfile">File input</label>
<input type="file" name="imgfile" />
This happened to me on Chrome v88.0, and I tried everything -- removing all the event handlers, making the simplest form possible, removing all other html and js from the page -- and still the file-selection dialog would not appear when clicking the "Choose File" button.
Then I shut down Chrome and re-opened it ... and it worked again.
Golden advice:
Have you tried turning it off and on again?
In my case the problem was as follows :
Whole document had a "on click handler"
Inside click hander, the code was canceling all propagation with
return false;
Removing this return statement solved problem with input=file.
I knew the problem wasn't an issue with the specific web page I was currently browsing because I went to codepen and tried various file uploaders to no avail.
In my specific scenario, I had run a chrome update a few days ago but failed to relaunch chrome after the update.
Navigating to Help > About Google Chrome, Google had informed me that a relaunch was necessary.
After relaunch, the browser native file picker started appearing again.
There's no reason that this shouldn't work in Chrome. Have you tried copying JUST the mark up in the example you've given us into a HTML file, and opening that? Does it work? It should, unless there's some third party plugin or extension stopping it.
It may be that you have have mark up elsewhere causing this issue; perhaps a layer over the input field catching the click event before it can make it's way down to the "browse" button?
I had the same issue, it would work in safari but not chrome. Turns out I just needed to update my chrome browser. Apparently if your chrome version is out of date by two weeks functionality that has been around for over a decade breaks...you know google engineering at its finest...
There could be two reasons for the input type file not working.
The file type input is styled as visibility: hidden. To hide the input use opacity:0.
There may be click event on document or parent element resisting click on input tag.
I had same issue recently. Restarting chrome fixed it.
Go to chrome://restart to do it.
It seems that a plugin (Colorzila), that I had installed on Chrome, was stopping it. I deactivated it, restart the Chrome and worked eventually.
In my case, vendor css was having a default CSS written to hide the input type file to display: none, as shown below, removing that/overriding that, made browse to work as expected. Hope it may help, that to verify if css for input[type='file'] is driven from other places.
//remove the below code
input[type="file"] {
display: none;
}
I had a similar issue where I was hiding the input element and trying to trigger the popup when a user clicked on the form label.
In my case, the for attribute on the label element didn't match the id of the input. Once I updated the for on the label to match the input's id the popup window worked great.
Simple Example:
<form>
<label for="images">Click here to upload your images!</label>
<input id="images" type="file" accept="images/*" style="display:none;" />
</form>
I found it difficult to style the input itself, so I hid the actual input element and styled the label to look like a file upload input.
Now whenever someone clicks on the label element the file popup will appear even though the input element is hidden.
I set event.preventDefault() in ajax request that is why input value was not being sent in form data
I had a global event event listener on window:
window.addEventListener("click", event => {
event.preventDefault();
event.stopPropagation();
});
Of course this was stopping my input from reacting. Be careful with global or local listeners that do preventDefault()
this worked for me
<input type="file" id="fileProfile2" name="fileProfile2" accept="image/png,image/jpeg" >
You must use it like this
<form enctype="multipart/form-data">
.......
.......
<label for="imgfile">File input</label>
<input type="file" name="imgfile" />
<input type="submit" name="submit" value="submit" />
</form>
Hope it helps someone; in my case the issue was that I had event.preventDefault() applying to the whole document, because I had my eventListener applying to the whole document:
function onMouse( event ) {
event.preventDefault();
// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouseEventHandler( event );
}
document.addEventListener( 'click', onMouse, false );
I only wanted my custom event handlers to apply to one div, not to the whole document, and specifically I didn't want my event handlers overriding the form events, set up in another div. So I limited the scope of my eventListeners to the 'visualizationContainer' div:
document.getElementByID('visualizationContainer').addEventListener( 'click', onMouse, false );
That fixed everything.
Observed Symptoms: The "Choose File" button (from the input type=file html tag) does not pop a file selection dialog. Same web page works on Firefox (version 68.5.0) on the same device.
Answer: Use Firefox on Android if the failure to select a file for upload symptoms appear. The code below does work on Linux Chrome (version 80.0.3987.87). It also works on Windows 10 Chrome (version 80.0.3987.122). This seems to only apply to Android and likely only certain versions.
Hardware: LG-H812
Android version: 6.0
Chrome version: 80.0.3987.117
Code:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>t9.php</title>
</head>
<body>
<h1>t9.php</h1>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='filename'/><br>
<br>
<input type='submit' name='submit' value='submit'/><br>
<br>
</form>
</body>
</html>

An invalid form control with name='' is not focusable

In Google Chrome some customers are not able to proceed to my payment page.
When trying to submit a form I get this error:
An invalid form control with name='' is not focusable.
This is from the JavaScript console.
I read that the problem could be due to hidden fields having the required attribute.
Now the problem is that we are using .net webforms required field validators, and not the html5 required attribute.
It seems random who gets this error.
Is there anyone who knows a solution for this?
This issue occurs on Chrome if a form field fails validation, but due to the respective invalid control not being focusable the browser's attempt to display the message "Please fill out this field" next to it fails as well.
A form control may not be focusable at the time validation is triggered for several reasons. The two scenarios described below are the most prominent causes:
The field is irrelevant according to the current context of the business logic. In such a scenario, the respective control should be disabled or removed from the DOM or not be marked with the required attribute at that point.
Premature validation may occur due to a user pressing ENTER key on an input. Or a user clicking on a button/input control in the form which has not defined the type attribute of the control correctly. If the type attribute of a button is not set to button, Chrome (or any other browser for that matter) performs a validation each time the button is clicked because submit is the default value of a button's type attribute.
To solve the problem, if you have a button on your page that does something else other than submit or reset, always remember to do this: <button type="button">.
Adding a novalidate attribute to the form will help:
<form name="myform" novalidate>
In your form, You might have hidden input having required attribute:
<input type="hidden" required />
<input type="file" required style="display: none;"/>
The form can't focus on those elements, you have to remove required from all hidden inputs, or implement a validation function in javascript to handle them if you really require a hidden input.
In case anyone else has this issue, I experienced the same thing. As discussed in the comments, it was due to the browser attempting to validate hidden fields. It was finding empty fields in the form and trying to focus on them, but because they were set to display:none;, it couldn't. Hence the error.
I was able to solve it by using something similar to this:
$("body").on("submit", ".myForm", function(evt) {
// Disable things that we don't want to validate.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", true);
// If HTML5 Validation is available let it run. Otherwise prevent default.
if (this.el.checkValidity && !this.el.checkValidity()) {
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
return true;
}
evt.preventDefault();
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
// Whatever other form processing stuff goes here.
});
Also, this is possibly a duplicate of "Invalid form control" only in Google Chrome
In my case the problem was with the input type="radio" required being hidden with:
visibility: hidden;
This error message will also show if the required input type radio or checkbox has a display: none; CSS property.
If you want to create custom radio/checkbox inputs where they must be hidden from the UI and still keep the required attribute, you should instead use the:
opacity: 0; CSS property
None of the previous answers worked for me, and I don't have any hidden fields with the required attribute.
In my case, the problem was caused by having a <form> and then a <fieldset> as its first child, which holds the <input> with the required attribute. Removing the <fieldset> solved the problem. Or you can wrap your form with it; it is allowed by HTML5.
I'm on Windows 7 x64, Chrome version 43.0.2357.130 m.
Not only required field as mentioned in other answers. Its also caused by placing an <input> field in a hidden <div> which holds an invalid value.
Consider below example,
<div style="display:none;">
<input type="number" name="some" min="1" max="50" value="0">
</div>
This throws the same error. So make sure the <input> fields inside hidden <div> doesnt hold any invalid value.
This issue occurs when you provide style="display: none;" and required attribute to the input field, and there will be validation on submit.
for example:
<input type="text" name="name" id="name" style="display: none;" required>
This issue can be resolved by removing required attribute from the input field from your HTML. If you need to add required attribute, add it dynamically. If you are using JQuery, use below code:
$("input").prop('required',true);
If you need to remove this field dynamically,
$("input").prop('required',false);
You can also make use of plain Javascript if you are not using JQuery:
document.getElementById('element_id').removeAttribute('required');
Yet another possibility if you're getting the error on a checkbox input. If your checkboxes use custom CSS which hides the default and replaces it with some other styling, this will also trigger the not focusable error in Chrome on validation error.
I found this in my stylesheet:
input[type="checkbox"] {
visibility: hidden;
}
Simple fix was to replace it with this:
input[type="checkbox"] {
opacity: 0;
}
It can be that you have hidden (display: none) fields with the required attribute.
Please check all required fields are visible to the user :)
For me this happens, when there's a <select> field with pre-selected option with value of '':
<select name="foo" required="required">
<option value="" selected="selected">Select something</option>
<option value="bar">Bar</option>
<option value="baz">Baz</option>
</select>
Unfortunately it's the only cross-browser solution for a placeholder (How do I make a placeholder for a 'select' box?).
The issue comes up on Chrome 43.0.2357.124.
For Select2 Jquery problem
The problem is due to the HTML5 validation cannot focus a hidden invalid element.
I came across this issue when I was dealing with jQuery Select2 plugin.
Solution
You could inject an event listener on and 'invalid' event of every element of a form so that you can manipulate just before the HTML5 validate event.
$('form select').each(function(i){
this.addEventListener('invalid', function(e){
var _s2Id = 's2id_'+e.target.id; //s2 autosuggest html ul li element id
var _posS2 = $('#'+_s2Id).position();
//get the current position of respective select2
$('#'+_s2Id+' ul').addClass('_invalid'); //add this class with border:1px solid red;
//this will reposition the hidden select2 just behind the actual select2 autosuggest field with z-index = -1
$('#'+e.target.id).attr('style','display:block !important;position:absolute;z-index:-1;top:'+(_posS2.top-$('#'+_s2Id).outerHeight()-24)+'px;left:'+(_posS2.left-($('#'+_s2Id).width()/2))+'px;');
/*
//Adjust the left and top position accordingly
*/
//remove invalid class after 3 seconds
setTimeout(function(){
$('#'+_s2Id+' ul').removeClass('_invalid');
},3000);
return true;
}, false);
});
If you have any field with required attribute which is not visible during the form submission, this error will be thrown. You just remove the required attribute when your try to hide that field. You can add the required attribute in case if you want to show the field again. By this way, your validation will not be compromised and at the same time, the error will not be thrown.
It's weird how everyone is suggesting to remove the validation, while validation exists for a reason...
Anyways, here's what you can do if you're using a custom control, and want to maintain the validation:
1st step. Remove display none from the input, so the input becomes focusable
.input[required], .textarea[required] {
display: inline-block !important;
height: 0 !important;
padding: 0 !important;
border: 0 !important;
z-index: -1 !important;
position: absolute !important;
}
2nd step. Add invalid event handler on the input to for specific cases if the style isn't enough
inputEl.addEventListener('invalid', function(e){
//if it's valid, cancel the event
if(e.target.value) {
e.preventDefault();
}
});
It happens if you hide an input element which has a required attribute.
Instead of using display:none you can use opacity: 0;
I also had to use some CSS rules (like position:absolute) to position my element perfectly.
Yea.. If a hidden form control has required field then it shows this error. One solution would be to disable this form control. This is because usually if you are hiding a form control it is because you are not concerned with its value. So this form control name value pair wont be sent while submitting the form.
I came here to answer that I had triggered this issue myself based on NOT closing the </form> tag AND having multiple forms on the same page. The first form will extend to include seeking validation on form inputs from elsewhere. Because THOSE forms are hidden, they triggered the error.
so for instance:
<form method="POST" name='register' action="#handler">
<input type="email" name="email"/>
<input type="text" name="message" />
<input type="date" name="date" />
<form method="POST" name='register' action="#register">
<input type="text" name="userId" />
<input type="password" name="password" />
<input type="password" name="confirm" />
</form>
Triggers
An invalid form control with name='userId' is not focusable.
An invalid form control with name='password' is not focusable.
An invalid form control with name='confirm' is not focusable.
Another possible cause and not covered in all previous answers when you have a normal form with required fields and you submit the form then hide it directly after submission (with javascript) giving no time for validation functionality to work.
The validation functionality will try to focus on the required field and show the error validation message but the field has already been hidden, so "An invalid form control with name='' is not focusable." appears!
Edit:
To handle this case simply add the following condition inside your submit handler
submitHandler() {
const form = document.body.querySelector('#formId');
// Fix issue with html5 validation
if (form.checkValidity && !form.checkValidity()) {
return;
}
// Submit and hide form safely
}
Edit: Explanation
Supposing you're hiding the form on submission, this code guarantees that the form/fields will not be hidden until form become valid. So, if a field is not valid, the browser can focus on it with no problems as this field is still displayed.
There are many ways to fix this like
Add novalidate to your form but its totally wrong as it will remove form validation which will lead to wrong information entered by the users.
<form action="...." class="payment-details" method="post" novalidate>
Use can remove the required attribute from required fields which is also wrong as it will remove form validation once again.
Instead of this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" required="required">
Use this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text">
Use can disable the required fields when you are not going to submit the form instead of doing some other option. This is the recommended solution in my opinion.
like:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" disabled="disabled">
or disable it through javascript / jquery code dependes upon your scenario.
It will show that message if you have code like this:
<form>
<div style="display: none;">
<input name="test" type="text" required/>
</div>
<input type="submit"/>
</form>
You may try .removeAttribute("required") for those elements which are hidden at the time of window load. as it is quite probable that the element in question is marked hidden due to javascript (tabbed forms)
e.g.
if(document.getElementById('hidden_field_choice_selector_parent_element'.value==true){
document.getElementById('hidden_field').removeAttribute("required");
}
This should do the task.
It worked for me... cheers
There are things that still surprises me... I have a form with dynamic behaviour for two different entities. One entity requires some fields that the other don't.
So, my JS code, depending on the entity, does something like:
$('#periodo').removeAttr('required');
$("#periodo-container").hide();
and when the user selects the other entity:
$("#periodo-container").show();
$('#periodo').prop('required', true);
But sometimes, when the form is submitted, the issue apppears: "An invalid form control with name=periodo'' is not focusable (i am using the same value for the id and name).
To fix this problem, you have to ensurance that the input where you are setting or removing 'required' is always visible.
So, what I did is:
$("#periodo-container").show(); //for making sure it is visible
$('#periodo').removeAttr('required');
$("#periodo-container").hide(); //then hide
Thats solved my problem... unbelievable.
In my case..
ng-show was being used.
ng-if was put in its place and fixed my error.
Wow, a lot of answers here!
If the problem is <input type="hidden" required="true" />, then you can solve this in just a few lines.
The logic is simple and straight-forward:
Mark every required input on page-load with a data-required class.
On submit, do two things: a) Add required="true" to all data-required inputs. b) Remove required="true"` from all hidden inputs.
HTML
<input type="submit" id="submit-button">
Pure JavaScript
document.querySelector('input,textarea,select').filter('[required]').classList.add('data-required');
document.querySelector('#submit-button').addEventListener('click', function(event) {
document.querySelector('.data-required').prop('required', true);
document.querySelector('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
jQuery
$('input,textarea,select').filter('[required]').addClass('data-required');
$('#submit-button').on('click', function(event) {
$('.data-required').prop('required', true);
$('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
For Angular use:
ng-required="boolean"
This will only apply the html5 'required' attribute if the value is true.
<input ng-model="myCtrl.item" ng-required="myCtrl.items > 0" />
I found same problem when using Angular JS. It was caused from using required together with ng-hide. When I clicked on the submit button while this element was hidden then it occurred the error An invalid form control with name='' is not focusable. finally!
For example of using ng-hide together with required:
<input type="text" ng-hide="for some condition" required something >
I solved it by replacing the required with ng-pattern instead.
For example of solution:
<input type="text" ng-hide="for some condition" ng-pattern="some thing" >
Not just only when specify required, I also got this issue when using min and max e.g.
<input type="number" min="1900" max="2090" />
That field can be hidden and shown based on other radio value. So, for temporary solution, I removed the validation.
I have seen this question asked often and have come across this 'error' myself. There have even been links to question whether this is an actual bug in Chrome.
This is the response that occurs when one or more form input type elements are hidden and these elements have a min/max limit (or some other validation limitation) imposed.
On creation of a form, there are no values attributed to the elements, later on the element values may be filled or remain unchanged.
At the time of submit, the form is parsed and any hidden elements that are outside of these validation limits will throw this 'error' into the console and the submit will fail. Since you can't access these elements (because they are hidden) this is the only response that is valid.
This isn't an actual fault nor bug. It is an indication that there are element values about to be submitted that are outside of the limits stipulated by one or more elements.
To fix this, assign a valid default value to any elements that are hidden in the form at any time before the form is submitted, then these 'errors' will never occur. It is not a bug as such, it is just forcing you into better programming habits.
NB: If you wish to set these values to something outside the validation limits then use form.addEventListener('submit', myFunction) to intercept the 'submit' event and fill in these elements in "myFunction". It seems the validation checking is performed before "myFunction() is called.
Its because there is a hidden input with required attribute in the form.
In my case, I had a select box and it is hidden by jquery tokenizer using inline style. If I dont select any token, browser throws the above error on form submission.
So, I fixed it using the below css technique :
select.download_tag{
display: block !important;//because otherwise, its throwing error An invalid form control with name='download_tag[0][]' is not focusable.
//So, instead set opacity
opacity: 0;
height: 0px;
}
For other AngularJS 1.x users out there, this error appeared because I was hiding a form control from displaying instead of removing it from the DOM entirely when I didn't need the control to be completed.
I fixed this by using ng-if instead of ng-show/ng-hide on the div containing the form control requiring validation.
Hope this helps you fellow edge case users.

Why does my form submit in IE but not in Chrome?

I have a form with <input type="submit">. In Chrome submit doesn't do anything. On a Network tab in developer tools I see nothing. No errors in developer tools either. Meanwhile, if I do save a page and open a saved page, then after I press submit button, I see something appears in Network tab. This happens in Chrome and Firefox. This works as expected in IE.
Does anybody have a hindsight, what should I look at?
I don't need a direct answer, I only need to know, where should I look at. If someone posts a direction and that'll help me to solve my problem, I'll accept it as a correct answer.
Structure of a page looks like this:
html
head
body
div
div
form
form
form
form
form
input
input
table
table
tbody
tr..td..input type=submit
If you are not using any JavaScript for form validation then a simple layout for your form would look like this:
<form action="formHandler.php" method="post">
<input name="fname" id="fname" type="text" value="example" />
<input type="submit" value="submit" />
</form>
You need to ensure you have the submit button within the form element and an appropriate action attribute on the form element is present.
For a more direct answer, provide the code you are working with.
You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html
Are you using HTML5? If so, check whether you have any <input type="hidden"> in your form with the property required. Remove that required property. Internet Explorer won't take this property, so it works but Chrome will.
I faced this problem today, and the issue was I was preventing event default action in document onclick:
document.onclick = function(e) {
e.preventDefault();
}
Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:
document.onclick = function(e) {
if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}
Hello from the future.
For clarity, I just wanted to add (as this was pretty high up in google) - we can now use
<button type="submit">Upload Stuff</button>
And to reset a form
<button type="reset" value="Reset">Reset</button>
Check out button types
We can also attach buttons to submit forms like this:
<button type="submit" form="myform" value="Submit">Submit</button>
Check if you are using any sort of jquery/javascript validation on the page and try disabling it and see what happens. You can use your browser's developer tools to see if any javascript file with validate or validation is being loaded. You can also look for hidden form elements (ie. style set to display:none; or something like that) and make sure there isn't a hidden validation error on those that's not being rendered.
I ran into this on a friend's HTML code and in his case, he was missing quotes.
For example:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" style="width:90;font-size:10>
<input type="submit" value="submit"/>
</form>
In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.
Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.
Also, if you have any tags like center, move them out of the form.
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<center> <-- bad
As strange it may seems, it can have an impact.
You can't have a form element as a child (directly or indirectly) of another form element.
If the following does not return null then you need to remove the excess form elements:
document.querySelectorAll('form form');//Must return null to be valid.
check your form is outside the table

Remove text caret/pointer from focused readonly input

I am using an <input readonly="readonly">, styled as normal text to remove the appearance of an interactive field, but still display the value.
This is very useful to prevent a user from editing a field, while still being able to post the value. I realize this is a convenience method and that there are several workarounds, but I want to use this method.
Problem: The blinking caret still appears when the field is clicked/focused. (At least in FF and IE8 on Win7)
Ideally, I would like it to behave as it normally does, focusable, but without the blinking caret.
Javascript solutions welcome.
On mine there is no caret or so:
<input type="text" value="test" readonly="readonly" >
Take a look at this: http://www.cs.tut.fi/~jkorpela/forms/readonly.html
Sorry, now I understand your problem.
Try this:
<input type="text" value="test" onfocus="this.blur()" readonly="readonly" >
You can use this in your css, but it will not focus:
[readonly='readonly'] {
pointer-events: none;
}
You can remove the blinking caret by specify the css attribute into transparent
caret-color: transparent;
you can test the result here
It can be done using html and javascript
<input type="text" onfocus="this.blur()" readonly >
or jQuery
$(document).on('focus', 'input[readonly]', function () {
this.blur();
});
the only way i found for this was
//FIREFOX
$('INPUT_SELECTOR').focus(function () {
$(this).blur();
});
//INTERNET EXPLORER
$('INPUT_SELECTOR').attr('unselectable', 'on');
KENDO
$('.k-ff .k-combobox>span>.k-input').focus(function () {
$(this).blur();
});
$('.k-ie .k-combobox>span>.k-input').attr('unselectable', 'on');
The onfocus/blur method works ok to remove the cursor from a readonly field, but the browser does not automatically refocus on the next field, and you may lose focus altogether, which is not what the user usually expects. So, if this is required, you can use plain javascript to focus on the next field you want, but you have to specify the next field:
<input type="text" name="readonly-field" value="read-only"
readonly onfocus="this.form.NextField.focus()">
Where 'NextField' is the name of the field to goto. (Alternatively, you could provide some other means to locate the next field). Obviously, this is more involved if you want to navigate to some non-visible UI element, like a tab-panel, as you will need to arrange this as well.
Easy!
Just add disabled to input and it will not be clickable (focused)