How to assign input radio value to a textarea content? - javascript

I have this form:
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
And I have this other form with an textarea:
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required/>
</form>
I would like to know if there is any simple way to assign the value of the chosen input inside the textarea content right when user click one of these input.

A more feasible and easiest way would be do this way by making sure you assign an id to your form which will ensure that you are only selecting Input[type=radio] from that form and not every input on your page.
Also use textContent to assign a value to your textArea. Using innerHTML is not recommended.
We need to use forEach function to loop through all the input which we will find using querySelectorAll function (which returns all nodes list) and then use we can addEventListener to make sure that we listen to change events on your input and assign the value of the checked radio button to your textArea
Live Demo:
//get all radio buttons
let getRadios = document.querySelectorAll('#myForm > input[type="radio"]');
//get text area
let getTextArea = document.querySelector('#textarea-field');
//Loop through the radio button
getRadios.forEach(function(radio) {
radio.addEventListener('change', function() {
getTextArea.textContent = this.value //assign value to textArea
})
})
<form id="myForm">
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<br>
<br>
<textarea id="textarea-field" placeholder='Type your message here...' required>
</textarea>
</form>

If you give each of your input a class purely for this script below it should work.
<script>
// GIVE EACH OF YOUR INPUTS A CLASS OF .input
// THEN ADD THIS SCRIPT
$(document).ready(function(){
$('.input').click(function(e) {
var text = $( this ).val();
$('#textarea-field').val( text );
});
});
</script>

You can do it this way
const radios = document.querySelectorAll('input');
const textarea = document.querySelector('#textarea-field');
radios.forEach(radio => {
radio.addEventListener('change', ({
target
}) => textarea.innerHTML = target.value);
});
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<textarea id="textarea-field" placeholder='Type your message here...' required></textarea>
</form>

Add a Custom Class to input where you want to put Radio Button
The Code below Gets the Value of clicked input radio button and sets in the TextArea Field.
$('.radiobuttoninput').click(function() {
$('#textarea-field').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input class="radiobuttoninput" type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input class="radiobuttoninput" type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input class="radiobuttoninput" type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input class="radiobuttoninput" type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
<br>
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required> </textarea>
</form>

If you don't want to use any libraries then you can also use vanilla to do this. Nothing to explain here so I will just show you.
HTML file:
<form name="form">
<input type="radio" name="rate" value="1"/>i am 1
<input type="radio" name="rate" value="2"/>i am 2
<input type="radio" name="rate" value="3"/>i am 3
</form>
<textarea value="" id="ta"></textarea>
You don't need id for the form or radio boxes. Just declare a name. That would do the trick.
JavaScript file:
document.form.onclick = function() {
var v = document.form.rate.value;
var t = document.getElementById("ta");
t.value = v;
}
Let me know if it worked.

Related

Creating multiple HTML elements with JavaScript. Dynamic forms?

I'd like to insert a block of HTML into the DOM when a checkbox or radio button or button is pressed.
For example, when a button is pressed, then another set of the labels and inputs below are added to the form.
<form class="details">
<div>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<label for="job">Job:</label><br>
<input type="text" id="job" name="job"><br>
<label for="id">ID:</label><br>
<input type="text" id="id" name="id">
<label for="shoesize">Shoe size:</label><br>
<input type="text" id="shoesize" name="shoesize"><br>
<label for="helmetsize">Helmet size:</label><br>
<input type="text" id="helmetsize" name="helmetsize">
</div>
</form>
Every time a button is pressed I'd like another set of fields where someone else can add their details to the form.
I am aware of document.createElement(), but it seems like I can only create 1 element at a time using that. This form will probably grow and so would like something less verbose.
I've experimented with appendChild() e.g.
var details = document.getElementsByClassName('details')[0]
var newDetailsSection = '<div>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<label for="job">Job:</label><br>
<input type="text" id="job" name="job"><br>
<label for="id">ID:</label><br>
<input type="text" id="id" name="id">
<label for="shoesize">Shoe size:</label><br>
<input type="text" id="shoesize" name="shoesize"><br>
<label for="helmetsize">Helmet size:</label><br>
<input type="text" id="helmetsize" name="helmetsize">
</div>'
details.appendChild(newDetailsSection)
But I am getting an error because newDetailsSection is not of type Node - it is a string and I understand that.
I am new to web development.
Is this a use case for a JS framework that handles components? Is this what a component is?
if u want to add html string; innerHTML is your friend.
to append use details.innerHtML = details.innerHtML + newSectionHTML;
ofcourse i would recommend using document.createElement and create a function that returns element that contain label:
example:
function creatInput(name, label){
const labelElm = document.createElement('label');
const inputElm = document.createElement('input');
labelElm.setAttribute('for', name);
labelElm.innerText = label+':';
inputElm.setAttribute('name', name);
inputElm.setAttribute('id', name);
inputElm.setAttribute('placeholder', label);
labelElm.appendChild(input);
return labelElm;
}
this way you can reuse it for all your input simply call:
var details = document.querySelector(".details");
details.appendChild( createInput('fname','First name') );
details.appendChild( createInput('lname','Last name') );
/// .. etc

clear certain text using jquery

I face problem with reset value to empty with jquery when click radio button.
<form id="my-form">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" value="123" />
</div>
<div>
<label for="ID">ID NO</label>
<input type="text" id="ID" name="ID" value="NO21034" />
</div>
<fieldset>
<legend>Option</legend>
<label for="clearID">clearID</label> <input type="radio" id="clearID" name="opt" checked />
<label for="clearName">clearName</label> <input type="radio" id="clearName" name="opt" />
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$('#clearname').on('click', function()
{
$('#my-form').find('input:text').val('');
});
});
</script>
now if my radio button click clearName,it will automatic clear the value of name and id.
is it having another code can replace find('input:text') ?I want to clear either one value(name or id),not both.
Clear each field using corresponding id..
<script type="text/javascript">
$(document).ready(function()
{
$('#clearname').on('click', function()
{
$('#ID').val('');//it clears the value of element having id='ID'
$('#name').val('');//it clears the value of element having id='name'
});
});
</script>
use javascript reset method
$('#clearname').on('click', function()
{
$("#my-form")[0].reset()
// or
$("#my-form").get(0).reset()
});

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Hide/display of 3 textboxes on selection of radio button

I have 2 radio buttons. On selection of one I want to display 3 text boxes and hide it on selection of other.
Here is the code.
These are my 2 radio buttons.
<input type="radio" name="type"> Fresher
<input type="radio" name="type"> Experienced
On click of radio button experienced I want to display these 3 text box.
Company Name: <input type="text" hidden="true"/> <br/>
Designation: <input type="text" hidden="true"/> <br/>
Year_of_Experience: <input type="text" hidden="true"/> <br/>
Please help me out with javascript for this as new to it.
You could do this as follows. First change your HTML to this:
<input type="radio" name="type" value="Fresher"> Fresher
<input type="radio" name="type" value="Experienced"> Experienced
<div id="textboxes" style="display: none">
Company Name: <input type="text" hidden="true"/>
Designation: <input type="text" hidden="true"/>
Year_of_Experience: <input type="text" hidden="true"/>
</div>
What this code adds to your code is to have a value for the radio buttons. This allows us to make a selection based on which radio button was selected. Secondly, the input fields are grouped together in a <div> to allow for easy hiding of the three input fields. After you have modifief your HTML as such, include jQuery on your website and use this code:
$(function() {
$('input[name="type"]').on('click', function() {
if ($(this).val() == 'Experienced') {
$('#textboxes').show();
}
else {
$('#textboxes').hide();
}
});
});
You can see how this works using this JSFiddle: http://jsfiddle.net/pHsyj/
This is the best example.Try something like this.,this is a sort of example
$("input[type='radio']").change(function(){
if($(this).val()=="other")
{
$("#otherAnswer").show();
}
else
{
$("#otherAnswer").hide();
}
});
http://jsfiddle.net/Wc2GS/8/
I guess this would solve your probs
<input type="radio" name="type" id='frsradio'> Fresher
<input type="radio" name="type" id='expradio'> Experienced <br>
<input type="text" class='txbx' hidden="true"/> <br/>
<input type="text" class='txbx' hidden="true"/> <br/>
<input type="text" class='txbx' hidden="true"/> <br/>
$(function() {
$('#expradio').click(function() {
$('.txbx').attr('hidden',false);
});
$('#frsradio').click(function() {
$('.txbx').attr('hidden',true);
});
});
WORKING jsfiddle
See there is no unique identity available for your html elements, i just given this code by thinking in a generic manner.
Try,
$('input[name="type"]:eq(1)').change(function(){
$('input[type="text"]').toggle(this.checked);
});
<input type="radio" name="type" onClick ="radio"> Fresher
<input type="radio" name="type" onClick ="radio"> Experienced
on click of radio button experienced i want to display these 3 text box.
<input type="text" hidden="true" class="text"/> <br/>
<input type="text" hidden="true" class="text"/> <br/>
<input type="text" hidden="true" class="text"/> <br/>
and javascript:-
<script>
function radio()
{
var result = document.getElementsByClassName('text'").style.display="none";
}
</script>
Try this
<input type="radio" name="type" value="fresher"> Fresher
<input type="radio" name="type" value="exp"> Experienced
<br/>
<input class="box" type="text" hidden="true"/> <br/>
<input class="box" type="text" hidden="true"/> <br/>
<input class="box" type="text" hidden="true"/> <br/>
Script
$("input[type='radio']").on('change',function(){
if($(this).val() == "exp")
$('.box').show('slow');
else
$('.box').hide();
});
DEMO
Try this....
<input type="radio" name="type" id="fresh"> Fresher
<input type="radio" name="type" id="exp"> Experienced
<input type="text" class="hid" hidden="true"/> <br/>
<input type="text" class="hid" hidden="true"/> <br/>
<input type="text" class="hid" hidden="true"/> <br/>
$("#fresh").change(function(){
$('.hid').css("style","display:none");
});
$("#exp").change(function(){
$('.hid').css("style","display:block");
});
For default hide the text boxes In OnRender Complete Method you need hide the three textbox for that you put the below code.
$("#textbox 1").hide();
$("#textbox 2").hide();
$("#textbox 3").hide();
You need to write the code in Radio button on change.
Using the Id get the value of radio button
var val=$('#radioId').val;
if(val=='Fresher')
{
$("#textbox 1").show();
$("#textbox 2").show();
$("#textbox 3").show();
}
else if (val=='Experienced'){
$("#textbox 1").hide();
$("#textbox 2").hide();
$("#textbox 3").hide();
}

using innerHTML with <input>

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing.
javascript
function setName(ID){
document.getElementById('searchtitle').innerHTML = "Enter " + ID.innerHTML;
}
HTML
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)">Last Name</input><br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)">Phone Number</input><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
What is supposed to happen is depending on which radio button I pick the label for the input box should change. I can make the label.innerHTML=radio.value but the values are named for my php code and not formated nicely(ie. phonenumber vs. Phone Number) this is why I am trying to use the innerHTML of the radio button.
Any help I could get would be greatly appriciated.
you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>
JavaScript:
console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'
If you want the value of an input tag, you want to use .value.
First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.
<html>
<head>
<script>
function setName(el){
document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last
Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone
Number</label><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>
Complete edit.
Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).
<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
JavaScript (in Jquery, for brevity):
function setName(elem)
{
$('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}
You have closed the Input tag improperly with </input>
this should be
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

Categories

Resources