HTML5 Input Required Validation fails on Submit when javascript sets the value - html

Basically, I have two input controls a textbox and a checkbox. What I want to happen is when the checkbox is clicked, I want to set the value of the input. The javascript I have sets the default value however when I submit, the form fails validation for the input text to be required even though the text input has the value.
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
if (lh != null) {
lh.value = "NONE";
}
}
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')"
oninput="this.setCustomValidity('')" /><input type="checkbox" title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder

This is the code you have,
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
if (lh != null) {
lh.value = "NONE";
}
}
<form>
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')" oninput="this.setCustomValidity('')" />
<input type="checkbox" title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder
<input type="submit" value="Submit">
</form>
When I ran it, I cannot reproduce the problem (it passes the validation normally), but I could see a few issues. I have modified you code to produce what I think might be a better solution.
var original = "";
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
var checkbox = document.getElementById("NoLienHolderCheckBox");
if (checkbox.checked) {
original = lh.value;
document.getElementById('status').innerHTML = "Uncheck it to restore its original value";
lh.value = "NONE";
lh.setAttribute("disabled", "disabled");
lh.removeAttribute("required");
} else {
lh.value = original;
document.getElementById('status').innerHTML = "Check the Checkbox if there is no holder";
lh.setAttribute("required", "required");
lh.removeAttribute("disabled");
}
}
<form>
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')" oninput="this.setCustomValidity('')" /> <input type="checkbox"
title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder
<input type="submit" value="Submit">
<span id="status">Check the Checkbox if there is no holder</span>
</form>
If you run it, fill in the input field manually, and submit, it will work like normal. If you don't fill in and don't check the box, the required validation will still come into effect. If you don't fill it and check the box, the text will become "NONE", and if the problem reemerges, then it will still submit, and the backend can process that.
In your original answer, you checked if the input field is empty before setting it to NONE, but if the user filled something in, and then checked the check box, what will happen? It would submit, but instead of getting NONE, you would get the user's input instead, although the checkbox is checked. So the best way is probably to save the user value, and restore it upon unchecking.
First of all, you probably want to check if the user clicked on the checkbox to check it or to uncheck it, because your script would set it the text field to "NONE" even if the user checked the checkbox, changed his mind, changed the text, and clicked on it to uncheck. Additionally, lh != null will not work, because lh is the element, not its value. You need to access its value attribute. Additionally, you might want to consider removing the required attribute from the element, setting it to empty, and disabling it when the user checks it. This prevents any issues if the user manually inputs "NONE" in the field but leaves the input box unchecked. After all, your request would send the state of the check box as well.

Related

Required attribute in multi step form

I have used a multistep form and I am using "required" attribute in some of the input fields. As such
<input type="text" placeholder="Full name" id="name" name="name" required="Please enter your full name">
The user fills one form and clicks next and after three nexts he can submit.
But the required attribute triggers only when the I click the submit button.I want the user to fill all the fields before he clicks next on the form. By that I mean that the required must trigger on the next button.
You can run an function to check if the input field is empty, then add the required attribute to the input element.
Example code:
function checkValue() {
var name = document.getElementById("name");
if(name.value === "") {
var att = document.createAttribute("required");
name.setAttributeNode(att);
}
}
<form>
<input type="text" placeholder="Full name" id="name" name="name">
<button onclick = "checkValue()">Next</button>
</form>
Hope this helps !

HTML form submits an empty string when JavaScript indicates the hidden control has a value

Amongst many other controls, I have the following HTML elements on a form
<input ID='cmdRegisterMe' name='cmdRegisterMe' value='Register Me' onclick="return preSubmit();" type='submit' />
<input type="hidden" ID="NewHash" name="NewHash" value="">
<INPUT TYPE="TEXT" ID="email" NAME="email" VALUE="" SIZE="50" MAXLENGTH="50">
<INPUT TYPE="PASSWORD" ID="password1" NAME="password1" VALUE="" SIZE="30" MAXLENGTH="25">
<INPUT TYPE="PASSWORD" ID="password2" NAME="password2" VALUE="" SIZE="30" MAXLENGTH="25">
and JS functions
function preSubmit() {
document.getElementById("NewHash").value = doNewHash(document.getElementById("password1").value, document.getElementById("email").value.toLowerCase());
alert(document.getElementById("NewHash").value);
document.getElementById("password1").value = '';
document.getElementById("password2").value = '';
return true;
}
function doNewHash(pw, strUsername) {
var hash_padding = '************';
return SHA1(SHA1(pw) + hash_padding + strUsername);
}
When I click Submit, I see the expected hashed value displayed by the call of alert().
However, in my PHP, the value of $_POST['NewHash'] is an empty string. I cannot fathom why this happens. In my understanding, there is no other code executed after the onclick() function returns true. I have done a global search on my code for 'NewHash' and there are no other assignments to it.
If I replace this line
document.getElementById("password1").value = '';
with this
document.getElementById("password1").value = document.getElementById("NewHash").value;
and inspect $_POST['password1'], it contains the hash value. What on earth could be happening to wipe out the value of 'NewHash'?
I have found what was wrong, but I hope posting the question may help someone else. I saved the PHP-generated HTML as a file, added to the top, and resolved to remove code piece by piece and submit until the submitted value for NewHash was no longer empty. I found I had TWO hidden controls called NewHash - so JS was displaying the value in one, and the browser was submitting the other!

Text enter in one text box gets populated in another

Here is a part of my html code for angularjs app
<input type="text" class="input-xlarge" id="user_name" ng-model="myModel.text"
name="user_name" rel="popover" data-content="Enter your first and last name."
data-original-title="Full Name">
<input type="text" class="input-xlarge" id="user_email" ng-model="myModel.text"
name="user_email" rel="popover" data-content="What’s your email address?"
data-original-title="Email">
Here is my controller code
function MyCtrl2($scope) {
var initial = {text1: 'initial value'};
var ini = {text2: 'initialvalue'};
$scope.myModel = angular.copy(initial);
$scope.myModel = angular.copy(ini);
}
MyCtrl2.$inject = ['$scope'];
What ever I write in first text box automatically gets populated in second text box too.Why is dat happening.How to avoid it.
Because both of your fields have the same ng-model.
To avoid it, use different values for ng-model for each input field.
Because your both input field associate with same model name myModel.text

How do you automatically set text box to Uppercase?

I am using the following style attribute to set the user input to uppercase so that when the user starts typing in the text box for example railway, then it should be altered to capital letters like RAILWAY without the user having to press the Caps-lock button.
This is the code I am using for the input:
<input type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0" style='text-transform:uppercase'/>
But I am not getting the desired output by using this attribute.
You've put the style attribute on the <img> tag, instead of the <input>.
It is also not a good idea to have the spaces between the attribute name and the value...
<input type="text" class="normal"
name="Name" size="20" maxlength="20"
style="text-transform:uppercase" />
<img src="../images/tickmark.gif" border="0" />
Please note this transformation is purely visual, and does not change the text that is sent in POST.
NOTE: If you want to set the actual input value to uppercase and ensure that the text submitted by the form is in uppercase, you can use the following code:
<input oninput="this.value = this.value.toUpperCase()" />
I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:
<input oninput="this.value = this.value.toUpperCase()" />
EDIT
Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
The answers with the text-transformation:uppercase styling will not send uppercased data to the server on submit - what you might expect. You can do something like this instead:
For your input HTML use onkeydown:
<input name="yourInput" onkeydown="upperCaseF(this)"/>
In your JavaScript:
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
With upperCaseF() function on every key press down, the value of the input is going to turn into its uppercase form.
I also added a 1ms delay so that the function code block triggers after the keydown event occured.
UPDATE
Per recommendation from Dinei, you can use oninput event instead of onkeydown and get rid of setTimeout.
For your input HTML use oninput:
<input name="yourInput" oninput="this.value = this.value.toUpperCase()"/>
The problem with the first answer is that the placeholder will be uppercase too. In case you want ONLY the input to be uppercase, use the following solution.
In order to select only non-empty input element, put required attribute on the element:
<input type="text" id="name-input" placeholder="Enter symbol" required="required" />
Now, in order to select it, use the :valid pseudo-element:
#name-input:valid { text-transform: uppercase; }
This way you will uppercase only entered characters.
try
<input type="text" class="normal"
style="text-transform:uppercase"
name="Name" size="20" maxlength="20">
<img src="../images/tickmark.gif" border="0"/>
Instead of image put style tag on input because you are writing on input not on image
Set following style to set all textbox to uppercase:
input { text-transform: uppercase; }
Using CSS text-transform: uppercase does not change the actual input but only changes its look.
If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:
document.querySelector("input").addEventListener("input", function(event) {
event.target.value = event.target.value.toLocaleUpperCase()
})
<input>
Here I am using toLocaleUpperCase() to convert input value to uppercase.
It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.
To overcome this jumping of the cursor, we have to make following changes in our function:
document.querySelector("input").addEventListener("input", function(event) {
var input = event.target;
var start = input.selectionStart;
var end = input.selectionEnd;
input.value = input.value.toLocaleUpperCase();
input.setSelectionRange(start, end);
})
<input>
Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;} to CSS file and everything will be fine.
The issue with CSS Styling is that it's not changing the data, and if you don't want to have a JS function then try...
<input onkeyup="this.value = this.value.toUpperCase()" />
on it's own you'll see the field capitalise on keyup, so it might be desirable to combine this with the style='text-transform:uppercase' others have suggested.
Various answers here have various problems, for what I was trying to achieve:
Just using text-transform changes the appearance but not the data.
Using oninput or onkeydown changes the cursor position, so you can't, for instance, click in the middle of your existing input and edit it.
Saving the position works, but just seemed a bit kludgey.
It felt cleaner to me to just break the problem up into two parts: upper-casing what I'm typing while I type (text-transform), and upper-casing the submitted data (run toUpperCase onchange):
<input id = "thing" onchange="this.value = this.value.toUpperCase(); pr()" style=text-transform:uppercase /><p>
<b><span id="result"></span></b>
<script>function pr() {document.getElementById("result").innerHTML = document.getElementById("thing").value}</script>
Type something in that, hit return or click out of the input, then click in the middle of your previous entry, add some lc text, hit return...
IN HTML input tag just style it like follows
<input type="text" name="clientName" style="text-transform:uppercase" required>
in backed php/laravel use:
$name = strtoupper($clientName);
This will both show the input in uppercase and send the input data through post in uppercase.
HTML
<input type="text" id="someInput">
JavaScript
var someInput = document.querySelector('#someInput');
someInput.addEventListener('input', function () {
someInput.value = someInput.value.toUpperCase();
});
As nobody suggested it:
If you want to use the CSS solution with lowercase placeholders, you just have to style the placeholders separately. Split the 2 placeholder styles for IE compatibility.
input {
text-transform: uppercase;
}
input:-ms-input-placeholder {
text-transform: none;
}
input::placeholder {
text-transform: none;
}
The below input has lowercase characters, but all typed characters are CSS-uppercased :<br/>
<input type="text" placeholder="ex : ABC" />
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0"/>
I went with the style text-transform:uppercase thing from poster. Then I just did the uppercase thing in php as well. Some people working too hard with that javascript.
You were close with the style being in the wrong place. You were trying to uppercase an image instead of the input.
$name = strtoupper($_POST['Name']);
I don't know why I wanted to throw in some extra stuff if it's a php page. This is something I like to do make it smoother for the person filling out the form.
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20" value="<?php echo $name; ?>"> <img src="../images/tickmark.gif" border="0"/>
That's assuming you're using PHP as the backend and posting to the same page you are on. This will keep the user from having to fill out that part of the form again. Less annoying for the person filling out the form.
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
document.getElementById('capitalizeInput').addEventListener("keyup", () => {
var inputValue = document.getElementById('capitalizeInput')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);
}
document.getElementById('capitalizeInput')['value'] = inputValue;
});
<input type="text" id="capitalizeInput" autocomplete="off" />
Just use this oninput in your input field:
<div class="form-group col-2">
<label>PINCODE</label>
<input type="number" name="pincode" id="pincode" class="form-control" minlength="6" maxlength="6" placeholder="Enter Pincode" oninput="this.value = this.value.toUpperCase()" autocomplete="off">
</div>
Just add in your input(style="text-transform:uppercase")
<input type="text" class="normal" style="text-transform:uppercase" name="Name" size="20" maxlength="20">
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">

How can I make an input field read only but still have it send data back to a form?

I have an input field:
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" />
I want the field to display on my form but don't want the user to be able to edit the field. When the user clicks submit I want the form value to be sent back to the server.
Is this possible. I tried different combinations of disabled = "disabled", readonly = "readonly". Seems I always get nothing sent back for the field.
Adding a hidden field with the same name will sends the data when the form is submitted.
<input type="hidden" name="my_name" value="blablabla" />
<input type="text" name="my_name" value="blablabla" disabled="disabled" />
With Chrome browser on Windows 10 just having name="your_name" and the readonly attributes works fine: client cannot change a value, but it is sent to the server.
On the assumption you're using a script to create the form, I'd suggest using <input type="hidden" /> which will submit the variable with the form, but also use a regular <input type="text" readonly="readonly" /> to show the variable to the user. This won't submit the value, obviously, but will make it visible (while the hidden input will submit the value, but not show the value).
You could also do this with JavaScript:
var theForm = document.getElementsByTagName('form')[0];
var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
if(inputs[i].type == 'hidden'){
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.setAttribute('disabled');
newInput.value = inputs[i].value;
theForm.appendChild(newInput);
}
}
Clumsy JS Fiddle demo.
alternatively u can make a little manipulation with javascript, remove the disabled property before form submitted
<form action="target.php" method="post">
<input type="text" id="anu" name="anu" value="data anu" disabled="disabled" />
<button onclick="document.getElementById('anu').disabled=''">send</button>
<script type="text/javascript">
function myFn(event) {
event.stopPropagation(); event.preventDefault();
}
</script>
<input onkeydown="myFn(event)" >
You can add 'readonly'='true' in the input element. With this the user cant edit and also send the value back to the server.
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" readonly='true' />
You should consider using input type="hidden" when submitting read-only fields. Otherwise, if you still need the value of input field to be visible, you should create another input (type=text) with a different name.
<input cid="Topic_Created" name="Topic.Created" type="hidden" value="6/5/2011 8:22:45 AM" />
<!--This is visible: -->
<input cid="Topic_Created" name="doesntmatter" size="25" type="text" value="6/5/2011 8:22:45 AM" />