I have 3 radio buttons that on click output text. When I click on more than one button the content stays with the click.
Here is my code to explain more:
var a = 1;
var b = 2;
var c = 3;
$("#value1").on("click", function() {
document.getElementById("New").innerHTML = a;
});
$("#value2").on("click", function() {
document.getElementById("New2").innerHTML = b;
});
$("#value3").on("click", function() {
document.getElementById("New3").innerHTML = c;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<label>Radio1</label>
<input type="radio" id="value1" name="value1">
<label>Radio2</label>
<input type="radio" id="value2" name="value1">
<label>Radio3</label>
<input type="radio" id="value3" name="value1">
</form>
<p id="New"></p>
<p id="New2"></p>
<p id="New3"></p>
My issue is that whenever I click on value1 and then value2, instead of it just showing 2, it shows 1 2. How can I get it so that only 2, and only 2 is shown when clicking on value 2 after clicking on value1?
4
Answers
Are you sure that’s what’s happening?
Copying your code directly into a sandbox looks like behaves as you would expect!
https://codesandbox.io/s/stack-overflow-76095535-cw51o1?file=%2Findex.html
If you’re still having issues — share some additional details like browser or context that the code is running in!
If you want to display only one value when you click on a radio button, why do you have three
<p>
tags to display this value.Do you want to display more than one value on click?
If I misunderstand your goal, let me know, I will then update the answer.
And as you tagged the topic with "javascript" only, I suppose that a pure "javascript" answer is OK for you too.
Have a nice day.
If your script is in the
<head>
section, change the code as here bellow.A quick, and ugly, solution is to simply clear the text of the various
<p>
elements every time your user interacts with an<input>
, for example:JS Fiddle demo.
But don’t do that, it’s silly.
Instead, use the
change
event – along with an event-handler – to update the content of one element (unless you have a specific need for extraneous elements), that way the process of setting the text of that element also handles the removal of unwanted previous values.Also, in the following example, I’m going to replace the
<p>
elements with an<output>
element, and also set – and use – thevalue
attribute of the<input>
elements. First, jQuery:JS Fiddle demo.
Or, the above written using plain JavaScript:
JS Fiddle demo.
References:
<input>
.<label>
.<output>
.document.querySelector()
.document.querySelectorAll()
.Event
.EventTarget.addEventListener()
.NodeList.prototype.forEach()
.Node.innerHTML
.Node.textContent
.change()
.click()
.text()
.Here I just put a second event handler in to clear them all first (order of the handlers matters)
Here I modified to use a proper radio group and work that way;
$("[name='value1'][type='radio']")
for='someid'
needed