Javascript not updating hidden field correctly - javascript

The Javascript code below should update the value of a hidden field which has the ID=adjustChk to 'y' if any of the radio buttons are selected as Yes.
It updates the field as expected, but if any of the radios are changed back to 'n' the hidden field is also updated to 'n'. Hoped the break would exit the for loop when a 'y' was encountered, but this doesn't behave the way I'd hoped.
window.onload = function() {
var ele = document.getElementsByTagName("input");
var hid = document.getElementById("adjustChk");
var chkItm = "";
for(var i = 0, item; item = ele[i]; i++){
item.addEventListener("click", function() {
chkItm = this.value;
for (var i = 0; i < ele.length; i++){
if(chkItm === 'y'){
hid.value = 'y';
break;
} else {
hid.value = 'n';
}
};
});
};
};
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="hidden" value="n" />
I'm still getting the hang of JS, so if there is also a better way using plain Jasvascript it would be helpful to see it!

The problem is that you're looking at the value of the radio button that was clicked, but what you really want is to look at the checked state of all of the "yes" radio buttons instead.
I'd probably get a true array of elements (using the slice trick described in the "array-like" part of this answer), use Array#forEach to hook up the handler (but the for loop is fine too), and when processing a click, use Array#some to get a flag for whether any of the buttons that's checked has value "y".
Here's an example, see the comments; I made the hidden field visible so it was easy to see its value at any given time:
// Get the radio buttons, convert the NodeList into a true array
var ele = Array.prototype.slice.call(document.getElementsByTagName("input"));
// Get the hidden field
var hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
ele.forEach(function(el) {
el.addEventListener("click", radioHandler, false);
});
function radioHandler() {
// Set `hid.value` to "y" if any of the checked checkboxes have the value "y",
// "n" otherwise
hid.value = ele.some(function(el) {
return el.checked && el.value === "y";
}) ? "y" : "n";
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />
But, here's a version using for loops instead:
// Get the radio buttons
var ele = document.getElementsByTagName("input");
// Get the hidden field
var hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
for (var i = 0; i < ele.length; ++i) {
ele[i].addEventListener("click", radioHandler, false);
}
function radioHandler() {
// Assume no "yes" radio buttons are checked
hid.value = "n";
for (var i = 0; i < ele.length; ++i) {
// Get the radio button for this loop iteration
var el = ele[i];
// If it's checked and has value "y", update the value and we're done
if (el.checked && el.value === "y") {
hid.value = "y";
break;
}
}
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />
Just for fun, here's that first example using ES2015 (aka "ES6"):
// Get the radio buttons as a true array
let ele = Array.from(document.getElementsByTagName("input"));
// Get the hidden field
let hid = document.getElementById("adjustChk");
// Attach a handler to all of our radio buttons
ele.forEach(el => {
el.addEventListener("click", radioHandler, false);
});
function radioHandler() {
// Set `hid.value` to "y" if any of the checked checkboxes have the value "y",
// "n" otherwise
hid.value = ele.some(el => el.checked && el.value === "y") ? "y" : "n";
}
<div>
Yes<input type="radio" name="radio1" value="y" />
No<input type="radio" name="radio1" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio2" value="y" />
No<input type="radio" name="radio2" value="n" checked="checked" />
</div>
<div>
Yes<input type="radio" name="radio3" value="y" />
No<input type="radio" name="radio3" value="n" checked="checked" />
</div>
<input id="adjustChk" type="text" value="n" />

Related

Radio button second click makes uncheck

If my radio button previously checked and i try to uncheck with second click i have to click once more. So it means if my radio button previously checked i got to clicked 2 times for unchecked but it should works with only 1 click . How can i fix it. Here is 2 codes they both have the same issue. I show both scripts here .Thanks For Helping!
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
$("input:radio").on("click", function (e) {
var inp = $(this);
if (inp.is(".clicked")) {
inp.prop("checked", false).removeClass("clicked");
} else {
$("input:radio[name='" + inp.prop("name") + "'].clicked").removeClass("clicked");
inp.addClass("clicked");
}
});
<input type="radio" name="rad" id="Radio0" checked="checked"/>
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />
and here is my html and jsfiddle
http://jsfiddle.net/fbyg1htz/
http://jsfiddle.net/7g684219/
The input element which is selected by default (checked="checked") should have the waschecked data attribute set to true because it's already checked.
<input type="radio" name="rad" id="Radio0" data-waschecked="true" checked="checked"/>
And the same for the second example. You should add class="clicked" to the element that is initially checked.
<input type="radio" name="rad" id="Radio0" class="clicked" checked="checked"/>
Updated fiddles:
http://jsfiddle.net/6fqLexbr/
http://jsfiddle.net/rmuh1sz3/
Example with razor for your first script:
<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
data-waschecked="#Model.OrderFilter.ActiveOrPassive.ToString().ToLower()" />
and for your second script:
<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
class="#(Model.OrderFilter.ActiveOrPassive ? "clicked" : null)" />

How to double click on radiobutton to uncheck instead of one click

I'm using 2 groups of radio buttons lets call it 1.1 1.2 and 2.1 2.1 (one radio button of the second group is always checked, depending on which one of the first group is checked, the other one is hidden).
I can't understand why I need to make a double click on the radio button to uncheck it when both radio buttons are checked. I want to click just one time to "uncheck" it.
function show() {
swich();
}
function swich() {
$('input[type="radio"]').change(function(){
$('[data-group="' + $(this).data('group') + '"]').prop('checked', this.checked);
});
}
var checkedradio = false;
var radioState = [];
$("input[type=radio]").on('click', function(e) {
if (radioState[this.name] === this) {
this.checked = false;
radioState[this.name] = null;
} else {
radioState[this.name] = this;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-group="A" id="radio1" required type="radio" value="Yes" name="group1">
<input data-group="B" id="radio2" required type="radio" value="No" name="group1">
<div id="someId1">
<input data-group="A" id="radio3" type="radio" name="group2" value="Yes" onclick="show()">
</div>
<div id="someId2">
<input data-group="B" id="radio4" type="radio" name="group2" value="No" onclick="show()">
</div>
CAVEAT
We do not recommend you take this approach as it breaks the standard UX for radio buttons.
Your issue is because you re-use checkedradio for both checks.
So:
click group A.1 - sets checkedradio = A.1
click group A.1 again, works ok and unchecks
click group A.1 - sets checkedradio = A.1
click group B.1 - sets checkedradio = B.1
click group A.1 (checked) - it's not A.1, so doesn't appear to work, set checkedradio = A.1
click group A.1 2nd time, works ok
You need a different variable for each group.
As multiple variables become very messy very quickly (and lots of DRY), you can use an array:
var radioState = [];
$(":radio").on('click', function(e) {
//console.log(radioState[this.name])
if (radioState[this.name] === this) {
this.checked = false;
radioState[this.name] = null;
} else {
radioState[this.name] = this;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required type="radio" value="Yes" name="group1">
<input required type="radio" value="No" name="group1">
<hr/>
<input type="radio" name="group2" value="Yes">
<input type="radio" name="group2" value="No">
Code based on this answer expanded to use an array.
I was able to achieve the desired result based on this code.
function show() {
swich();
}
function swich() {
$('input[type="radio"]').change(function(){
$('[data-group="' + $(this).data('group') + '"]').prop('checked', this.checked);
});
}
function toggleRadio(event)
{
if(event.target.type === 'radio' && event.target.checked === true)
{
setTimeout(()=>{ event.target.checked = false; },0);
}
}
document.addEventListener('mouseup', toggleRadio);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-group="A" id="radio1" required type="radio" value="Yes" name="group1">
<input data-group="B" id="radio2" required type="radio" value="No" name="group1">
<div id="someId1">
<input data-group="A" id="radio3" type="radio" name="group2" value="Yes" onclick="show(this)">
</div>
<div id="someId2">
<input data-group="B" id="radio4" type="radio" name="group2" value="No" onclick="show(this)">
</div>

Generated form not liking javascript change field value function

I was previously helped to get a javscript function using jquery working - see :
JS Fiddle working example
$("[name='COLUMN35']").on('change', function() {
var val = $(this).val();
var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
$("input[value='" + reverseVal + "']:not([name='COLUMN35'])").prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Option 1</span><br />
<form>
<label><input type="radio" name="option1" id="option1Yes" value="Yes">Yes</label>
<label><input type="radio" name="option1" id="option1No" value="No">No</label>
<br /><br />
<span>Option 2</span><br />
<label><input type="radio" name="option2" id="option2Yes" value="Yes">Yes
</label>
<label><input type="radio" name="option2" id="option2No" value="No">No</label>
<hr />
<span>Unsubscribe from all</span><br />
<label><input type="radio" name="COLUMN35" id="unsubYes" value="Yes">Yes</label>
<label><input type="radio" name="COLUMN35" id="unsubNo" value="No">No</label>
<br /><br />
<input type="submit" value="submit">
</form>
Upon implmenting that same code into the generated form page i am not sure why it does not work - see:
Webform with code not working
Unfortunately I am not able to edit the any of the form elements as they are generated automatically but hoping someone might have a different idea to implement - usually the messier the better E.G target the relevant ids to change and maybe not using jquery
try putting your code in $(document).ready(function(){})
eg
$(document).ready(function(){
$("[name='COLUMN35']").on('change', function(){
var val = $(this).val();
var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
$("input[value='"+reverseVal+"']:not([name='COLUMN35'])").prop('checked', true);
});
});

check all checkboxes javascript

I'm trying to have all checkboxes checked (true) when the user clicks on "All" button. I tried this, firstly just to see if "Anglais" could be checked clicking on "All" :
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous
My Javascript :
function checkedAll () {
var checked = false;
var all = document.getElementById('all');
if (checked == false) {
checked = true
}
else {
checked = false
}
var ang = document.getElementById('anglais').checked
if (ang == true) {
ang.checked = true;
}
But the button(s) are not checked when I click on All. I think I don't understand exactly how to use the .checked method..
Maybe, some of my code has not logic, because it was from this example :
https://www.hscripts.com/scripts/JavaScript/select-all-checkbox.php
Couple modifications:
Pass in the all checkbox to the checkedAll method (this allows you to reference it without having to re-find it).
Used document.getElementsByTagName to find the other checkboxes, but you could just as easily use document.getElementById for each one (anglais, allemand, etc.)
Set every other checkbox's checked status to the all.checked value. No need for a true/false comparison.
function checkedAll(allCheckbox){
var allCheckboxes = document.getElementsByTagName('input');
for (var i = 0; i < allCheckboxes.length; i++){
var curCheckbox = allCheckboxes[i];
if (curCheckbox.id != 'all'){
curCheckbox.checked = allCheckbox.checked;
}
}
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll(this)" name="all" id="all" value="Tous" /> Tous
The more explicit way would be:
function checkedAll(){
var isAllChecked = document.getElementById('all').checked;
// Set the other checkboxes .checked property based on the
// .checked status of the `all` checkbox
document.getElementById('anglais').checked = isAllChecked;
document.getElementById('allemand').checked = isAllChecked;
document.getElementById('espagnol').checked = isAllChecked;
document.getElementById('francais').checked = isAllChecked;
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous

Accessing the radio button value

Html Code: -
<input type="radio" name="radio" id="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate()"> For Users</input>
</p>
And JavaScript Code : -
function validate()
{
var btn_value=document.getElementById("radio").value;
if(btn_value==true)
{
alert(btn_value);
}
}
Now, whenever I am trying to print the value of radio button. It is always printing value as 1.
So, Now I don't understand what exactly am I missing here...
Thanx in advance for your help.
Elements ID should be unique. I modified your HTML and JS part and check below
Try this
HTML
<p>
<input type="radio" name="radio" id="radio1" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio2" value="2" onclick="validate(this)"> For Users</input>
</p>
JavaScrpit
function validate(obj)
{
var btn_value=obj.value;
if(btn_value==true)
{
alert(btn_value);
}
}
first of all never use a DOMID twice in your html!
remove them.... only use dublicated names!
<input type="radio" name="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" value="2" onclick="validate()"> For Users</input>
</p>
with the js check every element with the name attribute!
function validate() {
var elements = document.getElementsByName("radio");
for(var n = 0; n < elements.length; n++) {
if(elements[n].checked === true) {
alert(elements[n].value);
}
}
}
if you use your validate method ONLY in the onclick you can pass the domelement in the validate methode like this:
<input type="radio" name="radio" value="1" onclick="validate(this)"> For Yourself</input> </p>
and your js:
function validate(domElement) {
if(domElement.checked === true) {
alert(elements[n].value);
}
}
try this
<input type="radio" name="radio" id="radio" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate(this)"> For Users</input>
</p>​
function validate(ele)
{
alert(ele.value);
}​
IDs MUST be unique, it's a mistake to give it the same id.
You can give the IDs a running number (- radio1,radio2 etc) and loop through them to check which one was selected.

Categories

Resources