Pushing attribute value to two different arrays based on radio options selected - javascript

In short, if a user selects yes to a radio option, I'm trying to obtain the data-name attribute from that input and push it to an array called accepted_array.
If a user selects no, then store data-name to declined_array.
Here is a visual to the markup:
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Here are 2 approaches I've experimented with:
First approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var checkedVal = $this.val();
var accepted_array = [];
var declined_array = [];
if( checkedVal == "yes" ) {
var name = $this.data("name");
accepted_array.push(name);
} else {
declined_array.push(name);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + accepted_array.join(","));
});
});
}) (jQuery);
This only executes for the selected user and adds the name to both arrays.
Second approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var data = [];
var checked = $this.is(':checked');
var name = $this.attr('data-name');
if (checked) {
if (!data[name]) {
data[name] = []
}
data[name].push($this.val())
}
console.log(data);
});
});
}) (jQuery);
Which only adds the user to a single array.
If both select yes, I need both names in the accepted_array. If someone selects yes initially and then selects no I need to remove them from the accepted_array and vice versa.

You can use splice with inArray to remove value from array if someone selects yes initially and then selects no and vice versa.
Example:
var accepted_array = [];
var declined_array = [];
$('.guest__options-group > input[type=radio]').on('change', function() {
var $this = $(this);
var name = $this.data("name");
var checkedVal = $this.val();
var name = $this.data("name");
if (checkedVal == "yes") {
accepted_array.push(name);
declined_array.splice($.inArray(name, declined_array), 1);
} else {
declined_array.push(name);
accepted_array.splice($.inArray(name, accepted_array), 1);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + declined_array.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- options for John -->
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>

Related

How do i get the latest checked value of the checkbox?

I have the following code that would get the value of the checkbox, but not the one that is checked the latest, it get the last(?) value of the checkbox. I would like to get the value of the checkbox that is recently checked.
This is my html.
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="123456"
data-valuetwo="Mike"
id="customCheck32"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck32">Mike</label>
</div>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="6542321"
data-valuetwo="John"
id="customCheck33"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck33">John</label>
</div>
<div id="selecteditems" style="border: 1px solid black"></div>
<div class="itemhead"></div>
This is my script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(".chkbx").click(function() {
var selected = "";
var latestchoice = "";
$(".chkbx:checked").each(function() {
selected += $(this).attr("data-valuetwo") + "<br>";
latestchoice = $(this).attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
</script>
With the following code, if I check Mike first, then John, I could see the latest choice changing from Mike to John. However, if I selected John first and select Mike, the value of latest choice would not change to Mike. Thank you!
To do that, you'll have to remember when the checkboxes were checked. One way to do that is to use jQuery's data cache for elements, see comments:
$(".chkbx").click(function() {
var $this = $(this);
// If this checkbox is checked...
if (this.checked) {
// ...remember when
$this.data("checked", Date.now());
} else {
// Not checked, remove the data
$this.removeData("checked");
}
var selected = "";
var latestchoice = "";
// Get and sort the checked checkboxes
var checked = $(".chkbx:checked").get().sort(function(a, b) {
return $(a).data("checked") - $(b).data("checked");
});
// Loop through them in sorted order
checked.forEach(function(cb) {
var $cb = $(cb);
selected += $cb.attr("data-valuetwo") + "<br>";
latestchoice = $cb.attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
Live Example:
$(".chkbx").click(function() {
var $this = $(this);
// If this checkbox is checked...
if (this.checked) {
// ...remember when
$this.data("checked", Date.now());
} else {
// Not checked, remove the data
$this.removeData("checked");
}
var selected = "";
var latestchoice = "";
// Get and sort the checked checkboxes
var checked = $(".chkbx:checked").get().sort(function(a, b) {
return $(a).data("checked") - $(b).data("checked");
});
// Loop through them in sorted order
checked.forEach(function(cb) {
var $cb = $(cb);
selected += $cb.attr("data-valuetwo") + "<br>";
latestchoice = $cb.attr("data-valuetwo");
});
$("#selecteditems").html(selected);
if ($(".itemhead").is(":empty")) {
$(".itemhead").html(latestchoice);
} else {
$(".itemhead").empty();
$(".itemhead").html(latestchoice);
}
});
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="123456"
data-valuetwo="Mike"
id="customCheck32"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck32">Mike</label>
</div>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input chkbx"
value="6542321"
data-valuetwo="John"
id="customCheck33"
name="choice[]"
/>
<label class="custom-control-label" for="customCheck33">John</label>
</div>
<div id="selecteditems" style="border: 1px solid black"></div>
<div class="itemhead"></div>
This is my script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
That said, a list you can drag items around in might make for a better UX.

How to uncheck all when the other radial is picked

I create a js for my project. It almost work except that I need to uncheck all checkbox under first radial when second radial is picked.
JS
<script>
function habilitarSecciones(selected) {
var chk = $(selected);
var checked = chk.is(":checked");
var id = chk.val();
$("[id^='Grp2']").attr("disabled", true);
if (checked) {
$(".Grp2_" + id).removeAttr("disabled", false);
}
}
</script>
HTML
<div class="form-group">
<h3>Tipo</h3>
#foreach (Dominio.Tipo tipo in Model.Secciones.Select(x => x.Tipo).Distinct())
{
<label>
<input type="radio" value="#tipo.Id" name="Grp_Tipo" id='Grp_#tipo.Id' onclick="habilitarSecciones(this);" /> #tipo.Descrip
</label>
<hr />
foreach (var seccion in Model.Secciones.Where(x => x.Tipo == tipo))
{
<label>
<input type="checkbox" class="Grp2_#tipo.Id" value="#seccion.Id" name="SeccionesElegidas" id="Grp2_#seccion.Id" disabled /> #seccion.Descrip
</label>
}
<hr />
}
</div>
Please to try with $('element').prop('checked', false);

Checkbox arrays

Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>

Unique Ids to bind radio buttons to text areas?

I have a form with multiple yes/no radio buttons and text area I would like to disable ("grey out") when yes is selected and enable when no is selected.
What I have currently only works for the first text area, all other radio buttons only effect the first text area because they have matching ids.
This is my view I am using.
#for (int i = 0; i < Model.Questions.Count; i++)
{
<tr>
<td>
<div>
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, true, new { id = "radio" + i, #class = "class" + i, value = "yes", }) Yes
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id = "radio" + i, #class = "class" + i, value = "no" }) No
</div>
</td>
<td>
#Html.TextAreaFor(p => Model.Questions[i].ActionToTake, new { id = "text" + i })
</td>
</tr>
}
I know I will need to generate unique ids somehow for each pair of radio buttons and bind them to the text area somehow. This is the script I'm currently using.
$(document).ready(function() {
$(".class1").change(function (e) {
if ($(this).val() === 'True') {
$("#text1").prop('readonly', true);
$("#text1").css('background-color', '#EBEBE4');
} else if ($(this).val() === 'False') {
$("#text1").prop('readonly', false);
$("#text1").css('background-color', '#FFFFFF');
}
});
})
Whats a good way to approach this? I'm still new to javascript so any additional explanation for what you're doing would be helpful.
As I said in my comments, you do not need to have IDs unless you use them elsewhere. You can simply have a group, may be a DIV with a class and radio buttons and text area as the group children. Did you want something like this?
$(function() {
var $choices = $(".group").find(":radio");
$choices.on("change", function() {
var $this = $(this);
var choice = $.trim( $this.val() );
var tarea = $this.closest(".group").find("textarea");
tarea.prop("readOnly", choice === "yes");
if ( choice === "yes" ) {
//do your stuff when val = yes
} else {
//do your stuff when val = no
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group">
<input type="radio" name="choice1" value="yes" />Yes
<input type="radio" name="choice1" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice3" value="yes" />Yes
<input type="radio" name="choice3" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice4" value="yes" />Yes
<input type="radio" name="choice4" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>

Add the sum of from the value select of radiobutton

For instance, radiobutton one = value 1, radiobutton two = value 2.
Here is the code I have:
Script file:
<script type="text/javascript">
$(document).ready(function () {
$("div[data-role='footer']").prepend('Back');
$(".Next").click(function () {
$.mobile.changePage("#" + $("#Answer").val());
});
$("input[type=radio]").click(function () {
var answer = $(this).val();
$("#Answer").val(answer);
});
$('.Answer').live("click", function () {
var NextQuestionID = $(this).attr('NextQuestionId');
if (NextQuestionID == '') {
location.href = "/Surveys/Index";
}
$("#survey").load('/Questions/GetQuestion', { Id: NextQuestionID }, function () {
$('#answerInput').textinput();
$(".Answer").button();
});
});
});
and here is my markup:
<input type="radio" name="Answer" id="radio-choice-1" value="Question2" />
<input id="Answer" class="Answer" type="hidden" value="first" />
<div class="innerspacer">
Next
</div>
How do I assign the radio button as value from 1 to 4 and sum up the value for all the question?
There is a lot going on in your question and it is unclear what you want. I'm taking a guess and assuming you have a say 5 radio buttons and you want the 5th radio button value to be the sum of the other 4 values. Is that correct?
Here is an example of doing that: jsfiddle
HTML:
<div id="container">
<label>
<input type="radio" name="something" value="1">
A?
</label>
<label>
<input type="radio" name="something" value="3">
B?
</label>
<label>
<input type="radio" name="something" value="5">
C?
</label>
<label>
<input type="radio" name="something" value="">
All?
</label>
</div>
JavaScript:
$(document).ready(function() {
var choices = $('input[name="something"]');
var total = 0;
choices.each(function() {
var choice = $(this);
var value = parseInt(choice.val(), 10);
if (!isNaN(value)) {
total += value;
}
});
choices.filter(':last').val(total);
});
You will need to adapt this to your HTML.

Categories

Resources