I am using the following html input element for collecting the product quantity in Html page but the user can still go ahead and manually enter negative value. For example: I selected the the textbox and entered -100 and input field took it without complaining about it.
How can I prevent user from entering 0 and non-negative values in Html input element?
<input type="number" id="qty" value="" size="3" min="1" />
Due to the <input type="number"> still not being widely well supported, you are still better off using a text input. Preventively you could disallow any characters which are not numbers with the keypress event and e.preventDefault(). However be sure that if you want to support legacy browsers (IE8-), there are a number of inconsistencies to take into account regarding returned key codes/ char codes. If you also want to disallow pasting non-number content, you can do so with the paste event and e.clipboardData.getData('plain/text') (for a complete implementation see here)
Test with the code below:
var myInput = document.getElementsByTagName('input')[0];
myInput.addEventListener('keypress', function(e) {
var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
function keyAllowed() {
var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50,
51,52,53,54,55,56,57,91,92,93];
if (key && keys.indexOf(key) === -1)
return false;
else
return true;
}
if (!keyAllowed())
e.preventDefault();
}, false);
// EDIT: Disallow pasting non-number content
myInput.addEventListener('paste', function(e) {
var pasteData = e.clipboardData.getData('text/plain');
if (pasteData.match(/[^0-9]/))
e.preventDefault();
}, false);
<input type="text">
You can validate the value with regex with the pattern attribute:
<input type="number" pattern="^[1-9]\d*$" name="qty">
You can use the built-in form validation validity.valid, user won't be able to enter or paste negative values. Also user won't be able enter decimals. More info here
<input type="number" min="1" oninput="validity.valid||(value='');"/>
try this :
<input type="number" min="0">
Related
I have an input field which only allows number:
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" pattern="[0-9]+"/>
I set more parameters than needed just to check if it would work with these. Unluckily it didn't.
When I am using it on Chrome it works, but when I am using it on Safari it doesn't.
Unfortunately, many browsers will only validate the input for an input with type="number" upon form submission. In such a case, the following prompt will appear (example from Safari):
I've modified your snippet to remove any non-numeric input as it is entered. I have tested that this snippet works on the Chrome, Firefox and Safari.
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
If you were willing to forgo the stepper, you could avoid having a single non-numerical character remove the entire input:
<input class="border" type="text" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
In these snippets, we use:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');"
to remove all characters that would result in the value in the input not matching a typical numeric form (no leading zeroes, no more than one decimal point).
Be warned: while you can use HTML, CSS and JavaScript to restrict what users enter when using your website normally (known as 'client-side validation'), it is trivial to bypass the restrictions set this way.
If you are sending this data to a server for transformation, you should not trust that this data will only be numeric and of the form you expect. You should consider this type of validation to be purely for convenience's sake rather than providing any guarantee that the server will receive valid data.
The above series of "replace" did not work for me. Since my project is in Angular, I instead created a custom form field validator. That way, an error is presented to the user on invalid input (which prevents form submission):
public static numberInputValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isUndefinedOrEmpty(control?.value) || control.value <= min) {
return { numberRequired: true };
} else if(control.value > max) {
return { numberTooBig: true };
}
return null;
};
}
The only related attributes on the HTML input field are: type="number" step=".01"
To use it, add the validator to your FormControl in your FormGroup:
myControlName: new FormControl<undefined | number>(undefined, numberInputValidator(0, 100))
And even though the validator takes only number inputs, it will return numberRequired if the form field contains non-numeric characters.
You can then display custom error messages as such this (right after the <input> field) if using Angular Material form fields:
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberRequired">
<p>Amount must be greater than zero</p>
</mat-error>
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberTooBig">
<p>Amount must be less than or equal to 100</p>
</mat-error>
<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel">
Here I have to hide zero amount while user entering the values.
If he enters all zero's then only we have to hide not in cases like 20,30,100 etc...
I'm using Angular 2.
<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel"
(keyup)="hideZero()>
Added This keyUp event in Html and in .ts added below code
hideZero(){
if(this.userBalance.transactionAmount === '0' ){
this.userBalance.transactionAmount = '';
}
}
Working Absolutely fine
/* In your ts */
validateNumber(value: String) {
userBalance.transactionAmount = value && value.replace(/(?:0*)(\d*)/g, (_,value1) => {
return value1;
})
}
<input (input)="validateNumber($event)">
Try using (ngModelChange) event which will trigger when user types values. By using regex, you can remove the last zero value and update the DOM. Hope this helps.
Angular 0 value don't display
<span *ngIf="!pro.model === '0'">{{ pro.model }}</span>
Like this,
When model value is zero that time don't display model value.
If model value is not zero that time show model value in your html pages.
I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type="number" required name="price" min="0" value="0" step="any">
Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
In case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
For currency, I'd suggest:
<div><label>Amount $
<input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by #SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.
You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.
function enforceNumberValidation(ele) {
if ($(ele).data('decimal') != null) {
// found valid rule for decimal
var decimal = parseInt($(ele).data('decimal')) || 0;
var val = $(ele).val();
if (decimal > 0) {
var splitVal = val.split('.');
if (splitVal.length == 2 && splitVal[1].length > decimal) {
// user entered invalid input
$(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
}
} else if (decimal == 0) {
// do not allow decimal place
var splitVal = val.split('.');
if (splitVal.length > 1) {
// user entered invalid input
$(ele).val(splitVal[0]); // always trim everything after '.'
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />
I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.
just adding step=".01", sorted my issue.
<input type="number" class="form-control" name="price" step=".01">
Use this code
<input type="number" step="0.01" name="amount" placeholder="0.00">
By default Step value for HTML5 Input elements is step="1".
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):
function handleNumberChanged (e) {
const fixed = parseFloat(e.target.value).toFixed(2).toString()
if (fixed.length < parseFloat(e.target.value).toString().length)
e.target.value = fixed
}
This question has been already answer but you can allow decimals
with the step attribute.
you can read more about it here: Allow-decimal-values
This is the solution I've came up with which also stops the user from typing in more that 2 decimals, which a lot of the solutions mentioned above, don't protect against
html:
<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"
Javascript:
function priceCheck(element, event) {
result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
if (result) {
let t = element.value;
if (t === '' && event.charCode === 46) {
return false;
}
let dotIndex = t.indexOf(".");
let valueLength = t.length;
if (dotIndex > 0) {
if (dotIndex + 2 < valueLength) {
return false;
} else {
return true;
}
} else if (dotIndex === 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Only 3 decimal point input value in textbox using Javascript.
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
<input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
On Input:
<input type="number" name="price" id="price" required>
On script:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
Currently the HTML5 <datalist> element is supported in most major browsers (except Safari) and seems like an interesting way to add suggestions to an input.
However, there seem to be some discrepancies between the implementation of the value attribute and the inner text on the <option>. For example:
<input list="answers" name="answer">
<datalist id="answers">
<option value="42">The answer</option>
</datalist>
This is handled differently by different browsers:
Chrome and Opera:
FireFox and IE 11:
After selecting one, the input is filled with the value and not the inner text. I only want the user to see the text ("The answer") in the dropdown and in the input, but pass the value 42 on submit, like a select would.
How can I make all browsers have the dropdown list show the labels (inner text) of the <option>s, but send the value attribute when the form is submitted?
Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select would be a better choice.
To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:
To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value with the value of the datalist option instead of the innerText.
The following code then checks for an option with that value, pushes that into the hidden field and replaces the input.value with the innerText.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText says, but the unique id from option.value is available upon form submit.
Demo jsFiddle
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
to get text() instead of val() try:
$("#datalistid option[value='" + $('#inputid').val() + "']").text();
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.
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)">