How to set properties on other fields oninput with JQuery? - javascript

I have three inputs, and I'm trying to make it so that a user can enter any number of them, but at least one, in order to do a search. The backend is built to handle it just fine parsing these from the URL, but I'm having trouble client-side.
Right now, I'm using oninvalid and oninput like so:
<input type="text" id="Input1" name="Input1" required oninvalid=
"setCustomValidity('Please enter a valid Input1')" oninput="setCustomValidity('')"/>
What I'm trying to do is, in this package of 3 inputs, set the other two inputs to not be requiredand have a setCustomValidity value of '' when a value is entered in one of the fields. I also would like it to re-establish those rules if, say, the user were to change their mind after typing into the wrong field.
The JQuery I have right now:
jQuery(function ($) {
var $inputs = $("#Input1, #Input2, #Input3")
$inputs.oninput = (function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', false)
$inputs.not(this).prop("setCustomValidity", "")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
<input type="text" id="Input1" name="Input1" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="text" id="Input2" name="Input2" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="text" id="Input3" name="Input3" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="submit" value="Submit" />
</form>
Everything seems to compile correctly in Razor Pages etc with no errors, but the required properties are not being removed or changed. If anyone could offer insight into what I'm doing wrong, it'd be splendid; I'm new to JS and JQuery in general, but I can see it's powerful stuff.

setCustomValidity isn't a property or attribute, it's a function that you call from the oninvalid attribute. So it should be:
$inputs.not(this).removeAttr("oninvalid");
And when you want to re-establish it, use:
$inputs.not(this).attr("oninvalid", "setCustomValidity('Please enter a valid Input1')");
But I'm not sure you need to do this. Once you make it not required, it should never trigger the "invalid" event. So you don't need to remove it at all.
You can also do this with jQuery event listeners. To add the handler:
$elements.on("invalid", function() {
this.setCustomValidity("Please enter a valid input");
}
To remove it:
$elements.off("invalid");
You also have a typo in the assignment of $this. It should be:
var $inputs = $("#Input1, #Input2, #Input3");
And there is no jQuery .oninput() method. So it should be:
$inputs.on("input", function() {
...
});

Related

Input type="text" maxlength validation is ignored on form submit

The maxlength attribute on inputs and textareas works fine for user input, but when I modify the value with Javascript or set it via value="..." and submit the form afterwards, the validation is not applied:
<form action="#">
<input type="text" maxlength="5" value="Longer than 5 chars">
<input type="submit">
</form>
Why does this not fail?
Compare with number input, where the form fails as expected:
<form action="#">
<input type="number" max="4" value="8">
<input type="submit">
</form>
According to MDN,
[maxlength] Constraint validation is only applied when the value is changed by the user.
But why? And can this be solved without Javascript? It seems redundant to validate the maxlength in two different places, first in HTML and second in Javascript.
For which attributes does this validation issue apply? maxlength, minlength, and more...? Number inputs? Date inputs? Is there a list of those so I know which ones I need to validate manually?
Edit: Here's a more specific use case:
function addChar() {
document.querySelector('input[type="text"]').value += 'a';
}
<form action="#">
<input type="text" maxlength="5" value="a">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>
The user might click on the "Add another character" button a couple of times and then submit the form. It will not fail. If I want to prevent the user from adding too many characters, I need to add custom Javascript validation:
function addChar() {
var input = document.querySelector('input[type="text"]');
if(input.value.length > input.maxLength) {
return;
}
input.value += 'a';
}
<form action="#">
<input type="text" maxlength="5" value="a">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>
And now, there's validation for maxlength two times in the code. This does not seem right and inconsistent compared to other validit restraints (like number input max above)
For certain input types, the pattern attribute can be most useful in this particular situation, because as you have identified, the spec treats maxlength and minlength differently as it comes to Constraint Validation.
Both minlength and maxlength require user input for the dirty value flag to be raised, triggering an invalid state, and thus forcing the validation on submit. Setting the value via a script does not raise the flag:
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fe-dirty
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constraints
However, the pattern attribute doesn't have this unique requirement and thus will be validated on form submit, so it seems, see the example below:
function addChar() {
var input = document.querySelector('input[type="text"]');
input.value += 'a';
}
input:invalid {
border: 1px solid crimson;
}
<form action="#">
<input type="text" value="a" pattern=".{1,5}" title="You may only include a maximum of 5 characters.">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>

How to modify HTML5 form data before validation?

I am trying to reuse HTML5 validation required in simple serach form (so one input). It's exactly what I need (validation message in browser's language, styling, not allowing to progress, etc.). What I missing is trimming input string so not allowing user to submit just whitespaces.
I made research already and onsubmit event seems to be too late triggered to modify anything. I can't also make any change of actual inputs, so those has to remain intact during whole process (like with classic validation).
Is there any way to solve it with vanilla HTML5 without using libs like jQuery?
Edit: Using pattern attribute is not a solution here because it has different error message than this field cannot be empty.
You could try something along the lines of
<form method = "post">
<input type = "text" required pattern=".*[^ ].*" oninvalid="setCustomValidity('Please fill out this field')"
onchange="try{setCustomValidity('')}catch(e){}"/>
<input type = "submit" />
</form>
Otherwise if you really, really need to use only the required attribute you something like this would work for you
<form method = "post">
<input type = "text" required oninput = "if(this.value.trim() == '') { this.value = '' }"/>
<input type = "submit" />
</form>
You can use onsubmit, You just need to return false if it doesn't validate
<form onsubmit="return check()">
Enter name: <input type="text" id="myinput">
<input type="submit">
</form>
<script>
function check(){
if(document.getElementById("myinput").value.trim().length ==0){
return false;
}
return true;
}
</script>

How to set an HTML5 input to required via JavaScript

I have a form with many input fields and radio buttons.
Some fields must get the required - attribute. But which fields are required depends on which radio button has clicked.
(If "Company-email" is checked -> input field "Company email" is required, otherwise private email)
Initially all field should be required=false.
But that does not work. No matter which value I give to the required-attribute, required is always true.
So... how can I set an input-field initially to required=false?
EDIT:
Thank you all for your answers.
In fact nothing works.
I made a test html document like this:
function test2()
{
document.getElementById("33").attr("required");
}
<form method="post" action="#">
<input type="text" id="33">
<input type="text">
<input type="text">
<input type="text">
<input type="radio" onclick="test2()">
<input type="submit" value="send">
</form>
It's unbelievable but this very simple example does not work.
The field with id 33 is not a required-field.
I can submit the form and nothing is checked.
What is wrong here?
EDIT 2:
Now I found the solution:
function test2()
{
document.getElementById("33").required = true;
}
This works for me on my example page. I have to check if i really can work with that in my real project.
required is a boolean attribute, so no matter what value you give it will still be required.
Instead of setting attributes you can set the element property
document.getElementById('companyemail').required = false;
Remove the required attribute from the fields that are not required.
In HTML5, this is an example of how to use required:
<input type="text" name="name" required>
So chances are that even when setting it to false (or anything, in fact) would be considered true.
$(document).ready(function() {
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
$("#companyemail").attr("required");
$("#privateemail").removeAttr("required");
}
else{
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
}
});
});
I hope this may help, let me know your feedback...
try to remove the required attributes
your-input.removeAttr( "required" );

How to check inputs in <form> and send form correctly

I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.

How to skip fields using javascript?

I have a form like this:
<form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.
I tried to use OnBlur and OnEnter, without success.
Try 1:
<form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
Try 2:
<form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing.
BTW, all this tried with Firefox on Linux.
Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):
<INPUT tabindex="3" type="submit" name="mySubmit">
You could use the onfocus event on field two, which will be called when it receives focus. At that point, field 1's value should be updated and you can perform your check then.
If you used the method you describe, and they worked, the focus would also change when the user clicks on the field, instead of tabbing to it. I can guarantee you that this would result in a frustrated user. (Why exactly it doesn't work is beyond me.)
Instead, as said before, change the tabindex of the appropriate fields as soon as the content of field one changes.
<form name="mine">
<input type="text" name="one" onkeypress="if (mine.one.value == '123') mine.three.focus();" />
<input type="text" name="two">
<input type="text" name="three">
</form>
Try onkeypress instead of onblur. Also, on the onfocus of field two is where you should be sending to three. I'm assuming you don't want them typing in two if one is 123 so you can just check that on two's onfocus and send on to three.

Categories