I have these two radio buttons and I am checking to see if one of them is checked with the below javascript. As I type this question I realize that my script only checks if a specific radio button is checked. How can I check to verify that one of the two are checked?
jQuery(".GenderM1").each(function() {
var isChecked = jQuery(this).prop('checked');
if (isChecked == false) {
e.preventDefault();
pass = "false";
alert("Please select gender.");
return false;
}
});
<td>
<input type="radio" name="persinfo_gender[0]" <?php if($row_c->persinfo_gender == "0") echo "checked";?> id="maleradio" class="GenderM1" value="0" required>M
<br>
<input type="radio" name="persinfo_gender[0]" <?php if($row_c->persinfo_gender == "1") echo "checked";?> id="female_redio" class="GenderM1" value="1" required>F
</td>
Your code
jQuery(".GenderM1").each(function() {
var isChecked = jQuery(this).prop('checked');
if (isChecked == false) {
e.preventDefault();
pass = "false";
alert("Please select gender.");
return false;
}
});
You're comparing a boolean variable against a boolean value, use it directly:
isChecked == false// Use !isChecked
^
You're using an undeclared e, probably you thin that .each receives an event.
e.preventDefault();
^
The main problem is your loop comparing each radiobutton.checked attribute, you need to check is at least one of then is checked to stop your loop.
This code snippet show how to check if a radiobutton was checked:
var isChecked = false;
jQuery(".GenderM1").each(function() {
isChecked = isChecked || jQuery(this).is(':checked');
if (isChecked)
return false;
});
if (!isChecked) {
var pass = "false";
alert("Please select gender.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="persinfo_gender[0]" class="GenderM1" value="0" required>M
<br>
<input type="radio" name="persinfo_gender[0]" checked class="GenderM1" value="1" required>F
See?, the alert is not being shown when a radiobutton is checked.
Now, the best approach to know whether a radiobutton group has at least one of them checked:
$('.GenderM1:checked').length
The line above returns how many radiobuttons are checked (1 or 0) because you only can select one of then. That selector works with checkboxes as well.
the method .prop() is available since jQuery 1.6, in previous versions you have to use the method .attr()
which version do you use?
Still I think that what you want to do is that if you have not selected a genre that shows an error and with the code you have, it will not work well. To do this you must do the following:
1- Mark one of them selected by default, that is, establish it as checked by default, this eliminates the possibility that the error of not marking it will be committed.
2- Modify the validation you perform, otherwise it will always return false because only one will be selected and you will go through the entire radiobuttons arrangement, so that when you reach the unselected radiobuttons it will return false.
if ($('input[class="GenderM1"]').is(':checked')) {
// do something;
} else {
//do another thing;
}
Related
if (this.checked != true) {
this.checked = true;
}
else {
this.checked = false;
}
Above code enables Check up All and Check out All function. However, I found that if any of check box is reversely checked by user, every output reverses.
How should I change in order to acheive followings when button is clicked?
Check Up All box (Acheive)
check Up any box that isn't checked (Problem)
Check Out every box when all boxes are checked (Acheive)
Belows is the full code:
function display() {
$.ajax({
url: "test.php",
type: "get",
data: {
a: $('#selectest option:selected').val()
}
}).done(function(data) {
$('#result').text(data);
alert("Checking test");
$('input:checkbox[class='+data+']').each(function() {
if(this.checked != true){
this.checked = true;
}
else{
this.checked = false;
}
});
});
}
Was the user name Undefined actually available, or did you find a glitch in the matrix?
Your question contradicts your code. This answer is for your question. Your code appears to be setting checkbox states from an ajax call, which is something entirely different.
Since you're using jQuery, you can use the :checked selector. Then you can just check if the number of checked checkboxes is equal to the total number of checkboxes, and toggle .prop('checked') accordingly.
In this snippet, if all checkboxes are checked, all checkboxes will be unchecked (item 3). If not all checkboxes are checked, all checkboxes will be checked (item 1 and 2).
$('button').on('click', function() {
$('input[type="checkbox"]').prop('checked',
$('input[type="checkbox"]:checked').length !==
$('input[type="checkbox"]').length
);
});
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button>toggle</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a simple HTML form with two inputs. One is a radio input and the other is a numeric input.
Using a Javascript function, if the radio option is selected as Insurance - YES(1), then the script must force a numeric value input on the Insurance Value ins_value input. If the radio input is selected as NO, then no input to be entered in the text input.
I have tried to find a similar example but have only found simple examples where an alert is triggered.
I am learning Javascript and have been through tutorials - but also no similar examples.
<script>
function INSURANCE() {
var insurance = document.forms["RegForm"]["optradio"];
var ins_value = document.forms["RegForm"]["ins_value"];
if (insurance.value == 0) {
"";
return false;
} else {
if (ins_value.value == "") {
window.alert("Please insert Insurance value.");
ins_value.focus();
return false;
}
return true;
}
</script>
I expect once the form is submitted, it should either force an insurance value input or not, based on the radio input selection.
First of all, you need a checkbox for you're use case. Radio buttons force a selection of one in many. You only have a "is numeric" flag meaning you're value is either true or false.
Well I guess you can achieve you're goal by changing you're input type according to user selection:
<input id="optcheckbox" type="checkbox" onclick="HandleCheckboxClick();" />
<input id="ins_value" type="text" onclick="HandleCheckboxClick();" />
<script>
function HandleCheckboxClick() {
var type = 'text';
var checkbox = document.getElementById('optcheckbox');
if(checkbox.checked) {
type = 'number';
}
document.getElementById('ins_value').type = type;
}
</script>
I hope that helps.
Best regards
Only seeing the Javascript it's difficult to figure out what's going on, including the HTML would help a lot. Also, this question is a big vague which is makes it hard to answer.
First, when are you trying to trigger the forcing the numeric value? When the user clicks on the radio button? If so, then call that function on the change event. If you're going to change it on the submit, then put the code in the submit function.
I recommend building an array of numeric values and matching that up with the 0, 1, 2, ... values of the radio buttons. When you set the text input, plug that value into your numeric array.
Here's a JS fiddle of using an array in conjunction with the radio button values.
https://jsfiddle.net/Chris_Hayes/coxta1bw/1/
var form = document.querySelector("form");
var numbers = [30, 20, 80];
form.addEventListener("submit", function(event) {
form["textinput"].value = numbers[form["contact"].value]
event.preventDefault();
}, false);
If the user skips the radio buttons, just make that check in the on submit function before filling in the numerical input.
var radio = document.getElementById('optradio');
var input = document.getElementById('ins_value');
radio.addEventListener("click", function(){
if(radio.value == 0){
radio.value = 1;
this.checked = true;
input.removeAttribute('disabled')
input.value = radio.value;
}
else{
radio.value = 0;
input.setAttribute('disabled','disabled');
input.value = '';
this.checked = false;
}
});
<input type="radio" name="optradio" id="optradio" value="0">
<input type="number" name="ins_value" id="ins_value" value="" disabled>
add disabled attribute to your numeric input like so
html:
<input type="radio" name="optradio" id="optradio" value="0">
<input type="number" name="ins_value" id="ins_value" value="" disabled>
javacript:
<script type="text/javascript">
var radio = document.getElementById('optradio');
var input = document.getElementById('ins_value');
radio.addEventListener("click", function(){
if(radio.value == 0){
radio.value = 1;
this.checked = true;
input.removeAttribute('disabled')
input.value = radio.value;
}
else{
radio.value = 0;
input.setAttribute('disabled','disabled');
input.value = '';
this.checked = false;
}
});
</script>
add the script below your html code
I'm trying to get a form item (in this case a radio button) to toggle being disabled on a double click. by default I want the item to be disabled (this part works) however I cannot seem to get my javascript function to change the status of disabled for the ondblclick="".
Its also worth noting that I wan t to reuse this function on many different form items. So its important that I keep it generic so it can be reused, simply by calling the function.
Here is my form's radio button's code:
<input type="radio" name="clubMember" id="member" value="Member" <?= $U_Club_Member == "Member" ? 'checked' : '' ?> onMouseDown="this._chckd = this.checked" onclick=" if (this._chckd) this.checked = false; return validateClubInfo();" ondblclick="return disableToggle();" disabled = "true" />Club Member
<input type="radio" name="clubMember" id="nonMember" value="Non-Member" <?= $U_Club_Member == "Non-Member" ? 'checked' : '' ?> onMouseDown="this._chckd = this.checked; this._dsbld = this.disabled" onclick="if (this._chckd) this.checked = false; return validateClubInfo();" ondblclick="return disableToggle();" disabled = "true" />Non Member
Here is my javascript function:
function disableToggle()
{
if(this.disabled == true)
{
this.disabled = false;
return true;
}
else if(this.disabled == false)
{
this.disabled = true;
return true;
}
}
Since you aren't passing the context to the disableToggle function, it is trying to disable the entire window.
Try this: ondblclick="disableToggle(this);"
And this: function disableToggle(radio) {radio.disabled = !radio.disabled;}
Or even this: ondblclick="this.disabled = !this.disabled;"
Okay, scrap the above. The event won't fire on disabled elements.
But ask yourself if this is really a good idea. I mean, how will the user know to double-click. What if the user CAN'T double-click (ie. touchscreens/phones... or people who just use their keyboard like me)
I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />
<label for="Merital Status">Marital Status:</label>
<input type="radio" title="Marital Status" name="Marital_Status" id="Marital Status" value="Single"/>Single
<input type="radio" title="Marital Status" name="Marital_Status" value="Married"/>Married
<input type="radio" title="Marital Status" name="Marital_Status" value="Divorced"/>Divorced
And I want to write a JavaScript function that checks whether a radi button named "Merital_Status" is selected. I represent the function that I wrote for this purpose. The function gets as an argument the element id and returnes boolen:
function radio_button_checker(elemId)
{
var radios = document.getElementsByTagName(elemId);
var value = false;
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
value = true;
break;
}
}
return value;
}
And I invoke this function like this:
if (radio_button_checker('Marital_Status') == false)
{
alert('Please fill in your Merital Status!');
return false;
}
But it does not work. Please tell me how to modify my function in order to check if radiobutton is checked.
What you are doing is looking for an element with the tag name "Merital_Status". Replace document.getElementsByTagName with document.getElementsByName and it should work.
You are mixing ID's and NAME's.
Your radio button "set" needs to all have the same name (which you have), and if you need to refer to them individually by id, then you'll need to add an id to the last two (currently not set... and not required if you apply the labels to each individual option). You will want the label tags for each radio button as it improves the usability by allowing the user to click on the word not just the small radio button.
Marital Status:
<label><input type="radio" name="Marital_Status" value="Single"/>Single</label>
<label><input type="radio" name="Marital_Status" value="Married"/>Married</label>
<label><input type="radio" name="Marital_Status" value="Divorced"/>Divorced</label>
However when you test... you want to see that at least 1 radio in the set is checked. You can do this with:
function radioButtonChecker(fieldNAME){
var radioSet = document.forms[0].elements[fieldName];
for(var i=0;i<radioSet.length;i++){
if(radioSet[i].checked){
return true;
}
}
return false;
}
There are a few presumptions made here.
You always have more than 1 radio button in the set
Your form is the 1st (index 0) form... if not you'll need to adjust the radioSet lookup