I would just like to know is it possible to change the input automatically to capitalized on a certain input field where the user entered a value with Caps Lock on.
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps On = TEST NAME
Expected: Test Name
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps Off = test name
Default: Test Name
I know some Names looks like Reader Van der Bank where not all the name parts are capitalized, but still would like to know if its possible. Thanks
Alternative : Think i might be using a php function to transform everything to lowercase and then capitalized.
Here is a javascript function to do that, if there is no CSS solution for it.
var id = document.getElementById("test");
function change() {
var arr = id.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
id.value = arr.join(" ");
}
id.addEventListener("change", change);
id.addEventListener("keyup", change);
<input placeholder="Brand Name" id="test" type="text" />
For multiple elements with class test
var elements = document.getElementsByClassName("test");
function change() {
var arr = this.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
this.value = arr.join(" ");
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("change", change);
elements[i].addEventListener("keyup", change);
}
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
Do you want to enter all the text capitalized in the input? then u can use text-transform:uppercase in css and if u want to change it while typing you can use toUpperCase() on keyup of that input.
style="text-transform: capitalize"
(Question was edited. New Answer.)
Give your input an id, for this example let's say it's called "theInputId".
Then add an onkeypress event to it also and call the function script I've listed below.
<input placeholder="Brand Name" style="text-transform: capitalized"
type="text" id="theInputId" onkeypress="capsLock(event)">
<script>
//Script to check if Caps Lock is on.
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('theInputId').style.textTransform = 'lowercase'
document.getElementById('theInputId').style.textTransform = 'capitalize'
}
}
</script>
Related
Users on my application are used to press "Enter" when changing to the next input instead of "Tab", so I've been trying to change focus to the next Element in tabindex when pressing "Enter" instead of "Tab" given this code:
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Now that I've achieved it I want to share my solution so the next person who has this problem finds the solution quickly.
Solution
In my case I aimed $("#data") for the function to trigger but you can use it with $(window).
This function will get triggered on keydown, will check if the key is "Enter" (wich key code is 13), look for the next element of the focused element (activeElement) according to the tabindex and then will focus it.
$("#data").keydown(function(e) {
if(e.keyCode == 13){
let active = document.activeElement;
let target = $('[tabindex="' + (active.tabIndex + 1) + '"]');
target.focus();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Edit
In reference to #freedomn-m 's comment, this is his code to set the tabindex attribute on the non-readonly elements:
$(() => $("#data :input:not([readonly])").attr("tabIndex", (i, a) => i));
That's the code that I was using before:
$(document).ready(function(){
let inputs = $('#data :input');
let tabindex = 0;
for(let i = 0; i < inputs.length; i++){
if($(inputs[i]).attr("readonly") !== "readonly"){
inputs[i].setAttribute("tabindex", tabindex);
tabindex++;
}
}
})
const inputs = document.querySelectorAll('#data input');
const inputsArray = Array.prototype.slice.call(inputs);
document.addEventListener('keypress', function (event) {
const key = event.which || event.keyCode;
if (key === 13) { // 13 is the keycode for the Enter key
const activeElement = document.activeElement;
const index = inputsArray.indexOf(activeElement);
if (index > -1 && index < inputsArray.length - 1) {
inputsArray[index + 1].focus();
}
}
});
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
I want to show the message "Input Number Only" if I oninput the alphabet. The first text box is successfully show but when I input alphabet into the second text box it does not show anything at the span. How to edit my code so that it will show the message after I on input the alphabet. Here my code :
function allvalidate(){
var inp = document.getElementsByClassName('text');
for(var i in inp){
if(inp[i].type == "text"){
if(!/^\d{1,}$/.test(inp[i].value)){
error.textContent = "Input Number Only";
error.style.color = "red";
return false;
}
else {
error.textContent = "";
}
return true;
break;
}
}
}
<p>Number of Customer</p>
<p><input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" oninput="allvalidate()"></p>
<p>Age</p>
<p><input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" oninput="allvalidate()"></p>
<span id="error"></span>
Replace the following statement:
for(var i in inp){
with
for(let i=0 ;i<inp.length;i++){
A delegated event listener bound to the document can intercept and process all the input elements without needing to explicitly add the oninput event handler to each one as above. That event handler can likely also be simplified by using isNaN rather than a regex
const errspan=document.getElementById('error');
document.addEventListener('input',e=>{
errspan.textContent = "";
if( e.target.type=='text' && isNaN( e.target.value ) ) {
errspan.textContent = "Input Number Only";
}
})
#error{
color:red
}
<p>Number of Customer</p>
<p>
<input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" />
</p>
<p>Age</p>
<p>
<input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" />
</p>
<span id="error"></span>
I am trying to change/set a value using javascript.
From what I have currently created this works for a piece of text in tags going by the id: title.
It works like this:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Now what I want to set is a value inside here:
Voornaam + Achternaam:<input type="text" name="firstname" value="" />
Which is basically supposed to be a firstname.
I want the value to be set, using the method I was already using for my tag.
However when I give it an id like so:
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
And also change my function change to that id instead of title, it doesn't change or set the value inside the firstname field.
could anybody help me out?
While I don't understand why you want one input to update another , if you want to change the value of an input field you must use .value instead of .innerHTML
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('firstname');
title.value = myNewTitle;
}
<h1 id="title">test</h1>
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
<br/><br/>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
You set the value attribute on an element with the value key:
var firstnameInput = document.getElementById('firstname');
firstnameInput.value = 'Firstname value';
You need to do this:
Use firstname.value = myNewTitle; instead of innerHTML.
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var firstname = document.getElementById('firstname');
firstname.value = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Voornaam + Achternaam:<input type="text" id="firstname" value = ""/>
Okay, so I have a form which adds an item to a list of items and does calculations with it, but every new item thats added is done on the users side before being submitted to the server for verification and updating of database. Now, I've looked at other answers and couldnt really get an answer. If the user adds a new item and enter a quantity and rate it should calculate the amount automatically, how would one extract the unique ID identifier to change the value of the amount? The code below and in this case the unique identifier is 19786868. The length of this identifier is always different and their is no unique pattern, the length and value is generated by a random command.
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
How would I extract this unique identifier with the OnChange command in JavaScript to calculate the amount value?
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
var id = el.id.replace(/\D+/g,"");
console.log( id ); // "19786868"
});
so basically use a this.id.replace(/\D+/g,"") where all non Digit \D gets replaced by ""
Here's an example using the input event:
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
el.addEventListener("input", function() {
var id = this.id.replace(/\D+/g,"");
alert( id );
}, false)
});
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_123_foobar" />
Take note that: asd_123_foo_9 will return 1239 as result so make sure to always have asd_123_foo as ID value
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" onchange="extractId(event);"/>
And in javascript :
function extractId(event) {
var elem = event.target;
var myArr = elem.id.split('_');
var yourUnique_id = myArr[3];
}
To be able to respond to newly added input controls, you need to capture the change event at some parent element, otherwise you will not trap the change on newly added elements.
Here is some code that handles the change event on the document. As this event bubbles up, it will eventually get there, so we can respond to it:
For extracting the number from the input's id, we can use a regular expression:
document.onchange = function(e) {
var match = e.target.id.match(/^(list_item_attributes_.*?_)(rate|quantity)$/);
if (!match) return; // not rate or quantity
// read rate and quantity for same ID number:
var rate = +document.querySelector('#' + match[1] + 'rate').value;
var quantity = +document.querySelector('#' + match[1] + 'quantity').value;
// write product as amount:
document.querySelector('#' + match[1] + 'amount').value = rate*quantity;
}
Quantity: <input class="form-control" type="text" id="list_item_attributes_19786868_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_19786868_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_19786868_amount" /><br>
<p>
Quantity: <input class="form-control" type="text" id="list_item_attributes_14981684_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_14981684_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_14981684_amount" /><br>
As you have asked to respond to the change event, I have kept it that way, but you might be interested to use the input event instead, which will trigger as soon as any character changes in an input.
The above sample does not protect the amount fields from input. You should probably do something about that, because users could just overwrite the calculated result.
document.querySelector(".my-form").addEventListener("change", function(e) {
var changed = e.target;
var matchedId = changed.id.match(/^(list_item_attributes_[^_]*)_/);
if (!matchedId) {
// this isn't one of the relevant fields
return;
}
var uniquePrefix = matchedId[1];
var quantity = document.querySelector("#" + uniquePrefix + "_quantity");
var rate = document.querySelector("#" + uniquePrefix + "_rate");
var amount = document.querySelector("#" + uniquePrefix + "_amount");
var newVal = quantity.value * rate.value;
if (isNaN(quantity.value) || isNaN(rate.value) || isNaN(newVal)) {
amount.value = "";
} else {
amount.value = newVal;
}
});
<form class="my-form">
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</form>
If the user adds a new item and enter a quantity and rate it should
calculate the amount automatically, how would one extract the unique
ID identifier to change the value of the amount?
You can use input event; for loop; attribute contains selector [attributeName*=containsString], .nextElementSibling, .previousElementSibling, to sum values of id containing "quantity" and id containing "rate" and set result at id containing "amount"
function calculate() {
this.parentElement.querySelector("[id*=amount]")
.value = +this.value
+ +(/quantity/.test(this.id)
? this.nextElementSibling
: this.previousElementSibling
).value
}
var elems = document.querySelectorAll("[id*=quantity], [id*=rate]");
for (var i = 0; i < elems.length; i++) {
calculate.call(elems[i]); elems[i].oninput = calculate;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" value="1" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" value="2" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</div>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786867_quantity" value="3" />
<input class="form-control" type="text" id="list_item_attributes_19786867_rate" value="4" />
<input class="form-control" type="text" id="list_item_attributes_19786867_amount" />
</div>
hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/