skip to Main Content

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


  1. 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!

    Login or Signup to reply.
  2. 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.

        var a = 1;
        var b = 2;
        var c = 3;
        /* OPTIONAL
        value1 = document.getElementById("value1");
        value2 = document.getElementById("value2");
        value3 = document.getElementById("value3");
        */
        let display = document.getElementById("display");
        value1.addEventListener("click", () => {changeValue(display,a)});
        value2.addEventListener("click", () => {changeValue(display,b)});
        value3.addEventListener("click", () => {changeValue(display,c)});
        
        function changeValue(target,value){
            target.textContent = `${value}`;
        }
        <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="display">select a radio button</p>

    If your script is in the <head>section, change the code as here bellow.

            var a = 1;
            var b = 2;
            var c = 3;
            let display, value1, value2, value3;
            window.addEventListener("DOMContentLoaded",main);   
    
            function main(e){
                display = document.getElementById("display");
                value1 = document.getElementById("value1");
                value2 = document.getElementById("value2");
                value3 = document.getElementById("value3");
                value1.addEventListener("click", () => {changeValue(display,a)});
                value2.addEventListener("click", () => {changeValue(display,b)});
                value3.addEventListener("click", () => {changeValue(display,c)});
            }
            
            function changeValue(target,value){
                target.textContent = `${value}`;
            }
        <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="display">select a radio button</p>
    Login or Signup to reply.
  3. 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:

    const a = 1,
      b = 2,
      c = 3;
    
    $("#value1").on("click", function() {
      // this will select all <p> elements, iterate through
      // them and set the text to an empty-string (removing
      // the existing text, if any has been set):
      $('p').text('');
      // then we retrieve the relevant element, via its
      // id - as in the original code - and update its
      // innerHTML to the value of the variable:
      document.getElementById("New").innerHTML = a;
    });
    
    $("#value2").on("click", function() {
      $('p').text('');
      document.getElementById("New2").innerHTML = b;
    });
    
    $("#value3").on("click", function() {
      $('p').text('');
      document.getElementById("New3").innerHTML = c;
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form method="post">
      <!-- Note that I've wrapped the <input> element with the <label>
           element in order that the <label> is useful, and increases
           the target area for interaction (whether using touch or
           a mouse): -->
      <label>Radio1
      <input type="radio" id="value1" name="value1">
      </label>
    
      <label>Radio2
      <input type="radio" id="value2" name="value1">
      </label>
    
      <label>Radio3
      <input type="radio" id="value3" name="value1">
      </label>
    </form>
    
    
    <p id="New"></p>
    <p id="New2"></p>
    <p id="New3"></p>

    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 – the value attribute of the <input> elements. First, jQuery:

    // select all <input> elements that have a
    // 'name' attribute, with the value set to
    // "value1", and we use the change() method
    // to bind the anonymous function of the method
    // as the event-handler for the 'change' event:
    $('input[name=value1]').change(
      function() {
        // selecting the <output> element (this will
        // select *all* such elements in the page,
        // but in the demo there's only the one:
        $('output')
          // setting the text of the <output>
          // element(s) equal to the value
          // of the changed <input>:
          .text(this.value);
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form method="post">
      <label>Radio1
        <input type="radio" id="value1" name="value1" value="1">
      </label>
    
      <label>Radio2
      <input type="radio" id="value2" name="value1" value="2">
      </label>
    
      <label>Radio3
      <input type="radio" id="value3" name="value1" value="3">
      </label>
    
    </form>
    
    <!-- using the <output> element to display the
         output from interactive elements; setting
         the 'for' attribute-value to a white-space
         separated list of element ids to which the
         output is related: -->
    <output for="value1 value2 value3"></output>

    JS Fiddle demo.

    Or, the above written using plain JavaScript:

    // selecting all <input> elements with a "name" attribute,
    // the value of which is equal to "value1", and then
    // iterating over that NodeList of elements using
    // NodeList.prototype.forEach():
    document.querySelectorAll('input[name=value1]').forEach(
      // here we use an anonymous Arrow function, which passes
      // a reference to the current <input> element ('el') to
      // the function body. Within the function body we use
      // EventTarget.addEventListener() to bind the anonymous
      // function of that method as the event-handler for the
      // 'change' event fired on the current <input>:
        (el) => el.addEventListener('change',(evt)=>{
        // here we select the first element on the page that
        // matches the supplied CSS selector, and update its
        // text-content, setting it to the value held in the
        // value property of the element to which the event-
        // listener was bound:
        document.querySelector('output').textContent = evt.currentTarget.value;
      })
    );
    <form method="post">
      <label>Radio1
        <input type="radio" id="value1" name="value1" value="1">
      </label>
    
      <label>Radio2
      <input type="radio" id="value2" name="value1" value="2">
      </label>
      
      <label>Radio3
      <input type="radio" id="value3" name="value1" value="3">
      </label>  
      
    </form>
    
    <!-- using the <output> element to display the
         output from interactive elements; setting
         the 'for' attribute-value to a white-space
         separated list of element ids to which the
         output is related: -->
    <output for="value1 value2 value3"></output>

    JS Fiddle demo.

    References:

    Login or Signup to reply.
  4. Here I just put a second event handler in to clear them all first (order of the handlers matters)

    var a = 1;
    var b = 2;
    var c = 3;
    
    $(".radio-thing").on("click", function() {
      $('.show-outputs').html('');
    });
    
    $("#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">
      <labelfor="value1">Radio1</label>
        <input class="radio-thing" type="radio" id="value1" name="value1">
        <label for="value2">Radio2</label>
        <input class="radio-thing" type="radio" id="value2" name="value1">
        <label for="value3">Radio3</label>
        <input class="radio-thing" type="radio" id="value3" name="value1">
    </form>
    <p class="show-outputs" id="New"></p>
    <p class="show-outputs" id="New2"></p>
    <p class="show-outputs" id="New3"></p>

    Here I modified to use a proper radio group and work that way;

    • remove the global variables
    • Put the index and the current value in the output with a template literal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
    • used a change handler instead of a click handler (could even use both)
    • used a radio type and name selector $("[name='value1'][type='radio']")
    • added another radio button just to show it uses that with an odd value also
    • wrapped the label to avoid the excess id’s and so I can click the text without the for='someid' needed
    $("[name='value1'][type='radio']")
      .on("change", function() {
        const newV = `Value:${$(this).val()} Index:${$(this).index('[name="value1"]')}!`;
        $('.show-output').html(newV);
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form method="post">
      <label>Radio1
      <input class="radio-thing" type="radio" value="1" name="value1"/></label>
      <label f>Radio2
      <input class="radio-thing" type="radio" value="2" name="value1"/></label>
      <label>Radio3
      <input class="radio-thing" type="radio" value="3" name="value1"/></label>
      <label>Radio cheese
      <input class="radio-thing" type="radio" value="cheese" name="value1"/ ></label>
    </form>
    <p class="show-output"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search