Generic way to control disabled in windows form - javascript

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)

Related

How can I enable / disable form fields from within the form tag?

I am trying to enable / disable inputs inside a form using a checkbox. For some reason, when I place the checkbox INSIDE the form tag my javascript function won't work.
This works:
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<form id = 'form'>
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
However, when I try to move the input id = 'check' INSIDE the form tag, the function won't work:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
This must be something very silly, but I can't figure it out.
Please notice: I am trying to use this inside a bigger, multi-page form that asks from residence information first and then, in the second tab/page, asks for mailing info. So, if the checkbox is checked I want mailing info fields to be disabled.
Any idea? Help is appreciated!
It looks like that inside a form the check variable what you want to call will be the HtmlNode itself because it got the same name(id).
So in you code with check() you are try to call the HtmlNode which is for sure not a function.
If you rename the function to something like test it will work fine.
or use the addEventListener method to pass the function itself and this will also keep your code cleaner.
You can have a look in this fiddle:
https://jsfiddle.net/k7xjv0Ls/
So this thing is probably a possibility to make it easy to manage forms it self. e.g. You don't need any <script> here at all, if you do something like this:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'text.disabled = check.checked' />
<input type='text' id = 'text'/>
</form>
Explanation for all modern browsers like "Firefox, Chrome, Safari":
the id of an HTMLNode usually goes to the window object as an attribute to reference the HTMLNode itself.
If the HTMLNode is a input field AND it is inside a form tag it will always shadow all kinds of variables (Named functions, vars, consts and lets) but just inside the "Event Attribute" of the HTML, not in the javascript files or all what is inside the <script> tag.
In your case window.check is ambiguous - it could be window.check the function or window.check the field with id="check"
Try to never reuse function, var an element names/IDs
To dix your immediate issue, just rename and pass the checkbox
function checkIt(theCheck) {
const c = theCheck.checked
document.getElementById("text").disabled = c;
}
<form id='form'>
<input type='checkbox' id='check' onchange='checkIt(this)' checked />
<input type='text' id='text' disabled />
</form>
I however STRONGLY recommend to use event listeners
window.addEventListener("load", function() {
document.getElementById("check").addEventListener("change", function() {
document.getElementById("text").disabled = this.checked;
});
});
<form id='form'>
<input type='checkbox' id='check' checked />
<input type='text' id='text' disabled />
</form>

HTML form if one radio condition is selected then force an input

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

Checking between two radio buttons with javascript .prop('checked');

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;
}

how to call a javascript function on radio button's 'checked' property?

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");" />

How to Uncheck A radio button

I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!

Categories