Ways to prevent the checked value from being continually added to the input text box

I am currently working on a project that involves integrating radio button values with an input field.

The purpose of the input field is to enter a name, while the radio buttons are meant for selecting the gender. The default text in the input field should be "My Name", and when a user selects a radio button, it should append the text "I am a {radio button value}".

While I have made some progress, I am facing the following challenges:

  1. When toggling between radio buttons, the text keeps adding up unnecessarily.
  2. By default, it displays "I am a undefined" instead of "My Name."
  3. How can I ensure that the user has selected a gender before submitting the form?

<input type="radio" id="single" name="sex" value="Boy">Boy &nbsp;  &nbsp; |  &nbsp;&nbsp;
<input type="radio" id="single" name="sex" value="Girl">Girl     
<br><br><br><br>
<p></p>

Jquery Script

function displayVals() {
var gender = $("input[type='radio']:checked").val();
var prefix = "I am a";

var checkedValue = $("p").html("<b>I am a </b> " + " " + gender );

var userInput = $("input[type='text']");
userInput.val(userInput.val() + prefix + " " + gender);

}

$("input[type='radio']").change(displayVals);
displayVals();

Link to the jsfiddle copy is

http://jsfiddle.net/ssbrbsfp/2/

Your assistance is greatly appreciated.

Answer №1

For a demonstration, you can view a functional fiddle here: http://jsfiddle.net/ssbrbsfp/6/

To prevent duplicate output, refrain from appending input.val again:

input.val(b + " " + a);

Prior to filling the input and paragraph, check if the value is undefined:

if(a != undefined)
{
    $( "p" ).html( "<b>I am a </b> " + " " + a );
    var input = $("input[type='text']");
    input.val(b + " " + a);
}
else
{
    $( "p" ).html( "<b>I am a </b> ");
}

To validate before submitting:

$(".SubmitButton").click(function () {
    if($("input[type='radio']:checked").val() == undefined)
    {

        alert("You must choose a sex");
        return false;
    }
});

I included this on the submit button for demonstration purposes, but it should ideally be placed in the form submit event.

Answer №2

At the beginning, the function displayVals(); is executed when the DOM is ready without any radio button selected, causing the input text to receive the value of "undefined". Then, on every radio change, the old value is added. Check out the code snippet below for a better understanding:

function displayVals() {
  var a = $("input[type='radio']:checked").val();
  var b = "I am a";

  var checkedValue = $("p").html("<b>I am a </b> " + " " + a);

  var input = $("input[type='text']");
  //you want to add only the value of radio each time.
  input.val(a);
}

$("input[type='radio']").change(displayVals);
//why execute this one on dom ready??
//displayVals();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onblur="this.placeholder = 'my name'" onfocus="this.placeholder = ''" placeholder="my name" name="name" id="my name" class="InputText">
<input type="submit" value="Submit" class="SubmitButton">

<br>

<input type="radio" id="single" name="sex" value="Boy">Boy &nbsp; &nbsp; | &nbsp;&nbsp;
<input type="radio" id="single" name="sex" value="Girl">Girl

<br>
<br>
<br>
<br>
<p></p>
<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>

Answer №3

Let's make some improvements:

  1. Optimize the input text definition by removing unnecessary onblur and onfocus attributes as placeholder already provides similar functionality.

  2. Eliminate the call to displayVals() at the end of the script for a cleaner code structure.

  3. Simplify the reassignment of the input value by removing the unnecessary input.val() +.

  4. Enhance validation by utilizing the required keyword in the definition of both input radio tags.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Two elements occupy the rest of the vertical space

In the center, there is a div with content inside. I want the top and bottom divs to occupy the remaining space. Similar to this example <div class="container"> <div class="top"> </div> <div class="middle"> C ...

Is there a way to restrict the number of times I can utilize slideToggle function?

When I continuously click on a div element in an HTML website that triggers the .slideToggle() method, it will keep opening and closing for as many times as I click. The problem arises when I stop clicking, as the <div> continues to toggle open and c ...

DjangoPDFViewer

I need help figuring out how to integrate a PDF Viewer into my Django website. Right now, I'm using an iframe to show the PDF, but I want to add annotation functionality directly on the site. I've looked into using PDF.js, but it means incorporat ...

execute a function after submitting the form

I need to implement a function that will be triggered when submitting a form. This function should work for all forms contained within the div with the id "#js_ajax_form". ( The JavaScript code functions properly in Chrome console // Here is the HTML sni ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

What is the reason for the error message saying "The prefix 'h' for the element 'h:head' is not bound"?

Below is the xhtml code I have created: <html> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/> </h:head> <h:body> <view> <h:form> <br/> ...

Effortlessly find data in an HTML table and showcase the results instantly without

I am looking for a way to implement search functionality in my table without refreshing the page. The fields above the table are used for searching and I want the results to be displayed within the same table. Here is an example of the code: <?php $for ...

What is the best way to vertically align my image for perfect centering?

On one of my pages at , there is a section titled "FREE PICK UP AND RECYCLING OF LARGE QUANTITIES OF ELECTRONICS" with a picture of a truck. The image is perfectly centered vertically between the pictures on its left and right. Another page I have at fea ...

Having trouble with your jQuery animation on a div?

Check out this jsFiddle example: http://jsfiddle.net/uM68j/ After clicking on one of the links in the demo, the bar is supposed to smoothly slide to the top. However, instead of animating, it immediately jumps to the top. How can I modify the code to ac ...

What is the reason why the `td` element is not being added to the final

var options = [{ "start" : "A", "text" : "CONTRACTORS OF HIGHWAY & HEAVY STRUCTURES: Contractors primarily engaged in the construction of highways, streets and roads, air strip paving, underground construction, ...

I want to utilize an Ajax/JQuery filled dropdown to dynamically alter the user interface without the need for additional server-side requests

I am working on a feature where an AJAX post method populates a dropdown with object descriptions. But, I also need to update a textbox with the selected ID when changing the selection, without making another AJAX call. Here's the relevant code snipp ...

Challenge with modal dialog scrolling on iPad and iPhone

Our website contains various pages that open JQuery 'Modal Dialog' boxes. These modal dialog boxes function well in all web browsers. However, there is an issue when viewing the website on an iPad or iPhone, which seems to be a common problem. ...

Concealing divisions on a website with CSS styling

In my div, I have some text that I want to hide. <div style='visibility:hidden;' id='emailid'>$email</div> Although the visibility attribute successfully hides the text, it leaves behind empty space on the webpage where th ...

Determine through code if a CSS file is being utilized

Is there a way to automate a CSS audit for file-level info without rendering the page? Could Selenium be used for this purpose? I've come across browser plugins that can help audit CSS files, but manually reviewing results for each page would be time ...

What measures can be taken to prohibit a user from accessing a client-side HTML file using express?

I am currently developing a task management application called "todolist." In my node.js code, I utilize express and grant it access to my directory named Client: var app = express(); app.use(express.static(__dirname + "/Client")); The contents of my Cl ...

CSS uses color parameters in the same way

Apologies, I spent a few years immersed in the world of IT. Now, onto my query: I have a lengthy ".css" file with numerous structures like color: #567567; within it. Is there a way to utilize a construction similar to color: $mycolor or is this not po ...

What is the best way to retrieve the date value from ngx-daterangepicker-material?

When utilizing ngx-daterangepicker-material for creating a range date, my goal is to obtain the startdate and enddate values in order to filter the table upon pressing the submit button! Here is the HTML code: <form [formGroup]="filtreForm" ( ...

Prevent the page from automatically scrolling back to the top when a user clicks on a "read more"

When implementing the function below on an HTML page to show/hide more details about a comment, there is an issue where the page scrolls up to the top whenever the "read more" link is clicked. This can be frustrating as it takes the user away from the comm ...

rails/jquery/ajax: The completion function is not being triggered

My code was functioning correctly without any errors when making an AJAX call that didn't require a return value. In my Javascript (specifically coffeescript), I had the following: $.ajax({ url: "/images/" + image_id + "/" + action, type ...

JavaScript jQuery not starting up

Having issues with the jQuery Vertical Accordion from Design Chemical Menu not loading properly. I'm new to jQuery and struggling to get it working as intended. The plugin isn't displaying the accordion menu, just plain lists. Even though testin ...