HTML AutoFocus in a input field with value - html

first, if anyone has another more specific and better title for this question please tell me and I'll change. I've never been good at using Google so...
I'm currently using following code to create an input field
<input name="igname" type="text" maxlength="40" autofocus="autofocus" value="Hi">
It works fine, but there's just one problem -> the cursor is on the left, I want it to be on the right but I don't have any idea how to do so.
Thanks in advance

JoDev's answer does not seem to work with FF and could be simplified. el is the DOM element representing the input.
function moveCursorToEnd(el) {
'use strict';
var index=el.value.length;
el.focus();
el.setSelectionRange(index,index);
}

First idea
Use style='text-align:right' to change the text align.
PUT THE CURSOR TO THE END
To put the cursor to the end of editable element, use this : tested function | fiddle
For the fiddle, it works great on Chrome, but in FF, you have to give focus to the element because the IFRAME haven't got focus by default!
moveCursorToEnd = function(el, focused) {
console.log('go');
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
if(!focused)
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
if(!focused)
el.focus();
}
onbodyload = function() {
elem = document.getElementById('totheend');
moveCursorToEnd(elem);
}
<body onload='onbodyload()'>...
<input class='totheend' onfocus="if(typeof moveCursorToEnd != 'undefined') moveCursorToEnd(this, true)" name="igname" type="text" maxlength="40" autofocus="autofocus" value="Hi" >

Related

Get the radio button value in a form [duplicate]

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
var value = $('input:radio[name="radiogroupname"]:checked').val();

HTML input do not allow numbers

Right now I have an input field like this:
<input class="form-control" type="text"/>
But it stills allows the input of numbers.
I want names to be input and want to display an error message when the string contains a number. How can I achieve this?
You can use native HTML5 field validation
like e-mail validation (fiddle):
<input type="text" title="email" pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}" />
For your specific case you can use regexp like pattern="[a-zA-Z]*" (fiddle)
When you submit form it became highlighted with red border to show you validation error. In different browser it will behave slightly different.
I don't think there is standard way to override every default styling, however there are browser specific ways to do this (here).
For some style you can have css hooks in place for changes see here
Edit: updated fiddle.
This should help you to type only characters:
$(function() {
$('#txtNumeric').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<b>Enter Text:</b>
<input type="text" id="txtNumeric" />
</div>
no input alows just text:
http://www.w3schools.com/html/html_form_input_types.asp
... you can try js + action on input like onkeydown
http://www.w3schools.com/jsref/event_onkeydown.asp
and validate by regEx (just letters)
Regex to match only letters
can better control what happens when good or bad validation. Only the alert or change color etc.
You have several options....
Regardless of the options, you will be using regular expressions in some way shape or form.
You can do it on the client side using JavaScript...
function Validate () {
var inputValue = document.getElementById("test").value;
var reg = new RegExp('^\\d+$');
var test = reg.test(inputValue);
//--Do something with test--
console.log(test);
}
<input id="test" class="form-control" type="text" />
<button onClick="Validate()">Validate</button>
If it is just plain HTML with no server side code you will need to use JavaScript.
EDIT
And as far as I know this is supported in all browsers that support JavaScript regardless of version.

Make an html number input always display 2 decimal places

I'm making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?
So if someone else stumbles upon this here is a JavaScript solution to this problem:
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the html code if you so prefer
<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);
}
By changing the '2' in toFixed you can get more or less decimal places if you so prefer.
an inline solution combines Groot and Ivaylo suggestions in the format below:
onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"
An even simpler solution would be this (IF you are targeting ALL number inputs in a particular form):
//limit number input decimal places to two
$(':input[type="number"]').change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):
HTML
<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
JS
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
The accepted solution here is incorrect.
Try this in the HTML:
onchange="setTwoNumberDecimal(this)"
and the function to look like:
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
You can use Telerik's numerictextbox for a lot of functionality:
<input id="account_rate" data-role="numerictextbox" data-format="#.00" data-min="0.01" data-max="100" data-decimals="2" data-spinners="false" data-bind="value: account_rate_value" onchange="APP.models.rates.buttons_state(true);" />
The core code is free to download
I used #carpetofgreenness's answer in which you listen for input event instead of change as in the accepted one, but discovered that in any case deleting characters isn't handled properly.
Let's say we've got an input with the value of "0.25". The user hits "Backspace", the value turns into "0.20", and it appears impossible to delete any more characters, because "0" is always added at the end by the function.
To take care of that, I added a guard clause for when the user deletes a character:
if (e.inputType == "deleteContentBackward") {
return;
}
This fixes the bug, but there's still one extra thing to cover - now when the user hits "Backspace" the value "0.25" changes to "0.2", but we still need the two digits to be present in the input when we leave it. To do that we can listen for the blur event and attach the same callback to it.
I ended up with this solution:
const setTwoNumberDecimal = (el) => {
el.value = parseFloat(el.value).toFixed(2);
};
const handleInput = (e) => {
if (e.inputType == "deleteContentBackward") {
return;
}
setTwoNumberDecimal(e.target);
};
const handleBlur = (e) => {
if (e.target.value !== "") {
setTwoNumberDecimal(e.target);
}
};
myHTMLNumberInput.addEventListener("input", handleInput);
myHTMLNumberInput.addEventListener("blur", handleBlur);
Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.
What I didn't like about all these solutions, is that they only work when a form is submitted or input field is blurred. I wanted Javascript to just prevent me from even typing more than two decimal places.
I've found the perfect solution for this:
<!DOCTYPE html>
<html>
<head>
<script>
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
</script>
</head>
<body>
<p> Enter the number</p>
<input type="text" id="resultText" oninput="validate(this)" />
</body>
https://tutorial.eyehunts.com/js/javascript-limit-input-to-2-decimal-places-restrict-input-example/
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<input type="text" class = 'item_price' name="price" min="1.00" placeholder="Enter Price" value="{{ old('price') }}" step="">
<script>
$(document).ready(function() {
$('.item_price').mask('00000.00', { reverse: true });
});
</script>
give out is 99999.99

prevent cursor moving on text input

I have a few text inputs that I call a JS function when they are on focus. Basically this function changes the value oh this field.
When I do that, on IE, the cursor is moved to the left end of my input. That does not happen in Firefox. It just stays where I put it on the first place.
<input maxlength="5" type="text" onFocus=\"changeValueOnFocus(this);\">";
function changeValueOnFocus(myInput){
myInput.value = 1234;
}
Is there a way to avoid this?
Thanks!
Instead of onfocus rather use onfocusin, that'll make your code to work.
EDIT
I just realized, that there is no focusin in Firefox. Hence you need something heavier.
The script:
function changeValueOnFocus (e, elm) {
elm = elm || this;
elm.value = 1234;
return;
}
window.onload = function () {
if (window.onfocusin === undefined) {
document.getElementById('someinput').addEventListener('focus', changeValueOnFocus, false);
}
return;
}
and for input you'll need an id:
<input id="someinput" maxlength="5" onfocusin="changeValueOnFocus(event, this);" type="text" />
Now this supposed to be a cross-browser solution.
to move the cursor to the end of the textbox
modify your function like this :
function changeValueOnFocus(myInput) {
myInput.value = 1234;
//use this function to select text but in this case just to move cursor to the end
myInput.setSelectionRange(myInput.value.length, myInput.value.length);
}

Search form, if no value go to site

I have a search form which searchers wikipedia.com. Nothing fancy, a form with an input.
If the input is empty, currently the user is redirected here: http://en.wikipedia.org/w/index.php?title=Special%3ASearch&redirs=1&search=&fulltext=Search&ns0=1 .
Id like to redirect the users here: www.wikipedia.com instead
How can I do this?
This is my search form:
<form method="get" action="http://en.wikipedia.org/w/index.php">
<input type="hidden" value="Special:Search" name="title"/>
<input type="hidden" value="1" name="redirs"/>
<input type="text" name="search">
<input type="hidden" value="Search" name="fulltext"/>
<input type="hidden" value="1" name="ns0"/>
</form>
It's not possible, I don't think, without using JavaScript; if, as you've indicated, you're willing to use jQuery:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).attr('action','http://www.wikipedia.com/');
}
else {
$(this).submit();
}
});
JS Fiddle demo.
In plain JavaScript, the following seems to work (tested in Chromium 12 and Firefox 7 on Ubuntu 11.04):
var formEl = document.getElementsByTagName('form')[0];
var inputs = formEl.getElementsByTagName('input');
var textInputEl = [];
for(i in inputs){
if (inputs[i].type == 'text'){
textInputEl.push(inputs[i]);
}
}
formEl.onsubmit = function(){
if (textInputEl.value === '' || textInputEl.value === null){
this.action = 'http://www.wikipedia.com/';
}
else {
formEl.submit;
}
};
JS Fiddle demo.
I'm trying to set this up so that, with an empty text-input, the form will remove any hidden elements and then set the action, or the document.location to be http://en.wikipedia.org/wiki/Special:Random. This does not, for some reason, seem to work. Almost as if Wikipedia's finding something wrong and then redirecting to a different page. Ungh. Anyways, this is what I tried:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
$(this).attr('action','http://en.wikipedia.org/wiki/Special:Random');
}
else {
$(this).submit();
}
});
JS Fiddle demo;
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
document.location.href = 'http://en.wikipedia.org/wiki/Special:Random';
/*
I also tried 'document.location','window.location'
and 'window.location.href' all of which, predictably,
failed in exactly the same way.
*/
}
else {
$(this).submit();
}
});
JS Fiddle demo;