Hello I am trying to make a javascrip validate option depending on previouse choice.
Here is my form code:
<li><label for="age1">Question One ?</label>
<input type="radio" name="tienes_negocio" value="Yes" class="aboveage1" /> Si
<input type="radio" name="tienes_negocio" value="No" class="aboveage1" /> No</li></ol>
<ol id="parent1" class="formset2">
<li><label for="age2">Question Two ?</label>
<input type="radio" name="labora_negocio" value="Yes" required="true" class="aboveage2" /> Si
<input type="radio" name="labora_negocio" value="No" required="true" class="aboveage2" /> No</li>
Basicaly if you choose No frm the first selections I would like to pass the required attribute inside the selecond selection,
here is the JavaScript code:
$(document).ready(function(){
$("#parent1").css("display","none");
$(".aboveage1").click(function(){
if ($('input[name=tienes_negocio]:checked').val() == "No" ) {
$("#parent1").slideDown("fast"); //Slide Down Effect
$('input[name="labora_negocio"]').prop('required', true);
} else {
$("#parent1").slideUp("fast");
$('input[name="labora_negocio"]').prop('required', false); //Slide Up Effect
}
});
});
this is the code which I am using for passing the requred attribute: $('#labora_negocio').attr('required');
The problem is that when you choose No it is not passing anything.
You have two elements with the same id, in html this is a no no. Also when setting live element states you should set the element property rather than its (html) attribute.
You can select the radio button via their names and set their properties via prop.
<li><label for="age2">Question Two ?</label>
<input type="radio" name="labora_negocio" value="Yes" id="labora_negocio1" class="aboveage2" /> Si
<input type="radio" name="labora_negocio" value="No" id="labora_negocio2" class="aboveage2" /> No</li>
$(".aboveage1").click(function(){
if ($('input[name=tienes_negocio]:checked').val() == "No" ) {
$('[name="labora_negocio"]').prop('required', true);
$("#parent1").slideDown("fast"); //Slide Down Effect
} else {
$('[name="labora_negocio"]').prop('required', false); // not sure about this
$("#parent1").slideUp("fast"); //Slide Up Effect
}
});
Related
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)" />
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>
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.
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>
edit: Contacted the prof; I'm not actually [supposed] to use jQuery on this assignment as the action on the form (e.g. prof's website) doesn't allow for it. Tyvm to all who replied so quickly and helpfully. Therefore, I am interested in a pure, native JS soln. to resolving these difficulties:
getting a group of checkboxes to toggle "on or off" based on whether the user clicks "Yes" or "No" radio button in a DOM-oriented form. Here's the HTML for (I: the radio buttons, II: the checkboxes):
I:) Radio Buttons
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()"></input>
<label>Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()"></input>
<label>No</label>
II.) Checkboxes
<fieldset>
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
Using the rationale provided in posts such as Populating Checkboxes Based on Radio Button Click, which still uses jQuery, the best attempt I have made thus far is:
<script>
function subscribe(){
//var yesPlease = document.getElementById("rad1");
//var noThx = document.getElementById("rad2");
var arr = new Array["cor", "sof", "lspa", "cyn", "tos", "spal"];
//var hold = document.getElementById(arr[i]);
//if(hold.getAttribute(arr[i]).checked = true && arr[i] >= 1){
//document.getElementById("cor").innerHTML=hold.getAttribute("checked");
var hold = document.getElementsByName("mailinglist")[0];
for(var i = 0; i < arr.length; i++)
{
if(document.getElementById("rad1").checked==true)
{
hold.getAttribute(arr[i]).checked == true;
}
else if(document.getElementById("rad2").checked==true)
{
hold.getAttribute(arr[i]).checked == false;
}
}
}
</script>
When I load my document and click on either, nothing happens. Here's the screenshot of the concerned section if it helps:thanks:
Remove your inline javascript code and try attaching the event in the js file itself..
Try this
$('#rad1,#rad2').on('click', function() {
$('fieldset input[type="checkbox"]')
.prop('checked',this.value === 'Yes');
}
});
Check Fiddle
You need to an action handler when the radio button is clicked. So that the element attribute "checked" is correctly updated upon clicking.
The code below is edited from yours to just include the click handler on all input type radio
$(document).ready(function(){
function subscribe() {
$('input[type="radio"]').click(function(){
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked == true){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked == true) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
});
}
subscribe();
});
JSFiddle: http://jsfiddle.net/MSZtx/
This simple code will solve the issue,
JavaScript in HEAD section :
$(document).ready(function(){
$(".radio-button").click(function(){
if($(this).val() == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
});
})
Also add, the jquery library CDN source before the above code.
Markup in BODY section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()" class="radio-button"></input><label> No</label>
<fieldset class="checkbox-list">
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
There is also a 2nd option to do the same task,
JavaScript in HEAD section :
/* Solution - 2 */
function subscribe(ele)
{
if(ele == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
}
Also add, the jquery library CDN source before the above code.
Changes in MARKUP in body section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe(this.value)" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe(this.value)" class="radio-button"></input><label> No</label>
Your Code is just working perfectly :- see here:- http://jsfiddle.net/LeWbR/2/
the only problem I could imagine
have you included jquery in your page .
where you have placed your JS function.
see the left hand side dropdown in JSfiddle, if you change the the value from no wrap(body) to
onDomReady or onLoad it won't work.
function subscribe() {
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
}