prevent cursor moving on text input - html

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);
}

Related

Checkbox input is selected only when clicked outside

I have an issue with HTML which is generated via the GWT framework.
It seems that the checkbox can be selected only outside of input.
<label for="gwt-id">
<input type="checkbox" id="gwt-id" />
<span class="someclass"></span>
</label>
As you can see, there is for property. When I remove it then the checkbox can't be selected at all.
I didn't copy styles, because even after removing them it does not work. Any ideas why is it happening?
You can take a look at this thread.
But it will require some code.
Something like this:
document.addEventListener("click", function(evt) {
var flyoutElement = document.getElementById('flyout-example'),
targetElement = evt.target; // clicked element
do {
if (targetElement == flyoutElement) {
// This is a click inside. Do nothing, just return.
document.getElementById("flyout-debug").textContent = "Clicked inside!";
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
document.getElementById("flyout-debug").textContent = "Clicked outside!";
});
If you want, you can use an external library.
Or with Vue.js and React.js

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 AutoFocus in a input field with value

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" >

Return the value of a JS function and use it as the value for an input button

I want to set a JavaScript function which returns a string, and that string to be used as a value for a button. Something like this:
function test(){
x = "some text";
return x;
}
I want to use this function in a input element in the value attribute. Something like this:
<input type="button" id="s1" value="test()" />
Unfortunatly the button doesn't show "some text" but "test()" on the button. How can i fix this?
you could do:
<input type="button" id="s1" value="" />
<script type="text/javascript">
var elem = document.getElementById("s1");
elem.value = "some text";
</script>
The correct way to set the value of the button would be to use the HTML DOM, or a framework like JQuery. This also has a JSBin Demo.
For example,
HTML - Runs function test when document loads.
<body onload = "test()">
<input type="button" id="s1" value="" />
</body>
JavaScript -
function test(){
x = "some text";
document.getElementById("s1").value =x;
}
View JSBin Demo
value attribute for html button accepts only text. see here.
What I understand from your question is you want a html button whose value should be set by a javascript function. you can achieve this the other way around.
Get button element using document.getElementById and set the value inside the test()
you code should looks like this:
<input type="button" id="s1"/>
<script>
function test(){
document.getElementById('s1').value ='some text'; //s1 is the id of html button
};
test(); //dont forget to call function
</script>
You can also do it in an elegant way by using custom data attributes.
See a JSFiddle demo here: http://jsfiddle.net/NJ5sK/
Basically, you mark your input elements with the name of the function that should be called to return its value. Then you grab all the elements that have the data-value-function attribute, run the function and assign the value.
HTML:
<input type="text" data-value-function="cheese" />
<input type="text" data-value-function="animal" />
JS:
window.cheese = function() {
return "Limburger";
}
window.animal = function() {
return "Cat";
}
var elements = document.querySelectorAll('*[data-value-function]');
for (var i = 0; i < elements.length; i++) {
var valueFunctionName = elements[i].getAttribute('data-value-function');
elements[i].value = window[valueFunctionName]();
}
Enjoy!
function test(){
x = "some text";
document.getElementById('s1').value = x;
}

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