How to set an HTML5 input to required via JavaScript - 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" );

Related

How to set properties on other fields oninput with JQuery?

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() {
...
});

Update hidden form field with value from textfield

I am trying to set the value of a hidden form field with the value entered in a textfield when submitting my form.
I have tried combining the answers to various questions but the closest I have come is getting the 'id' of my source field - but not the value.
Text field name = wpcf-available-stock
Hidden field name = wpcf-total-stock
The hidden field simply needs to be set to the same value as the text field on form submit using Jquery?
I cannot seem to find a simple sample in other questions asked... thanks
To achieve expeccted result, use below
HTML:
<input type="hidden" name="wpcf-total-stock">
<input type="text" name="wpcf-available-stock" value="test">
JS:
$("input[name='wpcf-available-stock']").on('keyup',function(){
$("input[name='wpcf-total-stock']").val($(this).val());
alert($("input[name='wpcf-total-stock']").val());
});
Codepen- http://codepen.io/nagasai/pen/RRBwjA
First of all: Why would you fill a hidden form field from a text field when you're going to send it anyway?
Second, the jQuery looks like this:
var fieldValue = $('#wpcf-available-stock').val();
$('#wpcf-total-stock').val(fieldValue);
You can obviously chain that together, but this is pretty clean.
Here's a demo: https://jsfiddle.net/u5Lj8cLz/
Pure JavaScript solution.
updateHidden = function(x) {
document.querySelector("[name=bar]").value = x;
}
<input name="foo" value="" onchange="updateHidden(this.value)" type="text">
<input name="bar" value="sometext" type="hidden">
Update
updateHidden = function() {
document.querySelector("[name=bar]").value = document.querySelector("[name=foo]").value;
}
document.querySelector("[name=foo]").addEventListener("change", updateHidden);
/*
or,
document.querySelector("[name=foo]").addEventListener("keyup", updateHidden);
*/
<input name="foo" type="text">
<input name="bar" type="hidden">

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.

JavaScript if check-box is checked not working

I have a website form where I have fields that I want to be required (with JQuery Plugin) only when the check-box is checked.
So far I wrote JavaScript that works if the the check-box is not checked, or checked. But when a user checks the check-box and then unchecks it the code does not work (field is still mandatory when unchecked).
Also one other bug is for some reason this same code only works for updating only one items required boolean. For example if I have the same code but make it so two elements requirements are updated the script does not work at all.
Here is the relevant source code:
<script>
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "true");
}else{
document.getElementById("element1").setAttribute("required", "false");
}
}
</script>
<form>
<input type="checkbox" onclick="swap();" id="must" name="must" value="1" style="width:10;">
<input id="element1" type="text" name="element1" placeholder="Enter Value" >
<input type="submit" id="submit" name="submit" value="Send" >
</form>
Any assistance would be greatly appreciated.
Best way I know to check if checkbox is checked, it to use jQuery is() method (documentation). It handles x-browser differences for you. Also best way to add attribute to HTML element is to use attr() method.
if($("#must").is(":checked")) {
$("#element1").attr('required', 'required');
} else {
$("#element1").removeAttr();
}
You can check in DOM inspector that attribute is added.
Required attribute documentation is here.
Try this, in xhtml we specify required="required" and there no required="false", a better way is to remove attribute required on else
<script type="text/javascript">
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "required");
}else{
document.getElementById("element1").removeAttribute("required");
}
}
</script>
The required attribute is a boolean attribute, it presence means that the field is required and its absence means the field isn't required. It has only 3 valid forms 1. required alone by itself 2. required="" equal to an empty string 3. required="required"

Assign the value to different field ID?

I have a form with a unique identifier field that the user needs to enter, when passing this value it needs to appear in different field id. so for instance. the field that user enters the unique code in is called "unique" and the copy needs to be in "message", how can i achieve that?
<div data-role="fieldcontain">
<label for="pins" id="pinLabel"><span style="color:#f22300">*</span> Unique Code:</label>
<input data-mini="true" name="pins_r" id="pins" placeholder="9 alphanumeric characters"/>
</div>
<input type="hidden" id="msg" name="msg" value=pins>
Thanks
There are two ways to do this with JavaScript.
Method 1)
Have an onchange event on the unique field such that whenever the value is changed, change it in a hidden field called message.
<input type="text" id="unique" name="unique" onchange="setMessage(this);">
<input type="hidden" id="message" name="message">
function setMessage(field) {
document.getElementById('message').value = field.value;
}
Method 2)
Use ajax to post the form instead, that way you can build the fields yourself.
ie. post message= document.getElementById('unique').value
Both the above are greatly improved if you use JQuery or another JS helper framework.
If you want your values to be set in the label at the same time, it is entered.
You can do some thing like this.
$(document).ready(function() {
$('#pins').keypress(function() {
setTextValueForPins(this);
});
});
function setTextValueForPins(textPin)
{
$('#pinLabel').text($('#textPin').val());
}
If you want the value to be set after the user have entered the value, you can use the change event.
PS: Not tested the code , let me know if you face any Issues.

Categories