html radiobutton won't fire event - javascript

I'm constructing this webpage and i want to change the label and mas of an input depending on the radio button selected by the user.
I have read all the posts from people with the same problem, like jQuery .focus() and .blur() not working in Chrome or Safari or http://juristr.com/blog/2008/06/attaching-client-side-event-handler-to/ but the solutions proposed don't seem to be working!
Here's the javascript:
$(document).ready(function() {
$("#cep").mask("99999-999");
$("#jur", "#fis").click(function() {
docProcess(this.value);
});
function docProcess(value) {
alert("hi");
if (value == "jur") {
$("#docLabel").value = "CNPJ: ";
$("#docLabel").mask("99.999.999/9999-99");
} else {
$("#docLabel").value = "CPF: ";
$("#docLabel").mask("999.999.999-80");
}
}
});
and here is the html:
<label for="clientType">Tipo de cliente: </label>
<input class"radioButton" type="radio" name="clientType" id="jur" value="jur" />
<label class="radioButton" for="clientType">Jurídico</label>
<input class"radioButton" type="radio" name="clientType" id="fis" value="fis" />
<label class="radioButton" for="clientType">Físico</label>
<label for="doc" id="docLabel">CNPJ: </label>
<input type="text" id="doc" name="doc" />
Any help?

Instead of writing $("#docLabel").value = "CNPJ: ";, write $("#docLabel").text("CNPJ: ");.

Multiple selectors are delimited by a comma within the string. Update your selector to $("#jur, #fis") and it will work fine.
For more info regarding multi select statements reference jQuery Multiple Selector
$(document).ready(function() {
//$("#cep").mask("99999-999");
$("#jur, #fis").click(function() {
docProcess(this.value);
});
function docProcess(value) {
alert("hi");
if (value == "jur") {
$("#docLabel").value = "CNPJ: ";
//$("#docLabel").mask("99.999.999/9999-99");
} else {
$("#docLabel").value = "CPF: ";
//$("#docLabel").mask("999.999.999-80");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="clientType">Tipo de cliente:</label>
<input class "radioButton" type="radio" name="clientType" id="jur" value="jur" />
<label class="radioButton" for="clientType">Jurídico</label>
<input class "radioButton" type="radio" name="clientType" id="fis" value="fis" />
<label class="radioButton" for="clientType">Físico</label>
<label for="doc" id="docLabel">CNPJ:</label>
<input type="text" id="doc" name="doc" />

Thanks all, so it was a bit of help from adeneo and pierre!
changed the access to $("#jur, #fis") and the prop change $("#docLabel").text("CNPJ: ") and it worked like a charm! ty!

Related

Why the input never change the disabled attribute?

I want to enable/disable an input type="number" but it never changes.
It starts disabled and when I press a input type="radio" I want to enable it.
<input type="number" class="form-control filtros_mapa_ruta" id="n_nodes_ruta" value="2" min="1" disabled>
I see a lot of people have this problem and they usually try with $('input').attr("disabled", true); but is failing too.
The jQuery function, using .prop("disabled", true):
$("#radio_ult_pos").on('click', function() {
if ($('#radio_ult_pos').is(':checked')) {
$( ".filtros_mapa_ruta" ).checkboxradio( "disable" );
$('#n_nodes_ruta').prop("disabled", true);
}
});
$("#radio_ruta").on('click', function() {
if ($('#radio_ruta').is(':checked')) {
$( ".filtros_mapa_ruta" ).checkboxradio( "enable" );
$('#n_nodes_ruta').prop("disabled", false);
}
});
Snippet (the checkbox here is not working because I'm using a jQuery UI widget, but they're working well in my code):
function checkboxController() {
$("#radio_ult_pos").on('click', function() {
if ($('#radio_ult_pos').is(':checked')) {
$(".filtros_mapa_ruta").checkboxradio("disable");
$('#n_nodes_ruta').prop("disabled", true);
}
});
$("#radio_ruta").on('click', function() {
if ($('#radio_ruta').is(':checked')) {
$(".filtros_mapa_ruta").checkboxradio("enable");
$('#n_nodes_ruta').prop("disabled", false);
}
});
}
$(document).ready(function() {
checkboxController();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-2" id="filter_container">
<!-- FILTROS-->
<legend>Filtros mapa: </legend>
<label for="radio_ult_pos">Última posición</label>
<input type="radio" name="radio_select" class="filtros_mapa" id="radio_ult_pos" checked>
<label for="radio_ruta">Ruta</label>
<input type="radio" name="radio_select" class="filtros_mapa" id="radio_ruta">
<legend id="legend_filtro_datos">Filtros datos: </legend>
<label for="checkbox-2">Goat tracker 1</label>
<input type="checkbox" name="GOAT_TRACKER1" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-2" disabled>
<label for="checkbox-3">Goat tracker 2</label>
<input type="checkbox" name="GOAT_TRACKER2" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-3" disabled>
<label for="checkbox-4">Goat tracker 3</label>
<input type="checkbox" name="GOAT_TRACKER3" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-4" disabled>
<input type="number" class="form-control filtros_mapa_ruta" id="n_nodes_ruta" value="2" min="1" disabled>
<button type="button" class="btn btn-success" id="filtrar_btn_map">Filtrar</button>
</div>
I tried with $('#n_nodes_ruta').removeAttr("disabled") but is not working too...
Why never change the attribute disabled?
In JS, you can set an event listener on the container div and if the radio buttons are clicked, you can set the disabled property on the input to true or false.
const input = document.getElementById("n_nodes_ruta");
function checkboxController() {
document.querySelector('.col-2').addEventListener('click', () => {
if(event.target.id === "radio_ult_pos") {
input.disabled = true;
}
else if(event.target.id === "radio_ruta") {
input.disabled = false;
}
})
}
$(document).ready(function() {
checkboxController();
});
As #Heretic Monkey said the problem was the jQuery function checkboxradio.
Yes, it was defined, but the problem was that the class filtros_mapa_ruta has the input as well, and that made him fail.
The solution was to call the right class, only with the checkbox.
$(".filtros_mapa_ruta_checkb" ).checkboxradio( "disable");
Thank you
you can simply use .attr('disabled', 'disabled') to make it disabled and .removeAttr('disabled') to enable it.

Problems with checkbox required php-js [duplicate]

When using the newer browsers that support HTML5 (FireFox 4 for example);
and a form field has the attribute required='required';
and the form field is empty/blank;
and the submit button is clicked;
the browsers detects that the "required" field is empty and does not submit the form; instead browser shows a hint asking the user to type text into the field.
Now, instead of a single text field, I have a group of checkboxes, out of which at least one should be checked/selected by the user.
How can I use the HTML5 required attribute on this group of checkboxes?
(Since only one of the checkboxes needs to be checked, I can't put the required attribute on each and every checkbox)
ps. I am using simple_form, if that matters.
UPDATE
Could the HTML 5 multiple attribute be helpful here? Has anyone use it before for doing something similar to my question?
UPDATE
It appears that this feature is not supported by the HTML5 spec: ISSUE-111: What does input.#required mean for #type = checkbox?
(Issue status: Issue has been marked closed without prejudice.)
And here is the explanation.
UPDATE 2
It's an old question, but wanted to clarify that the original intent of the question was to be able to do the above without using Javascript - i.e. using a HTML5 way of doing it. In retrospect, I should've made the "without Javascript" more obvious.
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, you can easily control if a checkbox group has at least one checked element.
Consider the following DOM snippet:
<div class="checkbox-group required">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
</div>
You can use this expression:
$('div.checkbox-group.required :checkbox:checked').length > 0
which returns true if at least one element is checked.
Based on that, you can implement your validation check.
Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)
<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5
Following is jQuery script, which disables further validation check if any one is selected. Select using name element.
$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)
$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
$cbx_group.prop('required', false);
}
Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.
// but this might not work as expected
$('form').submit(function(){
// code goes here
});
// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
// skipping validation part mentioned above
});
HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:
HTML
<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two
JAVASCRIPT
function deRequireCb(elClass) {
el = document.getElementsByClassName(elClass);
var atLeastOneChecked = false; //at least one cb is checked
for (i = 0; i < el.length; i++) {
if (el[i].checked === true) {
atLeastOneChecked = true;
}
}
if (atLeastOneChecked === true) {
for (i = 0; i < el.length; i++) {
el[i].required = false;
}
} else {
for (i = 0; i < el.length; i++) {
el[i].required = true;
}
}
}
The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!
I guess there's no standard HTML5 way to do this, but if you don't mind using a jQuery library, I've been able to achieve a "checkbox group" validation using webshims' "group-required" validation feature:
The docs for group-required say:
If a checkbox has the class 'group-required' at least one of the
checkboxes with the same name inside the form/document has to be
checked.
And here's an example of how you would use it:
<input name="checkbox-group" type="checkbox" class="group-required" id="checkbox-group-id" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
I mostly use webshims to polyfill HTML5 features, but it also has some great optional extensions like this one.
It even allows you to write your own custom validity rules. For example, I needed to create a checkbox group that wasn't based on the input's name, so I wrote my own validity rule for that...
we can do this easily with html5 also, just need to add some jquery code
Demo
HTML
<form>
<div class="form-group options">
<input type="checkbox" name="type[]" value="A" required /> A
<input type="checkbox" name="type[]" value="B" required /> B
<input type="checkbox" name="type[]" value="C" required /> C
<input type="submit">
</div>
</form>
Jquery
$(function(){
var requiredCheckboxes = $('.options :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
} else {
requiredCheckboxes.attr('required', 'required');
}
});
});
Inspired by the answers from #thegauraw and #Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function () {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function () {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function () {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
I added an invisible radio to a group of checkboxes.
When at least one option is checked, the radio is also set to check.
When all options are canceled, the radio is also set to cancel.
Therefore, the form uses the radio prompt "Please check at least one option"
You can't use display: none because radio can't be focused.
I make the radio size equal to the entire checkboxes size, so it's more obvious when prompted.
HTML
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
Javascript
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
CSS
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
https://jsfiddle.net/codus/q6ngpjyc/9/
I had the same problem and I my solution was this:
HTML:
<form id="processForm.php" action="post">
<div class="input check_boxes required wish_payment_type">
<div class="wish_payment_type">
<span class="checkbox payment-radio">
<label for="wish_payment_type_1">
<input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_2">
<input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_3">
<input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
</label>
<input id='submit' type="submit" value="Submit">
</div>
</form>
JS:
var verifyPaymentType = function () {
var checkboxes = $('.wish_payment_type .checkbox');
var inputs = checkboxes.find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}
$('#submit').click(verifyPaymentType);
https://jsfiddle.net/oywLo5z4/
You don't need jQuery for this. Here's a vanilla JS proof of concept using an event listener on a parent container (checkbox-group-required) of the checkboxes, the checkbox element's .checked property and Array#some.
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEl = formEl.querySelector(".checkbox-group-required");
checkboxGroupEl.addEventListener("click", e => {
statusEl.textContent = validate(checkboxGroupEl) ? "valid" : "invalid";
});
formEl.addEventListener("submit", e => {
e.preventDefault();
if (validate(checkboxGroupEl)) {
statusEl.textContent = "Form submitted!";
// Send data from e.target to your backend
}
else {
statusEl.textContent = "Error: select at least one checkbox";
}
});
<form>
<div class="checkbox-group-required">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
If you have multiple groups to validate, add a loop over each group, optionally adding error messages or CSS to indicate which group fails validation:
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const allValid = els => [...els].every(validate);
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEls = formEl.querySelectorAll(".checkbox-group-required");
checkboxGroupEls.forEach(el =>
el.addEventListener("click", e => {
statusEl.textContent = allValid(checkboxGroupEls) ? "valid" : "invalid";
})
);
formEl.addEventListener("submit", e => {
e.preventDefault();
if (allValid(checkboxGroupEls)) {
statusEl.textContent = "Form submitted!";
}
else {
statusEl.textContent = "Error: select at least one checkbox from each group";
}
});
<form>
<div class="checkbox-group-required">
<label>
Group 1:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<div class="checkbox-group-required">
<label>
Group 2:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
I realize there are a ton of solutions here, but I found none of them hit every requirement I had:
No custom coding required
Code works on page load
No custom classes required (checkboxes or their parent)
I needed several checkbox lists to share the same name for submitting Github issues via their API, and was using the name label[] to assign labels across many form fields (two checkbox lists and a few selects and textboxes) - granted I could have achieved this without them sharing the same name, but I decided to try it, and it worked.
The only requirement for this one is jQuery, which could easily be eliminated if you wanted to rewrite it in vanilla JS. You can combine this with #ewall's great solution to add custom validation error messages.
/* required checkboxes */
jQuery(function ($) {
var $requiredCheckboxes = $("input[type='checkbox'][required]");
/* init all checkbox lists */
$requiredCheckboxes.each(function (i, el) {
//this could easily be changed to suit different parent containers
var $checkboxList = $(this).closest("div, span, p, ul, td");
if (!$checkboxList.hasClass("requiredCheckboxList"))
$checkboxList.addClass("requiredCheckboxList");
});
var $requiredCheckboxLists = $(".requiredCheckboxList");
$requiredCheckboxLists.each(function (i, el) {
var $checkboxList = $(this);
$checkboxList.on("change", "input[type='checkbox']", function (e) {
updateCheckboxesRequired($(this).parents(".requiredCheckboxList"));
});
updateCheckboxesRequired($checkboxList);
});
function updateCheckboxesRequired($checkboxList) {
var $chk = $checkboxList.find("input[type='checkbox']").eq(0),
cblName = $chk.attr("name"),
cblNameAttr = "[name='" + cblName + "']",
$checkboxes = $checkboxList.find("input[type='checkbox']" + cblNameAttr);
if ($checkboxList.find(cblNameAttr + ":checked").length > 0) {
$checkboxes.prop("required", false);
} else {
$checkboxes.prop("required", true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="post.php">
<div>
Type of report:
</div>
<div>
<input type="checkbox" id="chkTypeOfReportError" name="label[]" value="Error" required>
<label for="chkTypeOfReportError">Error</label>
<input type="checkbox" id="chkTypeOfReportQuestion" name="label[]" value="Question" required>
<label for="chkTypeOfReportQuestion">Question</label>
<input type="checkbox" id="chkTypeOfReportFeatureRequest" name="label[]" value="Feature Request" required>
<label for="chkTypeOfReportFeatureRequest">Feature Request</label>
</div>
<div>
Priority
</div>
<div>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: High" required>
<label for="chkPriorityHigh">High</label>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: Medium" required>
<label for="chkPriorityMedium">Medium</label>
<input type="checkbox" id="chkTypeOfContributionLow" name="label[]" value="Priority: Low" required>
<label for="chkPriorityMedium">Low</label>
</div>
<div>
<input type="submit" />
</div>
</form>
Really simple way to verify if at least one checkbox is checked:
function isAtLeastOneChecked(name) {
let checkboxes = Array.from(document.getElementsByName(name));
return checkboxes.some(e => e.checked);
}
Then you can implement whatever logic you want to display an error.
Here is another simple trick using Jquery!!
HTML
<form id="hobbieform">
<div>
<input type="checkbox" name="hobbies[]">Coding
<input type="checkbox" name="hobbies[]">Gaming
<input type="checkbox" name="hobbies[]">Driving
</div>
</form>
JQuery
$('#hobbieform').on("submit", function (e) {
var arr = $(this).serialize().toString();
if(arr.indexOf("hobbies") < 0){
e.preventDefault();
alert("You must select at least one hobbie");
}
});
That's all.. this works because if none of the checkbox is selected, nothing as regards the checkbox group(including its name) is posted to the server
Pure JS solution:
const group = document.querySelectorAll('[name="myCheckboxGroup"]');
function requireLeastOneChecked() {
var atLeastOneChecked = false;
for (i = 0; i < group.length; i++)
if (group[i].checked)
atLeastOneChecked = true;
if (atLeastOneChecked)
for (i = 0; i < group.length; i++)
group[i].required = false;
else
for (i = 0; i < group.length; i++)
group[i].required = true;
}
requireLeastOneChecked(); // onload
group.forEach(function ($el) {
$el.addEventListener('click', function () { requireLeastOneChecked(); })
});
Hi just use a text box additional to group of check box.When clicking on any check box put values in to that text box.Make that that text box required and readonly.
A general Solution without change the submit event or knowing the name of the checkboxes
Build a Function, which marks the Checkbox as HTML5-Invalid
Extend Change-Event and check validity on the start
jQuery.fn.getSiblingsCheckboxes = function () {
let $this = $(this);
let $parent = $this.closest('form, .your-checkbox-listwrapper');
return $parent.find('input[type="checkbox"][name="' + $this.attr('name')+'"]').filter('*[required], *[data-required]');
}
jQuery.fn.checkRequiredInputs = function() {
return this.each(function() {
let $this = $(this);
let $parent = $this.closest('form, .your-checkbox-list-wrapper');
let $allInputs = $this.getSiblingsCheckboxes();
if ($allInputs.filter(':checked').length > 0) {
$allInputs.each(function() {
// this.setCustomValidity(''); // not needed
$(this).removeAttr('required');
$(this).closest('li').css('color', 'green'); // for debugging only
});
} else {
$allInputs.each(function() {
// this.reportValidity(); // not needed
$(this).attr('required', 'required');
$(this).closest('li').css('color', 'red'); // for debugging only
});
}
return true;
});
};
$(document).ready(function() {
$('input[type="checkbox"][required="required"], input[type="checkbox"][required]').not('*[data-required]').not('*[disabled]').each(function() {
let $input = $(this);
let $allInputs = $input.getSiblingsCheckboxes();
$input.attr('data-required', 'required');
$input.removeAttr('required');
$input.on('change', function(event) {
$input.checkRequiredInputs();
});
});
$('input[type="checkbox"][data-required="required"]').checkRequiredInputs();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form>
<ul>
<li><input type="checkbox" id="checkbox1" name="countries" value="Argentina" required="required">Argentina</li>
<li><input type="checkbox" id="checkbox2" name="countries" value="France" required="required">France</li>
<li><input type="checkbox" id="checkbox3" name="countries" value="Germany" required="required">Germany</li>
<li><input type="checkbox" id="checkbox4" name="countries" value="Japan" required="required">Japan</li>
<li><input type="checkbox" id="checkbox5" name="countries" value="Australia" required="required">Australia</li>
</ul>
<input type="submit" value="Submit">
</form>
Try:
self.request.get('sports_played', allow_multiple=True)
or
self.request.POST.getall('sports_played')
More specifically:
When you are reading data from the checkbox array, make sure array has:
len>0
In this case:
len(self.request.get('array', allow_multiple=True)) > 0

How to toggle div visibility using radio buttons?

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.
I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.
I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().
JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});
You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});
.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}
use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

toggle textbox if checkbox is true for CMS

I try to make something like that work, implementing it in my CMS:
Fixed CMS part:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<input value="yes"></input>
<input value="no"></input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
own JS part someting like:
function EnableTextbox(radioListId,spanId)
{
if(document.getElementById(radioListId).inputValue == "yes")
document.getElementById(textBoxId).visibility = visible;
else
document.getElementById(textBoxId).visibility = hidden;
}
But I am not quite sure how to put it correctly - my understanding of js is not really high enough.
Any helping comments are highly appreciated!
try this
HTML
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" name="showhide"> Show</input>
<input type="radio" value="no" name="showhide"> Hide</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
Script
$(document).ready(function () {
$("#txtBoxId").hide();
$("input[name='showhide']").on("click", function () {
var option = $(this).attr('value');
if (option == "yes") {
$("#txtBoxId").show();
} else {
$("#txtBoxId").hide();
}
});
});
Fiddle Sample
There are a few changes you need to make:
the inputs need to have a type="radio" to indicate that those are radio buttons.
the inputs need to have a common name="whatever" to indicate that both belong to same group and cannot be checked simultaneously.
the inputs need to have a text between the opening/closing tags, this text appears next to the radio button.
you need to call the javascript function when you click/change the buttons, and inside you check which radio was selected.
you pass the radio button reference into the javascript function by writing this as the function variable.
inside the function you retrieve the radio button reference, you can name the variable whatever you want.
you are using visible and hidden as variables, but those are not defined. it supposed to be either a string, or a boolean value. i prefer to use css for that purpose.
here is an Example Fiddle
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" onclick="EnableTextbox(this);" name="Answer">Yes</input>
<input type="radio" value="no" onclick="EnableTextbox(this);" name="Answer">No</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
JS:
function EnableTextbox(radioList) {
if (radioList.value == "yes") document.getElementById("txtBoxId").style.visibility = "visible";
else document.getElementById("txtBoxId").style.visibility = "hidden";
}
Since onclick="" is outdated you should use the element.addEventListener();!
Here is an Example in Fiddle!
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<label><input type="radio" name="answer" id="yes" value="yes" />Yes</label>
<label><input type="radio" name="answer" id="no" value="no"/>No</label>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
JS:
var yes = document.getElementById('yes');
var no_ = document.getElementById('no');
if (yes.addEventListener) {
yes.addEventListener ("RadioStateChange", OnChange, false);
no_.addEventListener ("RadioStateChange", OnChange, false);
}
function OnChange(){
if (yes.checked) {
document.getElementById('txtBoxId').style.display = 'inline';
}
else {
document.getElementById('txtBoxId').style.display = 'none';
}
}
Greetings from Vienna
In jQuery
<span id="spanId">
<input type="radio" name="radiobutton" value="yes" />
<input type="radio" name="radiobutton" value="no" />
</span>
$('#spanId input:radio[name="radiobutton"]').change(function(){
if($(this).val() === 'yes'){
$('#txtBoxId').show();
} else {
$('#txtBoxId').hide();
}
});
Explanation
$('#txtBoxId').show() = display:block;
$('#txtBoxId').hide() = display:none;
If you want visibility instead.
$('#txtBoxId').css('visibility','visible');
$('#txtBoxId').css('visibility','hidden');
Let me know if you have any question.

How do I show an input field if a radio button is checked using jquery

I have a radio button called "other," and when checked, I want a input field called "other-text" to show up. It's fairly simple, but I've been failing all morning.
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
Here is my javascript:
jQuery(function(){
jQuery("input[name=other]").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
JSFiddle of the failure. http://jsfiddle.net/Wpt3Y/532/
This works
jQuery("#other-radio").change(function(){...
Just updated your jsfiddle: http://jsfiddle.net/Wpt3Y/539/
<pre><input type="radio" name="other" id="other-radio" value="Yes"><b>Other</b></pre>
Your code works, you simply mistyped your radio input, it had two name attributes.
I suggest to go this way. Tried to use prop() but realised you use old version of jquery
jQuery("input:radio[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
example with radio
Instead you can use checkbox:
html
<input name="ocalls" type="checkbox" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
js
jQuery("input:checkbox[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
example with checkbox
<form>
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes">
<b>Other</b><br />
</input>
<input type="text" name="other-text" id="other-text" style="display: none;" />
</form>
jQuery(function(){
jQuery("#other-radio").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
Try this.
If you want that toggle effect you can use this code with the checkbox.
jQuery(function(){
jQuery("input[name=ocalls]").change(function(){
if($(this).attr("checked"))
{
$("#other-text").show();
}
else
{
$("#other-text").hide();
}
});
});
Your code is not working because you have name attribute twice in radio button.
use this:
<input type="radio" name="other" id="other-radio" value="Yes">
remove name="ocalls" attribute.

Categories

Resources