Get values of selected checkboxes and their associated textareas in Javascript - javascript

I have a HTML form. In this form I have 5 checkboxes and each checkbox has an associated textarea.
So I want to get the values of only the checked checkboxes and their associated textarea text. I am able to get the values of the checked checkboxes but I can't figure out a way to get the values of their associated textarea.
My HTML code is:
<form class="my-form" id="id_MyForm">
<div class="form-group">
<label class="qquestion">6. Which of the following is most relevant to you and why? (Select all that apply).</label>
<div class="checkbox" id="id_Question6">
<label>
<input type="checkbox" id="input_que6a" value="Time" name="question6" />Time
</label>
<textarea name="question6a_textarea" id="id_que6a" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6b" value="Money" name="question6" /> Money
</label>
<textarea name="question6b_textarea" id="id_que6b" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6c" value="Family" name="question6" /> Family
</label>
<textarea name="question6c_textarea" id="id_que6c" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" id="input_que6d" value="Hobbies" name="question6" /> Hobbies
</label>
<textarea name="question6d_textarea" id="id_que6d" class="form-control" placeholder="Please provide the reason"></textarea>
<br>
<label>
<input type="checkbox" value="Other" name="question6" id="other_que6" /> Other
</label>
<br>
<textarea name="question6_textarea" id="id_Question6_textinput" class="form-control" placeholder="Please elaborate"></textarea>
</div>
</div>
<div class="text-center">
<button type="button" id="id_SubmitForm" class="btn btn-success">Submit</button>
</div>
</form>
My JavaScript code is:
/* Latest compiled and minified JavaScript included as External Resource */
var question6AnsArray = [];
/* To hide all the text areas when the page loads */
$("#id_Question6_textinput").hide();
$("#id_q6_opH_textarea").hide();
$('#id_que6a').hide();
$('#id_que6b').hide();
$('#id_que6c').hide();
$('#id_que6d').hide();
/* To show appropriate text area for selected check box */
$('#input_que6a').click(function() {
$("#id_que6a").fadeToggle(this.checked);
});
$('#input_que6b').click(function() {
$("#id_que6b").fadeToggle(this.checked);
});
$('#input_que6c').click(function() {
$("#id_que6c").fadeToggle(this.checked);
});
$('#input_que6d').click(function() {
$("#id_que6d").fadeToggle(this.checked);
});
$('#other_que6').click(function() {
$("#id_Question6_textinput").fadeToggle(this.checked);
});
$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
//Here I want to get the value for the textarea.
});
var question6Answer = question6AnsArray.join(", ");
alert(question6Answer);
});
Here is a link to JSFiddle

$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsOtherArray.push($(this).closest("label").next("textarea").val());
});
var question6Answer = question6AnsArray.join(", ");
var question6OtherAnswer = question6AnsOtherArray.join(", ");
alert(question6Answer);
alert(question6OtherAnswer);
});
And, You could actually optimize your code this way a little bit too..
/* Latest compiled and minified JavaScript included as External Resource */
var question6AnsArray = [];
var question6AnsOtherArray = [];
/* To hide all the text areas when the page loads */
$("#id_Question6_textinput").hide();
$("#id_MyForm textarea").hide();
/* To show appropriate text area for selected check box */
$("input[type=checkbox]").click(function() {
$(this).closest("label").next("textarea").fadeToggle();
})
$('#other_que6').click(function() {
$("#id_Question6_textinput").fadeToggle(this.checked);
});
$("#id_SubmitForm").click(function() {
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsOtherArray.push($(this).closest("label").next("textarea").val());
});
var question6Answer = question6AnsArray.join(", ");
var question6OtherAnswer = question6AnsOtherArray.join(", ");
alert(question6Answer);
alert(question6OtherAnswer);
});

from your this context step back up to your parent then grab the next text element.
$('input[type="checkbox"]').on('click', function() {
if ( $(this, ':checked') ) {
$(this).val();
$(this).parent().next('textarea').val();
)
}

Try below function at last:
$("#id_SubmitForm").click(function() {
question6AnsArray = [];
// To get all the selected checkbox values and their associated textareas
$('input[name="question6"]:checked').each(function() {
question6AnsArray.push(this.value);
question6AnsArray.push($('.form-control').val());
//Here I want to get the value for the textarea.
});
var question6Answer = question6AnsArray.join(", ");
alert(question6Answer);
});

Related

Convert a checkbox value into a live url when checked

I am creating a form where the visitor chooses items they wish to see by clicking relevant checkboxes.
At this time I have the url's of the items as the value of the checkbox and these appear when clicking a Request button.
I would like the url that appears to be live (a href etc), so they just need to click on the link as opposed to copying and pasting into a browser address.
If possible I would like to have the checkbox value to be the item, which then converts to the url onClick. This is so that a right click will not show the url which will be in a separate java file.
This is not urgent, but eventually the results will be imported into a csv/excel file at the site as opposed to sending the results as an email.
Any help would be greatly appreciated.
function displayResult() {
var se = document.getElementById("myEmailList"),
send = document.getElementById("send"),
x = document.getElementById("mySelect"),
l = [],
list = x.querySelectorAll(":checked");
for (i = 0; i < list.length; i++) {
l.push(list[i].value);
var fn = document.getElementById('item_1').value;
document.getElementById('links').value = 'https://example.com';
var fn = document.getElementById('item_2').value;
document.getElementById('links').value = 'https://bbc.co.uk';
var fn = document.getElementById('item_3').value;
document.getElementById('links').value = 'https://google.com';
var fn = document.getElementById('item_4').value;
document.getElementById('links').value = 'https://itv.com';
}
send.href = "mailto:" + l.join(", <br>");
se.innerHTML = l.join(", <br>");
}
<form>
Select items required:
<fieldset id="mySelect">
<input type="checkbox" id="item_1" name="item_1" value="item_1">
Item 1 <br>
<input type="checkbox" id="item_2" name="item_2" value="item_2">
Item 2 <br>
<input type="checkbox" id="item_3" name="item_3" value="item_3">
Item 3 <br>
<input type="checkbox" id="item_4" name="item_4" value="item_4">
Item 4 <br>
</fieldset>
<button type="button" onClick="displayResult()">Request</button>
<a id="send" href="mailto:">Send email</a>
<div id="myEmailList">
<br><br>
<textarea id="links" style="width:300px; "type="text" rows="4"></textarea>
So, you want the form to send the user to the relevant places?
<form>Select your place:
<fieldset id="mySelect">
<input type="checkbox" value="https://www.bbc.co.uk">Item 1
<br>
<input type="checkbox" value="https://google.com">Item 2
<br>
<input type="checkbox" value="email3#domain.com">Item 3
<br>
<input type="checkbox" value="email4#domain.com">Item 4
<br>
</fieldset>
...
</form>

How can I get the source code of a specific div on radio oncheck?

I'd like to get the source code of a div, so example if a div contains some tags I'd like to get them as they are in html format and update it on a textfield.
JsFiddle : https://jsfiddle.net/Lindow/g1sp1ms3/2/
HTML :
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<br><hr><br>
<label class="tp_box_2">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
JavaScript :
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the specific div children of $this
var selected_layout = $(this).find('.selected_layout');
// get source code of what's inside the selected_layout
/* example :
<h3>box_two</h3>
<p>2</p>
and put it in someVariable.
*/
// and put in into textarea (all this need to happens when a radio is changed with the source code of the checked div)
var someVariable = ...
$('textarea').val(someVariable);
}
});
How can I achieve this ? How can I get the source code inside a specific div ?
First, you don't want selected_layout to be equal to: $(this).find('.selected_layout') because this already points to that element. You want it to point to the next element that comes after it.
I think this is what you are looking for:
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the index within the set of radio buttons for the radio button that was clicked
var idx = $("[type=radio][class=selected_layout]").index(this);
// Get the div structure that corresponds to the same index
var test = $("[class^='box_']")[idx];
// Now, just make that the value of the textarea
$('textarea').val(test.innerHTML);
}
});
textarea { width:100%; height:75px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" id="sl1" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<label class="tp_box_2">
<input type="radio" name="selected_layout" id="sl2" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
Create div element with:
Template inside
class or id for identifying
Set inputs' value to desired template class/id, then on input change find the template element base on input's value and extract the innerHTML of it by using jQuery's .html() method. Then put this HTML as an new value of textarea using also the.html() method on textarea element.
HTML:
<div id="template1" style="display:none;">
<h1>Hi!</h1>
</div>
<input type="radio" onchange="findTemplate(event)" value="template1" />
<textarea class="texta"></textarea>
jQuery:
var findTemplate = function(event) {
var target = $(event.target);
var templateName = target.val();
var template = $("#"+templateName);
var template = template.html();
var textarea = $(".texta");
textarea.html(template);
};
Working fiddle: https://jsfiddle.net/rsvvx6da/1/

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

Jquery get value of text box next to a radio button

I am creating a form with multiple radio buttons and text boxes.
Each Text box is next to radio button like below:
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="correct_answer_id">
Correct
</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required>
</div>
</div>
There are several radio button and text box pair like above in the form.
On click of the radio button, i want to get whatever has been written in the corresponding text box
i am trying to use Jquery's next() function like below:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).next('input[type="text"]').val());
}
});
But my log shows undefined. What i am doing wrong?
Try this : find parent div of radio and do next().next() to get input box div and then find input box to get value.
NOTE - You need not to check if ($(this).is(':checked')) as when you click on radio button it will get checked always.
$('input[type="radio"]').click(function(){
var value = $(this).closest('.radio').next().next('.col-sm-10').find('input[type=text]').val();
console.log(value );
});
use below code using parents(); see working fiddle
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parents('div.radio').next().next('div.col-sm-10').find('input[type="text"]').val());
}
});
You should put the value that you want submitted in the value attribute of your input elements.
e.g. <input type="radio" name="correct_answer_id" value="correct">
Your click handler would change to:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).val());
}
});
If there's some value that you don't want to place in the value attribute then it's still best to have a reference to the value in the input element instead of relying on a particular document layout.
Try this
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parent().parent().siblings().find('input[type="text"]').val());
}
});
Working Demo
If you can change the html a little, here is a different approach http://jsfiddle.net/xa9cjLd9/1/
<div class="form-group">
<div class="radio">
<label data-for='answer[]'>
<input type="radio" name="correct_answer_id" />Correct</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required />
</div>
</div>
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
var data = $(this).closest('label').attr('data-for');
console.log($('input[name=' + '"' + data + '"' + ']').val());
}
});
Just Define a data attribute to the label , which contains the name of the related input.

How to show jquery dialog with radio buttons when checkbox is checked and post value in textbox

I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)

Categories