I'm getting this error
error:Uncaught TypeError: Cannot read properties of null (reading 'value')
at HTMLButtonElement.<anonymous> (script.js:6:23)
Here is my code
const button = document.getElementById('button');
const input = document.querySelector('input[name="num"]:checked')
button.addEventListener('click', () => {
console.log(input.value)
input.value = document.getElementById('output').innerHTML
let before = document.getElementById('before')
let after = document.getElementById('after')
before.style.display = 'none'
after.style.display = 'flex'
})
I am trying to do a challenge from Frontend Mentor, I need to get access to the input value that is checked, and this error is appearing, but I cannot find a solution
The null is because querySelector didn't find a matching element, probably because you're looking for a checked input too soon (I'm guessing at page load). Instead, do your DOM query inside the click handler, so you're looking as of the click, not on page load.
const button = document.getElementById("button");
button.addEventListener("click", () => {
// Look for the checked input now that the button has been clicked
const input = document.querySelector('input[name="num"]:checked');
// *** Note the optional chaining (?.) on the below.
// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
// That way, we get `undefined` instead of an error if no element matched
// the selector.
console.log(input?.value);
/*
input.value = document.getElementById("output").innerHTML;
let before = document.getElementById("before");
let after = document.getElementById("after");
before.style.display = "none";
after.style.display = "flex";
*/
});
<input type="button" id="button" value="Click Me">
<label>
<input type="radio" name="num" value="A"> A
</label>
<label>
<input type="radio" name="num" value="B"> B
</label>
Related
How do I link a button to an input field? I am trying to create something so that when I click on the button, it will add what was in the text field, to an array (shown below)
const userTags = [];
function addTags(event) {
userTags.push(event.target.__ what do I even put here to get the input data? __)
}
<label>
Tags: <input type="text" name="todoTags"/> <button>Create new tag</button>
</label>
Again, I am trying to link up the button so that when I click it, it will grab the data from the input field, and add that data to the 'userTag' array with the addTags() function.
You can use the event target within your callback function to get the label using const parent = e.target.closest('label'), then use querySelector() to get the input element that is grouped under that label tag using const input = parent.querySelector('input') then set a variable to that value like const inputValue = input.value, then push the value into your array.
Your callback function is placed into an event listener for click.
const btn = document.querySelector('.btn')
const userTags = []
function getValue(e) {
// get the label by traversing up the DOM tree to the closest label element
const parent = e.target.closest('label')
// get the input that lives inside the label element using querySelector
const input = parent.querySelector('input')
// get the inputs value and assign to variable
const inputValue = input.value
// only push values that are not empty
if (inputValue !== "") {
userTags.push(inputValue)
}
console.log(userTags)
}
//event listener for click on btn element
btn.addEventListener('click', getValue)
<label>
Tags: <input type="text" name="todoTags"/> <button class="btn">Create new tag</button>
</label>
let valueArray = []
function getValue(){
let value = document.getElementById("input").value
valueArray.push(value)
document.getElementById("Messages").innerHTML = valueArray
}
<body>
<input type="text" id="input">
<button onclick="getValue()">Click</button>
<div id="Messages"></div>
</body>
Get the element with document.getElementById and then take its value
document.getElementById("Put Id In Here").value
How do I deal with this behaviour:
Relevant HTML:
<p>
Player 1: <input type="text" name="player1Name">
<input type="radio" name="option1" value="X" id='option1X'/> X
<input type="radio" name="option1" value="O" id='option1O' /> O
</p>
<p>
Player 2: <input type="text" name="player2Name">
<input type="radio" name="option2" value="X" id='option2X' /> X
<input type="radio" name="option2" value="O" id='option2O'/> O
</p>
Here's what I have tried:
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
function checkRadios(option1, option2, option3) {
option1.addEventListener('click', function () {
if(option1.checked && option2.checked)
option3.setAttribute('checked', 'true');
});
}
checkRadios(option1X, option2X, option2O);
checkRadios(option1O, option2O, option2X);
checkRadios(option2X, option1X, option1O);
checkRadios(option2O, option1O, option1X);
This works for the first time and then it stops working.
I checked the debugger, and the reason is that option3's value changes somehow.
Player1's radios are option1X and option1O.
What I want:
If an option is clicked by user A and the same option has already been taken by another user (B), then the other user's (B's) radio should change.
I tried changing the 'click' event to 'change' and that also didn't work.
Is this what you want?
I have used addEventListener method for calling a function that checks another radio button. There exists no need for clearing selected checkbox. This is because as soon as you check one radio button out of the two, other automatically gets deselected.
I have also used a function to check if both the two options are selected or not. If they are not, null is returned and then nothing happens. But if both of them are selected, manipulation of selected radio button takes place.
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
check = () => document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
option1X.addEventListener("change", function() {if (check()) option2O.checked = true});
option2X.addEventListener("change", function() {if (check()) option1O.checked = true});
option1O.addEventListener("change", function() {if (check()) option2X.checked = true});
option2O.addEventListener("change", function() {if (check()) option1X.checked = true});
Note: This starts working from MS Edge 12. For lower versions, change the check function to
function check() {
return document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
}
You may simply allow only the first player to choose the letter.
Anyway, you can simply change the checked property of the radio buttons:
switch (player1.choice) {
case "X":
player2RadioX.checked = false;
player2RadioX.enabled = false;
player2RadioO.checked = true;
player2RadioO.enabled = true;
break;
case "O":
player2RadioO.checked = false;
player2RadioO.enabled = false;
player2RadioX.checked = true;
player2RadioX.enabled = true;
break;
}
I tried .value , .textContent , innerText .... But nothing worked....
Below is my html
var input = document.getElementById('input').value
var button = document.getElementById('submit')
button.addEventListener('click', () => {
console.log(input) /// Output is always blank
})
<div class="input-section">
<input type="text" id="input" placeholder="Enter the word">
<button id="submit">Find</button>
</div>
You need to read the value property when the event fires, not before it.
let input = document.getElementById('input');
let button = document.getElementById('submit');
button.addEventListener('click',()=>{
console.log(input.value);
})
The reason why it is blank is because, you're initializing the input variable with the initial value inside input, i.e. nothing.
When you click the button, you want the "current" value of input, which means that you'd have to find value on each button click.
Do it like this :
var button = document.getElementById('submit')
button.addEventListener('click', () => {
var input = document.getElementById('input').value;
console.log(input);
})
<div class="input-section">
<input type="text" id="input" placeholder="Enter the word">
<button id="submit">Find</button>
</div>
Why can't I insert the value of an input into another input? The following example doesn't work:
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
// Trying to insert text into 'output'.
output.innerText = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
Thank you!
You should use .value instead of .innerText to set the value to an input element, like:
output.value = input.value;
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
output.value = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
may be this will be helpful. as per my knowledge. your code will not work on IE. because arrow functions are not supported in IE. however error in your code is "value1.innerText" which is not a right property. because in your code you can see.
value1.innerText=currentValue.value
so if you are fetching value using 'value' property of input. you have to assign a same property for another input box.
so function will be something like this.
var convertTemperature = function convertTemperature() {
var currentValue = document.getElementById("currentValue");
var value1 = document.getElementById("value1");
value1.value = currentValue.value;
};
You can get real time value by below code,
jQuery('input#currentValue').change(function(){
var current_value = jQuery('input#currentValue').val();
jQuery('input#value1').val(current_value );
});
function getId(e){
var xid = e.target.id;
console.log(xid);
}
<form onclick="getId(event)">
<label for="name" id="I am an Span">Nombre</label><br>
<input type="text" name="name" id="tbx_nombre"> <br>
<span id="nombre"></span> <br>
</form>
<div id="result"></div>
When the user click on a texbox the function gets the id of the element, then the deleteSpan method is call with the splitted id of the textbox which is now the id of the span to be changed to an emply string.
I get this error Cannot set property 'onclick' of null at getId
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name"></span>
...MORE INPUTS AND SPAN TAGS...
</form>
JS
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
document.getElementById(xid).onclick = function(){deleteSpan(spanId)};
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
You are getting that error because when you try to set the click handler on the span by ID, you don't currently have the correct ID. It's null, because the click target is currently the form (which doesn't have an ID) instead of the input.
As others mentioned, the click event listener should be attached to the input.
But you also don't need to set a separate click handler within getId--you can just call deleteSpan in the getId function. In fact, if you set it inside another handler like you have, it won't work the first time (unless that's your desired outcome).
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form>
<input onclick="getId(event)" type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>
onclick attribute event handler should be at input instead of form
<form>
<input type="text" name="name" id="tbx_name" onclick="getId(event)"><br>
<span id="name"></span>
</form>
or even better, use addEventListener for the inputs which have id format as tbx_{{value}}
var allInputs = document.querySelectorAll("input[id^='tbx_']");
allInputs.forEach( s => s.addEventListener( "click", e => getId ));
You can invoke above code when the form has loaded (at document load or window load).
You have to set the attribute onclick in input instead of form to get the expected id. Otherwise you have to check if the target node is INPUT or not:
function getId(e){
if(e.target.nodeName == 'INPUT'){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>