How to know if a checkbox or radio button is checked in Dart? - checkbox

I have a checkbox and a radio button group and I want to know if the checkbox is checked and which radio button is selected.
How do I do this in dart?

Let's say we have your HTML with something like this:
<form >
<input type="radio" name="gender" id="gender_male" value="male">Male<br>
<input type="radio" name="gender" id="gender_female" value="female">Female
</form>
<form>
<input type="checkbox" id="baconLover">I like bacon<br>
</form>
Your Dart code to obtain their values would be something like the following, I also added an event to know when the checkbox is clicked.
import 'dart:html';
void main() {
// Adds a click event when the checkbox is clicked
query("#baconLover").on.click.add((MouseEvent evt) {
InputElement baconCheckbox = evt.target;
if (baconCheckbox.checked) {
print("The user likes bacon");
} else {
print("The user does not like bacon");
}
});
// Adds a click event for each radio button in the group with name "gender"
queryAll('[name="gender"]').forEach((InputElement radioButton) {
radioButton.onclick.listen((e) {
InputElement clicked = e.target;
print("The user is ${clicked.value}");
});
});
}

I found this solution for radio button, where catch event by "html" ... I have used this solution into my project.
my_example.html
<polymer-element name="my-example">
<template>
<div on-change="{{updateRadios}}">
Your favorite color is:
<div>
<label for="red">Red <input name="color" type="radio" id="red" value="red"></label>
</div>
<div>
<label for="green">Green <input name="color" type="radio" id="green" value="green"></label>
</div>
<div>
<label for="blue">Blue <input name="color" type="radio" id="blue" value="blue"></label>
</div>
</div>
<div>
You selected {{favoriteColor}}
</div>
</template>
<script type="application/dart" src="my_example.dart"></script>
</polymer-element>
my_example.dart
import 'package:polymer/polymer.dart';
import 'dart:html';
#CustomTag('my-example')
class MyExample extends PolymerElement {
#observable String favoriteColor = '';
MyExample.created() : super.created();
void updateRadios(Event e, var detail, Node target) {
favoriteColor = (e.target as InputElement).value;
}
}

Related

React - problems with checkbox

I am trying to create a component with four options. The user is supposed to choose only one option. So if the user chooses another option, the previosluy selected ones should change to false. This is my code:
const riddles_ = [{
id:2,
options: ['A grandson','A daughter','A father','A nephew'],
state_: [false,false,false,false]
}]
function toggleToDo(o){
riddles_.state_ = [false,false,false,false]
riddles_.state_[o] = true
console.log(riddles_.state_)
}
return (
<div>
<input type="checkbox" id="check1" checked={riddles_.state_[0]} onClick={(o)=>toggleToDo(0)}/>
{riddles_.options[0]}
<div className='space'></div>
<input type="checkbox" id="check2" checked={riddles_.state_[1]} onClick={(o)=>toggleToDo(1)}/>
{riddles_.options[1]}
<div className='space'></div>
<input type="checkbox" id="check3" checked={riddles_.state_[2]} onClick={(o)=>toggleToDo(2)}/>
{riddles_.options[2]}
<div className='space'></div>
<input type="checkbox" id="check4" checked={riddles_.state_[3]} onClick={(o)=>toggleToDo(3)}/>
{riddles_.options[3]}
</div>
)
}
When the user clicks on a checkbox, it just turns true or false, and generates no change in the others. I know the riddles_.state_ array is changing but the checkbox donĀ“t seem to be able to take its value.
Its a best practice to use set method frome useState hooks when u work with state, using react functional components.
Example :
const init_state = [false,false,false,false]
const [checked_state, setCheckedState] = useState(init_state);
function toggleToDo(o){
const current_state = [false,false,false,false]
current_state[o] = true;
setCheckedState(current_state);
}
return (
<div>
<input type="checkbox" checked={checked_state[0]} onClick={(o)=>toggleToDo(0)}/>
option1
<div className='space'></div>
<input type="checkbox" checked={checked_state[1]} onClick={(o)=>toggleToDo(1)}/>
option2
<div className='space'></div>
<input type="checkbox" checked={checked_state[2]} onClick={(o)=>toggleToDo(2)}/>
option3
<div className='space'></div>
<input type="checkbox" checked={checked_state[3]} onClick={(o)=>toggleToDo(3)}/>
option4
</div>
)
}

How can I do event on text box in Angular?

I have a text box that show when I click on checkbox and I need to make an event on it that can make me bind it to object from DB
HTML:
<div ng-repeat="feture in featureEnumArray">
<input id="txtchkFet" type="checkbox" ng-model="feture.IsChecked" />
{{feture.DisplayText}}
<div ng-show="feture.IsChecked" >
<input class="form-control" type="text" ng-model="feture.Value" ng-change="getFeatureID(feture)" id="txtValue" placeholder="Type Feature Value" />
</div>
<div class="label label-danger" ng-show="feture.IsChecked && !feture.Value">
Type Value
</div>
</div>
And in Angular controller I did Like this :
$scope.getFeatureID = function (feture) {
if (feture.IsChecked) {
$scope.Planfeature = angular.copy(feture);
$scope.PlanFeatureTemp.FeatureID = $scope.Planfeature.ID;
$scope.PlanFeatureTemp.Value = $scope.Planfeature.Value;
$scope.Planfeature = [];
}
else {
var index = $scope.JAdminPlan.PlanFeatureValues.indexOf(feture);
$scope.JAdminPlan.PlanFeatureValues.splice(index, 1);
}
if (!$scope.$$phase) $scope.$apply();
};

How to get selected radio value using Bootstrap radio button groups and AngularJS

I'm using Bootstrap radio button groups and am having a hard time getting the selected value into my controller. I have a small snippet of JS to set the selection on which button was clicked:
$(document).ready(function() {
$('form .btn-group label').on('click', function() {
$(this).find('input').prop('checked', true);
});
});
Here is example HTML:
<form name="add-form" ng-submit="addFavorites()" novalidate>
<div class="form-group">
<label class="control-label">Color</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn">
<input type="radio" name="color" value="red" class="form-control" ng-model="favorites.color" ng-required="true">Red
</label>
<label class="btn">
<input type="radio" name="color" value="blue" class="form-control" ng-model="favorites.color" ng-required="true">Blue
</label>
</div>
</div>
</form>
Now when I submit this with ng-submit to this function, I do not get any console logged values for my radio buttons.
$scope.addFavorites = function() {
angular.forEach($scope.favorites, function(value, key) {
console.log(key, value);
});
};
What am I doing wrong?
You do not need this code:
(document).ready(function() {
$('form .btn-group label').on('click', function() {
$(this).find('input').prop('checked', true);
});
});
Your radio button is wrapped with its label so HTML5 will propagate click from the label to the radio.
Initialize your $scope.favorites object to {}
That is it, in submit you can get your $scope.favorites object with all its arguments.
Plunker: http://plnkr.co/edit/OatdIsvCUBSniHHQFyxG?p=preview

Get the value of checkbox using ref in React

is there any way to get value of checkbox using ref in React. Normal way return always value "on" to me.
var MyForm = React.createClass({
save: function(){
console.log(this.refs.check_me.value);
},
render: function(){
return <div><h1>MyForm</h1>
<div className="checkbox">
<label>
<input type="checkbox" ref="check_me" /> Check me out
</label>
</div>
<button className="btn btn-default" onClick={this.save}>Submit</button>
</div>
}
});
For checkbox, use "checked" instead of "value":
var MyForm = React.createClass({
save: function () {
console.log(this.refs.check_me.checked);
},
render: function () {
return <div><h1>MyForm</h1>
<div className="checkbox">
<label>
<input type="checkbox" ref="check_me" /> Check me out
</label>
</div>
<button className="btn btn-default" onClick={this.save}>Submit</button>
</div>
}
});
As a result:
There is a classic way to catch the event and corresponding values with the help of:
event.target.checked, event.target.name
You can see an example:
class MyForm extends React.Component {
onChangeFavorite(event){
console.log(event.target.checked, event.target.name);
};
render(){
return (<div><h1>MyForm</h1>
<div className="checkbox">
<label>
<input type="checkbox" name="myCheckBox1"
onChange={this.onChangeFavorite}
defaultChecked={false} />
Check me out
</label>
</div>
<button className="btn btn-default" onClick={this.save}>Submit</button>
</div>)
};
};
You can make the checkbox a controlled element by listening to onChange and giving it a state value. Try the following:
var MyForm = React.createClass({
save: function(){
console.log(this.refs.check_me.value);
},
toggleCheckboxValue: () => {
this.setState({checkBoxValue: !this.state.checkboxValue});
},
render: function(){
return <div><h1>MyForm</h1>
<div className="checkbox">
<label>
<input type="checkbox" ref="check_me" value={this.state.checkboxValue} onChange={this.toggleCheckboxValue} /> Check me out
</label>
</div>
<button className="btn btn-default" onClick={this.save}>Submit</button>
</div>
}
});
whenever the checkbox is clicked it will run the toggleCheckboxValue function, which will toggle the value of this.state.checkboxValue.
Just don't forget to initialize the this.state.checkboxValue function in your code.
Note: As ivarni pointed out, you may want to control the checked value specifically for checkboxes rather than value. Though both solutions will work.
I'm not sure why you want it using ref specifically, but it can be done nativily:
import React from 'react';
function CheckBox() {
const [isSave, setIsSave] = React.useState(false);
const handler = (value) => {
console.log(value);
setIsSave(value);
};
return (
<div>
<input type="checkbox" onChange={(ev) => handler(ev.target.checked)} />
<label> Save me..</label>
</div>
);
}
export default CheckBox;

Angular directive for horizontal Bootstrap form

I'm trying to build a directive for my Angular to help with the integration of form fields. I've implemented Scott Allens solution from his Angular playbook, and it works fine for a normal stacked form.
I need however to adapt it to a horizontal form instead. Here's my code:
Markup
<div form-group>
<label for="name">Name</label>
<input type="text" id="name" ng-model="vm.name">
</div>
formGroup directive
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
var label = element.querySelector("label");
label.classList.add("control-label");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
}
element.classList.add("form-group");
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
The output becomes:
<div form-group="" class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
And that's fine for stacked form. Since I need a horizontal form, my output needs to look like this:
<div form-group="" class="form-group">
<label for="name" class="control-label col-sm-3">Name</label>
<div class="col-sm-9">
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
</div>
I've tried many solutions and I can get it work with single elements like an input, textarea or a select. It becomes much more tricky when I have something like two radio buttons inside my markup like this:
<div form-group>
<label>Active</label>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
The desired output of the above mentioned code should be:
<div form-group class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
</div>
Please notice that the input(s) in the form-group is not fixed. It can be either a single input, textarea, select, a group of radio buttons or checkboxes. I'm lost for how I can make that happen. Any help is appreciated. Thanks!
UPDATE
I made some small changes to Mark Veenstra's code to make it (sort of) working:
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label", "col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
angular.element(input).wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelector("div[class='radio']");
angular.element(div_radio).wrap(angular.element('<div class="col-sm-9"></div>'));
}
This does not work completely as intended with multiple radio inputs since it only wraps the <div> on the first radio input element.
The output from radio button example in my original post using Marks code is:
<div form-group="" class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active" value="true"> Yes
</label>
</div>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active" value="false"> No
</label>
</div>
</div>
SOLUTION
Check out the Plunker with the final result: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview
In the angular.element documentation you can find the method wrap() to be able to wrap HTML around a selected element. Or see this direct link.
So what you could do in your directive is change the setupDom() function to match your requirements per type of form element.
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
input.wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelectorAll("div[class='radio']");
div_radio.wrap(angular.element('<div class="col-sm-9"></div>'));
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
NOTE: This code is not tested, maybe there are some minor mistakes, but I guess you'll get the point now.
Mark's suggestion came close, but it didn't solve my problem completely. I ended up using the following code in my formGroup directive:
(function (module) {
"use strict";
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var children = angular.element(element).children();
var labels = children.splice(0, 1);
// Set label classes
labels[0].classList.add("control-label", "col-sm-3");
// Wrap children in div
angular.element(children).wrapAll(angular.element("<div class='col-sm-9'></div>"));
// Handle inputs
var inputs = element.querySelectorAll("input, textarea, select");
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i],
type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox") {
input.classList.add("form-control");
}
}
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
module.directive("formGroup", formGroup);
}(angular.module("app.core")));
Check out this Plunker to see it in action: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview

Resources