Sync Selected Radio Button between 2 radio button groups - Opposites - javascript

I need to do something similar to JQuery Sync Selected Radio Button between 2 radio button groups.
I have 2 radio groups -
<input type="radio" name="radio_A" id="radio_A_1" value="1" />1st
<input type="radio" name="radio_A" id="radio_A_2" value="2" />2nd
<input type="radio" name="radio_B" id="radio_B_1" value="1" />1st
<input type="radio" name="radio_B" id="radio_B_2" value="2" />2nd
When radio_A_1 is checked, I need radio_B_2 synced/checked. The relationships would be-
radio_A_1=>radio_B_2
radio_A_2=>radio_B_1
radio_B_1=>radio_A_2
radio_B_2=>radio_A_1
Using the answer provided #8804502
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, but only when A changes-
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
So if I copy it, changing it if from A=>B to B=>A-
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]');
console.log(index);
$('input[name=radio_A]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, when either A or B changes -
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
radio_B_1=>radio_A_1
radio_B_2=>radio_A_2
How can I sync them 1=>2/2=>1, instead of 1=>1/2=>2? And can it be done with 1 block of code, instead of 2?

You need to add some code to take the index of the element just clicked and set it to 0 if it is 1, or 1 if it is 0. The first way that came to mind is as follows:
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]') === 1 ? 0 : 1;
$('input[name=radio_B]:eq(' + index + ')').attr('checked', 'checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]') === 1 ? 0 : 1;
$('input[name=radio_A]:eq(' + index + ')').attr('checked', 'checked');
});
Demo: http://jsfiddle.net/cTQeJ/1/
Though you could also try:
var index = 1 - $(this).index('input[name=radio_A]');
(Or the following demo uses kind of a fun hack if you like to make your code confusing: http://jsfiddle.net/cTQeJ/)
"And can it be done with 1 block of code, instead of 2?"
If you can modify the html slightly it is pretty easy with a single, short code block. Try a change like this:
<input type="radio" name="radio_A" data-sync="1" value="1" />1st
<input type="radio" name="radio_A" data-sync="2" value="2" />2nd
<input type="radio" name="radio_B" data-sync="2" value="1" />1st
<input type="radio" name="radio_B" data-sync="1" value="2" />2nd
I've added a data-sync attribute to each radio button (and removed the id attribute since it wasn't being used, but obviously you can leave that in if needed). Then you can write a simple function like this:
var $radios = $('input[data-sync]');
$radios.change(function() {
$radios.filter('[data-sync="' + $(this).attr('data-sync') + '"]')
.prop('checked', true);
});​
...that basically says whenever any of the radio buttons is checked, find all other radio buttons with a data-sync attribute of the same value and check them too.
Note that this will work with more than two groups, as shown in this demo: http://jsfiddle.net/cTQeJ/2/

Related

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

jquery checkbox with limit dinamis

I have following html:
<input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" id="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
jquery :
function ambil(x){
var limit = x.data('stok')
var cnt = $('#perlengkapans:checked').length
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)
}
}
I want to show a message as "you can maximum <variable_limit_value>", if the stock has reached the limit.
But it is not showing the message. Please help.
Change Input attribute - onchange="ambil((this))"
And your function to -
function ambil(x) {
limit = $(x).data('stok')
cnt = $('#perlengkapans:checked').length
if (cnt > parseInt(limit,10) ) {
$(x).prop('checked', '')
alert('you can maximum ' + limit)
}
}
Not sure, what you are achieving with you code.
But, depending upon your code, following are corrections:
1) In HTML DOM, there should be only one id for one element. In short id is a unique property. In your case, there were three elements with same id. Need to fix it.
2) Change id property to name and access the same. There can be multiple elements with same name.
Corrected Code:
<input type="checkbox" name="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" name="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" name="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
<script>
function ambil(x){
var limit = x.data('stok')
var cnt = $('[name=perlengkapans]:checked').length; // observe what is changed here.
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)}}
</script>
First of all, IDs should not be repeated and the logic seems to be wrong. Try something like below.
<input type="checkbox" id="perlengkapans1" name="perlengkapans" data-stok="1" value="name item 1" />
<input type="checkbox" id="perlengkapans2" name="perlengkapans" data-stok="4" value="name item 2" />
<input type="checkbox" id="perlengkapans3" name="perlengkapans" data-stok="0" value="name item 3" />
In js file add this
$("input[name='perlengkapans']").on("change", function(){
if($("input[name='perlengkapans']":checked").length > $(this).data('stok')) {
// Display Alert
}
});
});

unsetting bits in javascript producing wrong value

I have 4 checkboxes. If all 4 check boxes are pressed, I want to produce the Number 15, e.g. "0000 1111". If none of checkboxes are clicked, then it should produce 0, e.g. "0000 0000". In other words, when the checkbox is clicked, the associated bit should be set, else it should be unset. Each checkbox is raised by the power of 2 in order to target the next bit:
<input type="checkbox" name="validation_rules" id="inlineCheckbox1" value="1">
<input type="checkbox" name="validation_rules" id="inlineCheckbox2" value="2">
<input type="checkbox" name="validation_rules" id="inlineCheckbox4" value="4">
<input type="checkbox" name="validation_rules" id="inlineCheckbox8" value="8">
I have it working fine to set the bits:
Below is the relevant method:
listen_for_enabled_change: function(){
$form.on('click', 'input[name="validation_rules"]', function(){
var $hidden = $(this).closest('.field-border').find("input[type='hidden'][name='result']");
var new_val;
if($(this).get(0).checked) {
new_val = $hidden.val() | $(this).val();
} else {
var mask = 1 << $(this).val()/2;
new_val = $hidden.val() & ~mask;
}
$hidden.val(new_val);
})
}
Unfortunately, unsetting the bit is not working in the above code. For example, if the hidden input field value is 8. And then I uncheck the checkbox with value 8, it should produce 0. However, it doesn't change the value at all. It just returns the Number 8. What may I be doing wrong?
I think your problem is here:
var mask = 1 << $(this).val()/2;
new_val = $hidden.val() & ~mask;
The values are [1,2,4,8], which would result in rounded down integers of [0,1,2,4]. Yes thats a 4, should be a 3.
Why not tag the checkbox value as the bit index that needs setting instead?
<input type="checkbox" name="validation_rules" id="inlineCheckbox1" value="0">
<input type="checkbox" name="validation_rules" id="inlineCheckbox2" value="1">
<input type="checkbox" name="validation_rules" id="inlineCheckbox4" value="2">
<input type="checkbox" name="validation_rules" id="inlineCheckbox8" value="3">
Then you can just:
if($(this).get(0).checked) {
// flip on the bit at the bit index
new_val = $hidden.val() | (1 << $(this).val());
} else {
// flip off the bit at the bit index
new_val = $hidden.val() & ~(1 << $(this).val());
}
Or the whole thing, cleaned up a bit:
var $this = $(this);
var $hidden = $("#result");
var newVal = $hidden.val();
var bit = $this.val()
if (this.checked) {
newVal = newVal | (1 << bit);
} else {
newVal = newVal & ~(1 << bit);
}
$hidden.val(newVal);
Working example: https://jsfiddle.net/zjg2gbp3/3/
It seems to me that all that bit masking and shifting based on which checkbox was just checked is unnecessarily complicated (premature optimization?), and that instead of manipulating the current $hidden value based on the checkbox that was just checked, you'd get far more readable / less error prone code by simply totalling the value each time any of the checkboxes change:
$form.on('change', 'input[name="validation_rules"]', function () { // 'change' is more robust than 'click' here
var new_val = 0;
$('input[name="validation_rules"]').each(function(i, elem) {
if (elem.checked) {
new_val += parseInt(elem.value, 10);
}
});
$hidden.val(new_val);
})
I must be missing something but...simple serialise will do:
you can just pass a collection of elements into a function that will add up your bitmasks.
var getBitmask = function(els){
return Array.prototype.reduce.call(Array.prototype.filter.call(els, function(el){
return el.checked;
}), function(a, b){
return {value: ~~a.value + ~~b.value};
}).value;
};
console.log(getBitmask(document.querySelectorAll('input[type=checkbox]')));
above works without jQuery.
you can build your bitmasks automatically around the element index as well.

javascript modify variable

I have this:
var category = "3%2C16%2C6%2C10%2C1%2C19";
in witch category id are 3 16 6 10 1 19 and the %2C is the space between category.
What i want is here:
if (document.getElementById("3").checked = false) {
category = "16%2C6%2C10%2C1%2C19";
}
else {
category = "3%2C16%2C6%2C10%2C1%2C19";
}
I want to make this for all the checkbox that i have, but you can't deselect all the checkbox because the servers don't send you back any data.
This is for filtering the results
It would be easier to use an array, then convert it to this string representation, when needed.
var categories = [];
$('#category-form input').change(function () {
var id = $(this).attr('data-id'),
index = categories.indexOf(id);
if (this.checked && index === -1) {
categories.push(id);
} else if (!this.checked && index !== -1) {
categories.splice(index, 1);
}
});
You can see my working code in this fiddle.
(with multiple checkboxes, string representation, and at least one check)
Try
if (document.getElementById("3").checked === false) {
notice the extra double equals to do a typesafe check
or better still
if (!document.getElementById("3").checked) {
However, as you're using jQuery and you appear to be munging a string together from checked states, which is going to be really brittle with hardcoded strings so maybe something like:
var category = "";
$( "input:checked" ).each(function() {
category = $(this).id + "%2C";
};
Only calling that when you need the output e.g. button press.
As you are using jquery, you can listen to the change event for the checkboxes, then build the list each time one is checked or unchecked. To store the values you can either use the value attribute for the checkbox or add data- attributes.
Getting an array of values and joining them will avoid the trailing %2C.
var category = '';
(function($) {
// cache collection of checkboxes
var cboxes = $('input[type=checkbox]');
cboxes.on('change', function() {
// find the ticked boxes only, and make an array of their category values, then join the values by a space
category = $.makeArray(cboxes.filter(':checked').map(function() {
return $(this).data('category');
//return $(this).val(); // if you store them in value="3"
})).join('%2C');
// output for debug purpose
$('#categoryOutput').html("'" + category + "'");
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="c1" data-category="3" />
<input type="checkbox" id="c2" data-category="16" />
<input type="checkbox" id="c3" data-category="6" />
<input type="checkbox" id="c4" data-category="10" />
<input type="checkbox" id="c5" data-category="1" />
<input type="checkbox" id="c6" data-category="19" />
</form>
<div id="categoryOutput"></div>
Side Note: try to avoid starting element ids with numbers - it is technically invalid and can break things in some scenarios.

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

Categories

Resources