I am trying to have the input fields tab over to the next field once maxlength is met but I keep getting an error Failed to execute 'querySelector' on 'Document': 'name=2' is not a valid selector.. Ive read over mozialla's explanation of a querySelector and I've tried using the elements id to focus() on but that gives the same error. I guess Im not understanding how to properly craft a selector to pass to the querySelector.
My Input fields ill only show 2 i have 3:
<Input
onChange={dateChange("month")}
value={date.month}
id="1"
maxLength={2}
type="number"
/>
<span className="sep">/</span>
<Input
onChange={dateChange("day")}
value={date.day}
name="2"
id="2"
maxLength={2}
type="number"
/>
My onChange:
const dateChange = (field) => (e) => {
const fieldIndex = e.target.name;
let fieldIntIndex = parseInt(fieldIndex, 10);
// format to fit
let value = e.target.value;
if (value.length === e.target.maxLength) {
if (fieldIntIndex < 3) {
const nextfield = document.querySelector(
`name=${fieldIntIndex + 1}`
);
console.log(nextfield);
if (nextfield !== null) {
nextfield.focus();
}
}
}
const d = { ...date, [field]: value };
setDate(d);
debounceCallback(handleDateInputChange, d);
};
Im still learning so any advice on this would be great :) thanks in advance!
First of all, I think that it is incorrect to set event listeners like this:
onChange={dateChange("month")}
If you do it that way, you actually execute that function during rendering of the page. The function should be executed when the event occurs. The correct way to do this would be:
onChange={dateChange}
If you also wanted to add parameters to your function then you should do it like this:
onChange={dateChange.bind(this, "month")}
Moreover, regarding the query selector, I think the correct syntax would be:
const nextfield = document.querySelector(`input[name='${fieldIntIndex + 1}']`);
Your name prop is set to an input element, so we use input[name].
Also name has a string value, so we use input[name=''].
Finally we want to set name value parametrically, so we use `input[name='${parameter}']`.
You can find the MDN documentation of bind JavaScript function here and the documentation of querySelector here.
Edit: Another alternative for navigating among inputs would be the tabindex attribute. You can find more about it here.
Name is a string So i think you should do it like this(add brackets)
name='${fieldIntIndex + 1}'
Related
I've had a problem where I wrote a checked() function for the onchange of a checkbox:
<input
type="checkbox"
id = "checked"
onchange="checked()"
/>
Here's my javascript:
const check = document.getElementById("checkbox")
const yes = document.getElementsByClassName("yes")
function checked() {
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Basically I want the span with the class of yes to change output depending on if the checkbox is checked or not (Says Yes or No)
However, when I inspect, it says "TypeError: checked is not a function
at HTMLInputElement.onchange" even though my javascript is perfectly linked to my HTML (I checked this with an alert).
How can I solve this?
You're getting checkbox by id checkbox, but in your input field, you put id="checked" which is incorrect, so you need to correct your id from checked to checkbox.
<input
type="checkbox"
id = "checkbox"
onchange="checked()"
/>
You also need to change your function name from checked to another name (like checkData which is not similar with native values/functions) and then wrap your document.getElementById into your function
You should not use getElementsByClassName too, because it returns a list of elements and innerHTML does not work for those, so you need to select a particular element with getElementById
function checkData() {
const check = document.getElementById("checkbox")
const yes = document.getElementById("yes") //need to use `getElementById` instead of `getElementsByClassName`
//if `yes` element is not there, we don't need to set `innerHTML`
if(!yes) {
return
}
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Remember to implement your yes element like this
<p id="yes"></p> //tag name is your choice
Technically, checked is the name of the value attribute on that input and it's not a function, so you cannot use it as a function name.
By the way, thank #Teemu for the suggestion!
const check = document.getElementById("checkbox")
There is no such ID in your code named "checkbox". I think you want:
const check = document.getElementById("checked")
Try giving your IDs, function names and input-types unique names so you won't get them mixed up with each other.
I have some HTML:
<input type="text" />
and I'm trying to make it so that when the character limit hits 12 that javascript automatically deletes the next character from the input field. See code pen here: https://codepen.io/jadedeterville/pen/NWayzpM
Here is my JS:
inputEl.addEventListener("keyup", fixLength);
function fixLength() {
const inputElValue = inputEl.value.length;
if (inputElValue > 11) {
inputEl.innerHTML.slice(12);
}
}
I also tried inputEl.slice(12); and inputElValue.slice(12);but both of those tell me that .slice isn't a function. I tried adding the toString() but that didn't work either.
Appreciate some advice. I've been looking at this for a long time.
Thank you in advance!
try below code.
if (inputElValue > 11) {
inputEl.value = inputEl.value.slice(0,12);
}
There are three mistakes in your script:
With inputEl.innerHTML.slice(12); you're slicing anything from the start of the string up to index 12. So essentially you're clearing the whole string. If you want to keep a specific part of a string it's better to use string.substr(startIndex, length)
You don't assign the result of the slice operation to the <input> textbox e.g. inputEl.innerHTML=inputEl.innerHTML.slice(12);
you should use the .value property instead of .innerHTML as the latter will come up empty.
Putting it all together:
let inputEl = document.getElementById("inp");
inputEl.addEventListener("keyup", fixLength);
function fixLength() {
const inputElValue = inputEl.value.length;
if (inputElValue > 11) {
inputEl.value = inputEl.value.substr(0, 12);
}
}
<input type="text" id="inp" />
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();
I'm a novice back end developer and I've been tasked with fixing a feature and I'm stuck on the react portion. I can't seem to find the appropriate syntax to get a value from a select component and that's pretty much my whole issue. I've looked at lots of other posts and the react docs and nothing I'm trying is working. An example of markup is as follows(There's lots of select fields in this view):
<div className="grid-content noscroll medium-6 small-12" style={{overflow: 'visible'}}>
<div className="grid-content"><label>Program</label></div>
<div className="grid-content" style={{overflow: 'visible'}}>
<Select
key="program_key"
ref="program_key"
multi={false}
value={ jobData && jobData.program_key ? jobData.program_key : null}
options={programOptions}
onChange={this.changeField.bind(null, 'program_key')}
/>
</div>
</div>
Then the event handler is as follows:
changeField: function(propName) {
var field = this.refs[propName].getDOMNode();
console.log(field.input);
console.log(field);
var nextProp = field.value.length > 0 ? field.value : null;
var job = Object.assign({}, this.state.job);
job.payload.data[propName] = nextProp;
if(propName === 'user_id') {
this.changeUserId = true
}
this.setState({
job: job,
updated: false
});
}
The result of console.log(field) is:
<div class="Select is-searchable has-value" data-reactid=".0.0.2.0.1.0.1.1.0.1.1.$program_key">
<input type="hidden" value="NHDS" data-reactid=".0.0.2.0.1.0.1.1.0.1.1.$program_key.0">
It goes on from there but the 'value="NHDS"' is the piece that I need and I cannot figure out how to get to it for the life of me. Please let me know if I can clarify or improve this question. Thanks in advance.
Based on your example code it looks like you're using the react-select component https://github.com/JedWatson/react-select. onChange is going to fire with the new changed value as its prop. In your case the changeField method has a bound param ('program_key') that will be injected as the function's first parameter. The next parameter should be the selected value. To test this you can execute console.log(arguments) within the changeField function, it should return an array with 'program_key' and the new value. If that works just add a new param to changeField named newValue and use it where needed.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://github.com/JedWatson/react-select#further-options
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 like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].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">
var value = $('input:radio[name="radiogroupname"]:checked').val();