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:
- When toggling between radio buttons, the text keeps adding up unnecessarily.
- By default, it displays "I am a undefined" instead of "My Name."
- 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 |
<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.