Enable/Disable input by radio selection with jquery - javascript

A form with radio buttons. If "Existing" is checked, the "existingnumber" input will be enabled. It works fine during the selection process but does not work onload. On load the input "existingnumber" remains disabled even though it's "checked". This is problematic when the form is submitted, and fails error validation. I've tried appending .change() at the end, and creating a function which I called on document ready but that didn't work. I think I'm missing something. Perhaps I need to get the value first? I'm a bit of a jquery noob.
<input type="radio" name="officephone" value="New" id="officephonenew" >
<label for="officephonenew">New</label><br>
<input type="radio" name="officephone" value="Existing" id="officephoneexisting" checked>
<label for="officephoneexisting">Existing</label><br>
<input type="text" name="existingnumber" placeholder="555-555-1234" /><br>
<input type="radio" name="officephone" value="No" id="officephoneno">
<label for="officephoneno">Not required</label>
$('input:radio[name="officephone"]').change(function(){
$('input[name="existingnumber"]').prop("disabled",true);
if($(this).attr('value') == 'Existing') {
$('input[name="existingnumber"]').prop("disabled", false);
}
});
https://jsfiddle.net/Cormang/sd8xaj9h/10/

To make this work on load simply use filter() to retrieve the checked radio button and trigger() the change event on it.
Also note that you can simplify the logic by providing the boolean output of the condition to the disabled property and by using val().
$('input:radio[name="officephone"]').change(function() {
$('input[name="existingnumber"]').prop("disabled", $(this).val() != 'Existing');
}).filter(':checked').trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="officephone" value="New" id="officephonenew" />
<label for="officephonenew">New</label><br />
<input type="radio" name="officephone" value="Existing" id="officephoneexisting" checked />
<label for="officephoneexisting">Existing</label><br />
<input type="text" name="existingnumber" placeholder="555-555-1234" disabled /><br />
<input type="radio" name="officephone" value="No" id="officephoneno" />
<label for="officephoneno">Not required</label>

Related

Sending "this" radio button element parameter to function in Google Apps script

I have a custom sidebar generated via Apps Script on a Google Sheet.
The custom sidebar html contains a form and fieldset with 5 radio input elements, all with onchange events:
google.script.run.viewOptionsFormRadioChange(this);
Here's the full form HTML:
<form id="viewOptionsForm">
<fieldset class="viewOptionsFieldset">
<input type="radio" id="all" name="viewOptionsRadio" value="All" checked="checked" onchange='google.script.run.viewOptionsFormRadioChange(this);' >
<label for="all">All</label><br>
<input type="radio" id="firstImport" name="viewOptionsRadio" value="First Import" onchange='google.script.run.viewOptionsFormRadioChange(this);'>
<label for="firstImport">First Import</label><br>
<input type="radio" id="secondImport" name="viewOptionsRadio" value="Second Import" onchange='google.script.run.viewOptionsFormRadioChange(this);'>
<label for="secondImport">Second Import</label><br>
<input type="radio" id="compositionLinking" name="viewOptionsRadio" value="Composition Linking" onchange='google.script.run.viewOptionsFormRadioChange(this);'>
<label for="compositionLinking">Composition Linking</label><br>
<input type="radio" id="underTheHood" name="viewOptionsRadio" value="Under the Hood" onchange='google.script.run.viewOptionsFormRadioChange(this);'>
<label for="underTheHood">Under the Hood</label>
</fieldset>
</form>
I then have a function "viewOptionsFormRadioChange":
function viewOptionsFormRadioChange(checkbox) {
if(checkbox.checked == true){
if(checkbox.attr('id') == "underTheHood") {
SpreadsheetApp.getActive().toast("underTheHood Selected", "Title", 15);
}
}
}
I'm trying to get it so the toast notification appears when I select the Under the Hood radio button, however the "this" element parameter doesn't appear to be coming through as parameter variable: checkbox since the above doesn't work.
Any ideas where I'm going wrong?
Thanks either way
I think that in your script, how about modifying this to this.value or this.id? It seems that in this case, this cannot be parsed. So, when your script is modified, how about the following modification?
Modified script:
In this modification, your HTML is modified.
<form id="viewOptionsForm">
<fieldset class="viewOptionsFieldset">
<input type="radio" id="all" name="viewOptionsRadio" value="All" checked="checked" onchange='google.script.run.viewOptionsFormRadioChange(this.value);' >
<label for="all">All</label><br>
<input type="radio" id="firstImport" name="viewOptionsRadio" value="First Import" onchange='google.script.run.viewOptionsFormRadioChange(this.value);'>
<label for="firstImport">First Import</label><br>
<input type="radio" id="secondImport" name="viewOptionsRadio" value="Second Import" onchange='google.script.run.viewOptionsFormRadioChange(this.value);'>
<label for="secondImport">Second Import</label><br>
<input type="radio" id="compositionLinking" name="viewOptionsRadio" value="Composition Linking" onchange='google.script.run.viewOptionsFormRadioChange(this.value);'>
<label for="compositionLinking">Composition Linking</label><br>
<input type="radio" id="underTheHood" name="viewOptionsRadio" value="Under the Hood" onchange='google.script.run.viewOptionsFormRadioChange(this.value);'>
<label for="underTheHood">Under the Hood</label>
</fieldset>
</form>
But, in this case, the returned value is the string value like First Import, Second Import,,,. So, your Google Apps Script might be required to be modified as follows.
function viewOptionsFormRadioChange(checkbox) {
if(checkbox == "Under the Hood") {
SpreadsheetApp.getActive().toast("underTheHood Selected", "Title", 15);
}
}
By this modification, when you check "Under the Hood", toast() is run.
Note:
If you want to use the value of id, please moidify this.value to this.id. By this, you can use the value of ID in your HTML tag. It's like if(checkbox == "underTheHood") {,,,} instead of if(checkbox == "Under the Hood") {,,,}.

How to toggle a radio button with a label

I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.

Passing input id as jquery function paramenter

I'm new to jQuery.
I am trying to create a reusable function that will replace the text of a input field.
I pass in the field I want to change as one parameter and the new text as another parameter.
I figured I would try it out with some radio buttons.
HTML
<label>
<input type="radio" name="optradio" onClick="replaceText(txt_recipient, 'All')" value="0" checked>All</label>
<label>
<input type="radio" name="optradio" onClick="replaceText(txt_recipient, 'Geo')" value="1">Geographical Area</label>
<label>
<input type="radio" name="optradio" onClick="replaceText(txt_recipient, '')" value="2">Specific User</label>
<input type="text"id="txt_recipient" name="txt_recipient" value="All" />
JS
function replaceText(field, newtext) {
document.getElementById(field).text(newtext);
};
I originally toyed with the idea of
function replaceText(field, newtext) {
$(field).text(newtext);
};
but that didn't seem to work either. Help?
field is the actual element so just set the input value property.
function replaceText(field, newtext) {
field.value = newtext;
}
DEMO: http://jsfiddle.net/039v0wst/1/
with jQuery
function replaceText(field, newtext) {
$(field).val(newtext);
}
DEMO: http://jsfiddle.net/rgen7vLv/1/
First of all give unique names:
<input type="radio" name="optradio1" onClick="replaceText(txt_recipient, 'All')" value="0" checked>All</label>
Geographical Area
then js
$('input[name$="optradio1"]').val("newtext")
Can you pass the field id with ' '
E.g;
'txt_recipient' instead of 'txt_recipient
It is no longer recommended to declare event handlers inline in the HTML attributes.
Using a more modern syntax, I'd include a data attribute that specifies the text in the destination, the update your target using the string from the data attribute.
$('input[type="radio"]').change(function() {
$("#txt_recipient").val($(this).data("text"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>
<input type="radio" name="optradio" data-text="All" value="0" checked>All</label>
<label>
<input type="radio" name="optradio" data-text="Geo" value="1">Geographical Area</label>
<label>
<input type="radio" name="optradio" data-text="" value="2">Specific User</label>
<input type="text"id="txt_recipient" name="txt_recipient" value="All" />

Delete drop down when it is blank using Javascript or Jquery

Is it possible to write a Javascript function to delete a drop down when it is blank?
<form name="myform" method="post" enctype="multipart/form-data" action="" id="myform">
<div>
<label id="question1">1) Draw recognizable shapes</label>
<br />
<input type="radio" value="Yes" id="question1_0" name="question1_0" />
Yes
<input type="radio" value="No" id="question1_1" name="question1_1" />
No
</div>
<div>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
<div>
<label id="question3">3) Hold a pencil</label>
<br />
<input type="radio" value="Yes" id="question3_0" name="question3_0" />
Yes
<input type="radio" value="No" id="question3_1" name="question3_1" />
No
</div>
<input type="submit" value="Delete Drop Down" onclick="return checkanddelete"/>
</form>
If somebody does not select question 2 for example, it deletes question 2 label and the drop down.
Assuming you actually meant radio button groups (and not drop down lists) then firstly your HTML is incorrect, you need to set the name values of each group of radio buttons to be the same:
<input type="radio" value="Yes" id="question1_0" name="question1" /> Yes
<input type="radio" value="No" id="question1_1" name="question1" /> No
Then you need to loop through the list of radio buttons, if none in the group are selected then delete the parent div:
$('input[type=submit]').on('click', function() {
var radioArr = [];
$(':radio').each(function(){
var radName = this.name;
if($.inArray(radName, radioArr) < 0 && $(':radio[name='+radName+']:checked').length == 0)
{
radioArr.push(radName);
$(this).closest("div")
.remove();
}
});
return false; //to stop the form submitting for testing purposes
});
While you are there, you might want to add some <label for=""> tags around your text.
Here is a jsFiddle of the solution.
If your dropdown has an id of DropDown, and you are looking to hide the dropdon on submit click:
function checkanddelete()
{
if ( $('#question2_0.=:checked, #question2_1:checked').length )
$('#dropdown').hide() // Or $('#dropdown').remove() if you do not plan on showing it again.
return false; // if you plan on not submitting the form..
}
Optimization for use in a module for a page include adding appropriate ids and classes to the divs, which I'm assuming that in full code are there, but if you are planning on making UI adjustments I would advise against using a submit button in the mix..
I don't know, what do you mean under "dropdown menu", but here some info, that can help you.
You can set a class name for the all Objects, you want to delete. E.g.
HTML
<div>
<label class='question2' id="question2">2) Competently cut paper </label>
<br />
<input class='question2' type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input class='question2' type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
JS
$(".question2").remove();
As an another solution you can set an ID for the DIV Tag above all of this elements
<div id='block_to_remove'>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
And then remove it in JS
$("#block_to_remove").remove();

Set radio button value in javascript

I am trying to set the value of the radio button via javascript. But I am not being able to do so. What I tried to do was have 4 radio buttons one of which is already selected. If I select some other radio button and click on Refresh, default radio button should be selected.
http://jsfiddle.net/ds345/Un8XK/1/
HTML:
<fieldset data-role="controlgroup" data-type="vertical">
<input type="radio" name="radio" id="x" data-theme="a" />
<label for="x" style="color: White">X</label>
<input type="radio" name="radio" id="y" onclick="axisonoff(this)" data-theme="a" />
<label for="y" style="color: White">Y</label>
<input type="radio" name="radio" id="z" data-theme="a" />
<label for="z" >Z</label>
<input type="radio" name="radio" id="none" data-theme="a" />
<label for="none" style="color: White">None</label>
</fieldset>
<button id = "Refresh" value="Refresh">Refresh</button>
JS:
$(document).ready(function () {
$("#none").attr("checked", true).checkboxradio("refresh"); // if this line is not present initially then it works for the 1st refresh.
});
$("#Refresh").click(function(){
$("#x").attr("checked", false).checkboxradio("refresh");
$("#y").attr("checked", false).checkboxradio("refresh");
$("#z").attr("checked", false).checkboxradio("refresh");
$("#none").attr("checked", true).checkboxradio("refresh");
});
I am sure that I have missed something very small but not able to figure out why this approach is not working.
Tools used: Javascript,Jquery 1.9 and JQuery mobile 1.3
Thanks,
Deeksha
You should use prop over attr when dealing with boolean attributes.
.attr("checked", false) will add checked="false" to your element.In HTML, <input checked="false" .../> is the same as <input checked="true" .../> or simply <input checked .../> as the attribute simply needs to be present on the element for it to be active.
See this JSFiddle example.
Change your code to use .prop() instead:
$("#none").prop("checked", false)...
Here is a fixed version of your JSFiddle demo: http://jsfiddle.net/Un8XK/8/
What you have missed is that there is no need for script. Simply use a form with a reset button:
<form>
<input type="radio" name="radio" value="0" checked>0<br>
<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>
<input type="radio" name="radio" value="3">3<br>
<input type="reset">
</form>
If you really must use script, you can simply return the radio buttons to their default by adding a button to the form:
<input type="button" onclick="reset(this.form.radio);" value="Script reset">
and a function:
<script>
function reset(els) {
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].checked = els[i].defaultChecked;
}
}
</script>

Categories

Resources