I searched the net and tried all solutions for similar questions from SO, but just can't get this one working.
I am working in Django admin, and I have RadioSelect widget for the field is_valid, with two radio buttons in the form:
<div class="form-row field-is_valid">
<div>
<label for="id_is_valid_0">Is it valid?</label>
<ul id="id_is_valid" class="inline">
<li><label for="id_is_valid_0"><input type="radio" name="is_valid" value="True" id="id_is_valid_0" checked>
Yes
</label>
</li>
<li><label for="id_is_valid_1"><input type="radio" name="is_valid" value="False" id="id_is_valid_1">
No
</label>
</li>
</ul>
</div>
</div>
<div class="form-row field-not_valid_reason">
<div>
<label for="id_not_valid_reason">Reason:</label>
<select name="not_valid_reason" id="id_not_valid_reason">
<option value="" selected>Choose</option>
<option value="Expired">Expired</option>
<option value="Not adopted">Not adopted</option>
<option value="Unknown">Unknown</option>
</select>
</div>
</div>
I want to hide a class .field-not_valid_reason when 'Yes' (True) is checked (which is default for is_valid field) and show it when I click 'No'. This I accomplished.
Here is my jQuery code:
(function($) {
$(function() {
var isValid = $('input[type=radio][name=is_valid]'),
notValidReason = $('.field-not_valid_reason'),
function toggleFields(value) {
if (value === 'True') {
notValidReason.hide(250);
} else {
notValidReason.show(250);
}
}
// show/hide on load based on previous value of isValid
toggleFields(isValid.val());
// show/hide on change
isValid.change(function() {
toggleFields($(this).val());
alert(isValid.val());
});
});
})(django.jQuery);
But, for some reason, after the object is saved in the database with the is_valid field False, when I am on the change page of that object, the class .field-not_valid_reason is hidden, albeit active radio button is set to "No" (False).
Can you help, please?
In your current jquery code you where using alert(isValid.val()); to see which option is selected but this will give you first value only so to get current value which user has selected use $(this).val().
Then , onload you where getting right value for radio but the div was still hidden because you are again passing toggleFields(isValid.val()); which will give you first value only .So , to overcome this pass radio value which is checked i.e : $("input[name='is_valid']:checked").val() .
Related
I am new to Angular. Need some help here. There are two radio buttons for two text fields:
<div class="col-1">
<label class="radio-container mb-0 mt-1">
<input id="Page_Color" name="Page_Color" type="radio" [(ngModel)]='Br.Page_IsGraphic'
[value]='false' (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_IsGraphic','Page_GraphicName','Page_Color')">
<span class="checkmark"></span>
</label>
</div>
<div class="col-1">
<label class="radio-container mb-0 mt-1">
<input id="IsGraphic" name="IsGraphic" type="radio" (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_Graphic','Page_GraphicName','PageColor')"
[(ngModel)]='Br.Page_IsGraphic' [value]='true'>
<span class="checkmark"></span>
</label>
</div>
In [(ngModel)]='Br.Page_IsGraphic' Br.Page_IsGraphic value is either true or false and that is dynamic and based on that the radio button is getting checked i think.
If it's true then the second radio button gets selected and if it's false then the 1st one.
Now the 1st text field had to be removed as per the requirement and I want the second radio button to be always selected by default.
Br.Page_IsGraphic value should be set to true before theis code gets executed for this to work? or is there another way.
I tried [checked]="true" and that did not work.
As I understand you have two radio button associated with two text field and want to show text fields based on radio buttons are checked or not
.html file
<input type="radio" [checked] = "isFirst === true" (change)="markFirst()"/> First
<input type="radio" [checked] = "isSecond === true" (change)="markSecond()"/>Second
<br><br>
<input type="text" placeholder="First" *ngIf="isFirst"/>
<br><br>
<input type="text" placeholder="Second" *ngIf="isSecond"/>
.ts file
export class AppComponent {
isFirst = false
isSecond = false
markFirst(){
this.isFirst = true
// this.isSecond = false If you want second to hide if one is shown
}
markSecond(){
this.isSecond = true
// this.isFirst = false If you want second to hide if one is shown
}
}
Working link
https://stackblitz.com/edit/angular-jkqvqz
I did this and it selected the checkbox by default:
[(ngModel)]='Br.Page_IsGraphic' [value]='Br.Page_IsGraphic'>
My form has a checkbox followed by several radio buttons.Basically, the design calls for a user to be able to use a checkbox to clear a set of radio buttons (or set a default value). If the user should select a radio button then the checkbox will also be set.
Overall most of the requirements are met by the code below, however there is one condition when it doesn't work:
User Selects Checkbox. (Check appears in checkbox)
User Selects Radio button. (Radio button is selected)
User Selects Checkbox Again. (Check disappears from checkbox and radio button deselects)
User Selects Radio button. (Check appears in checkbox and radio button selects)
User deselects Checkbox. (Check disappears but the value isn't updated so the radio button does not deselect)
What is happening? How can this be written to get the behavior my user wants?
Thanks,
Matt
Here is the code:
var myAngular=angular.module('myApp',[]);
myAngular.controller('myController',function($scope){
$scope.title="Angular Radio Buttons";
$scope.selectedValue='i10';
$scope.numStatus = 0;
$scope.numStatusChanged = function () {
console.log('numStatusChanged:')
if ($scope.numStatus === 0) {
$scope.numStatus = 3;
console.log('From 0 to 3.');
} else {
$scope.numStatus = 0;
console.log('From ' + $scope.numStatus + ' to 0.' )
}
};
$scope.$watch('numStatus', function(newValue,oldValue,scope){
console.log('newVal:' + newValue + ' oldValue:' + oldValue);
});
$scope.$watch('aBool', function(newValue,oldValue,scope){
console.log('aBoolNew:' + newValue + ' aBoolOld:' + oldValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller='myController'>
<p>Selected Value: {{numStatus}}</p>
<div class="checkBoxGroup">
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-checked="numStatus !== 0" ng-change="numStatusChanged()">
<label for="isCheckbox">A Value Is Selected</label>
<div class="radio-button-vertical">
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="1" name="numStatus" /> One</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="2" name="numStatus" /> Two</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="3" name="numStatus" /> Three</label>
</div>
</div>
</div>
</div>
</div>
You are using ngChecked and ngModel together, I would expect that your issue is that those two properties are conflicting with each other since they represent similar bindings (other SO post explaining this).
Just rewrite the checkbox to be:
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-change="numStatusChanged()">
and then do the numStatus !== 0 check in the numStatusChanged() method and use the result to set aBool.
I need to know if a radio button has been selected to hide / show other options.
<input #r4 type="radio" name="x">
<span>Group</span>
<div class="subOption" *ngIf="r4.checked"></div>
div.subOption must be displayed when it has been selected.
it's correct?¿
I would just create a new boolean variable in the component, that you set as true when radio button has been checked. With that boolean you then display the div. So for example:
isChecked: boolean = false; // our new variable
<input type="radio" name="x" (click)="isChecked = true">
<div *ngIf="isChecked">
<!-- Your code here -->
</div>
EDIT: As to multiple radiobuttons... as mentioned in a comment, radio buttons seems at this point be kind of buggy with Angular. I have found the easiest way to deal with radio buttons seems to be using a form. So wrap your radio buttons in a form, like so:
<form #radioForm="ngForm">
<div *ngFor="let val of values">
<input (change)="changeValue(radioForm.value)" type="radio" [value]="val.id" name="name" ngModel />{{val.name}}
</div>
</form>
whereas on radio button would look like the following in this example:
{
id: 1,
name: 'value1'
}
In the form there is a change event, from which we pick up the chosen radio button value.
(change)="changeValue(radioForm.value)"
Then I would just play with boolean and the value chosen:
changeValue(val) {
this.valueChosen = true; // shows div
this.chosenVal = val.name; // here we have the value chosen
}
A plunker to play with: here
Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});
Can anyone tell me how can i load a listbox from a selected item of a dropdownlist?
Let's say i have a dropdownlist that contain "option1=male" & "option2=female"
I want that when male is selected, a list of male employees is shown in a listbox.
Added note:
i want to know how can i do this if employees names are saved in a file / data base?
Is this what you're after?
Selecting from a dropdown box a specific option will trigger an ajax call for a specific json file. On success, we display file's content into a listbox. This is just a demo.
Code sample:
$(document).ready(function() {
var listbox = $('#listbox'),
populateListbox = function(data) {
for (var i = 0, item; i < data.length; i++) {
item = data[i];
var option = $('<option>').val(item.age).text(item.name);
listbox.append(option);
}
showListbox();
},
emptyListBox = function() {
listbox.empty();
},
showListbox = function() {
listbox.removeClass('hide');
},
hideListbox = function() {
listbox.addClass('hide');
};
$('#dropdown').on('change', function (e) {
emptyListBox();
hideListbox();
var selectedOption = $("option:selected", this),
selectedValue = this.value;
switch (selectedValue) {
case 'male':
$.getJSON( "male.json", populateListbox);
break;
case 'female':
$.getJSON( "female.json", populateListbox);
break;
}
});
});
I gather that you want it to populate another listbox asynchronously? What you would need to do to achieve this is to use JavaScript and to call a function when the document loads. For example
$(document).ready(function(){
exampleFucntion();
});
This will call the function "exampleFunction" when the document loads. Inside this function the following code can be put where #dropdownbox would be the ID of your HTML drop down box.
$("#dropdownbox").change(exampleOnDropDownChanged);
This again will call a function that performs an action everytime the index of the drop down box changes. Inside the called function is where you would put the code to create another dropdown box dynamically with the details of male or female employees (or just populate an existing dropdown). Within the function you could put 'if' statements to get the male or female employees and then carry out the corresponding code to populate the dropdown. This function could also call a PHP page which could retrieve data and then populate the drop down.
The way I have described doesn't require the HTML page to be refreshed. I also suggest that you read around JavaScript and AJAX and also basic techniques, such as populating dropdown boxes.
I think this is what you are looking for. DEMO HERE
Select your gender and shows relative listbox.
<form id="survey" action="#" method="post">
<div id="section1">
<label for="Gender">Select employee gender.</label>
<select id="Gender" onchange="selection(this);">
<option value="Gender">---Select---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div id="section2" style="display:none;">Please select employee gender from above.</div>
<div id="section3" style="display:none;">Male Employees
<br />
<label for="Jim">Jim</label>
<input type="radio" id="Jim" />
<label for="Tom">Tom</label>
<input type="radio" id="Tom" />
<label for="Sam">Sam</label>
<input type="radio" id="Sam" />
</div>
<div id="section4" style="display:none;">Female Employees<br />
<label for="Kate">Kate</label>
<input type="radio" id="Kate" />
<label for="Claire">Claire</label>
<input type="radio" id="Claire" />
<label for="Sue">Sue</label>
<input type="radio" id="Sue" />
</div>
</form>
<script>
var sections = {
'Gender': 'section2',
'Male': 'section3',
'Female': 'section4'
};
var selection = function (select) {
for (var i in sections)
document.getElementById(sections[i]).style.display = "none";
document.getElementById(sections[select.value]).style.display = "block";
};
</script>