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;
Related
I want to create a simple form using react. So I though I go with the onSubmit function of the form element, but as it turns out I don't get the form data. data of my handleSubmit function is empty. Why is that?
There is a fiddle that works: https://jsfiddle.net/everdimension/5ry2wdaa/ I don't see the difference.
export default function App() {
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const data = new FormData(e.target);
console.log('do the submitting', data)
}
return (
<div className="App">
<form onSubmit={handleSubmit}>
<label>
Media Plan
<input type="text" name="media-plan" placeholder="Media Plan" required />
</label>
<fieldset>
<legend>Time span selection</legend>
<label>
Start date
<input type="date" name="start-date" required />
</label>
<label>
End date
<input type="date" name="end-date" required />
</label>
</fieldset>
<fieldset id="submit">
<legend>Send options</legend>
<button type="submit" name="copy">
Copy plan
</button>
<button type="submit" name="save">
Save plan
</button>
</fieldset>
</form>
</div>
)
}
I had to read them this way, the formData object only appears empty.
const formData = new FormData(e.target)
for (var value of formData.values()) {
console.log(value);
}
I'm trying to write (two) multiple selected options using two handle change functions, I don't think it's not a good practice, in that two selected options I have to bind that data separately without disturbing the other multiple selected option.
import React, { Component } from 'react';
class AddEvent extends Component {
constructor() {
super();
this.state = {
speaker: [''],
hash_tag: ['']
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
var options = event.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.setState({ value: value });
}
handleChange(event2) {
var options2 = event2.target.options;
var value2 = [];
for (var j = 0, l = options2.length; j < l; j++) {
if (options2[j].selected) {
value2.push(options2[j].value);
}
}
this.setState({ value: value2 });
}
render() {
return (
<div className="col-md-12">
<h3>Add Events</h3>
<form onSubmit={this.handleSubmit}>
<div className="col-md-6">
<div className="form-group">
<label>Event Speaker:</label>
<select
data-style="btn-default"
className="form-control"
multiple
data-max-options="3"
value={this.state.value}
onChange={this.handleChange}
>
<option value="Vivek Srinivasan">Vivek Srinivasan</option>
<option value="Salma Moosa">Salma Moosa</option>
<option value="Rengaprasad">Rengaprasad</option>
</select>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<label>Event Hash Tags:</label>
<select
data-style="btn-default"
className="form-control"
multiple
data-max-options="3"
value={this.state.value}
onChange={this.handleChange2}
>
<option value="hash_tag_1">hash_tag_1</option>
<option value="hash_tag_2">hash_tag_2</option>
<option value="hash_tag_3">hash_tag_3</option>
<option value="hash_tag_4">hash_tag_4</option>
<option value="hash_tag_5">hash_tag_4</option>
</select>
</div>
</div>
<div className="col-md-12">
<div className="form-group">
<label>Event Content</label>
<textarea
id="summernote"
value="Type Here "
onChange={val => this.setState({ content: val.target.value })}
/>
</div>
</div>
<div className="col-md-3">
<button className="btn btn-block btn-primary btn-lg" type="submit">
Save Event
</button>
</div>
</form>
</div>
);
}
}
export default AddEvent;
I don't quite understand why you don't want to use different handlers for each select element. Especially since you've already written two handler functions. Perhaps I've misunderstood your question.
You got three main problems, as I see it.
1) You can't have two functions with the same name, as you do with handleChange.
2) In your current code, you're referencing a function that doesn't exist (handleChange2).
3) In both handleChange functions, you're overriding the value property in the state with the other, as both are changing the property value in the state.
Renaming the latter handleChange function to handleChange2 would solve problems 1 and 2.
The third problem would be solved by having two value properties in your state, e.g. value1 and value2 (though I would suggest using more descriptive names).
View 1:
<div ng-controller="ctrl1">
<button ng-click="goToExtendedForm({'name':'aaa'})">
</button>
</div>
ctrl1:
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
$state.go('view2');
console.log(e); // prints updated value
};
View 2:
<div ng-controller="ctrl1">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
</div>
But the input box is always empty, even though to get to the view the goToForm() is called. Why doesn't it update the HTML value?
Views are changed with ui.router's $state.
From your description, your code is supposed to work. Check if you are passing the right parameter into the function. Here is a working demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="goToForm({'name':'aaa'})">Change</button>
<br>
<input type="text" ng-model="selectedList.name" ng-readonly="true" />
</div>
Try adding $scope.$apply() at the end of your $scope.goToForm function
Try this ;
HTML Code
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
<button ng-click="goToForm(testUserDetails)" >Go To</button>
</button>
</div>
</div>
Define controller like this;
function ClickToEditCtrl($scope) {
$scope.selectedList = {
name: ""
};
$scope.testUserDetails ={
name: "nimal"
}
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
}
I have a div which renders on a boolean condition triggered by a button.
I have multiple select options in the new div. The problem is just the first works and others dont.
Code Snippet:
var Results = React.createClass({
getInitialState: function(){
return {
partname:[],
moveOptions: false,
fromLocation:'',
toLocation:'',
moveQuantity:0
}
},
componentWillMount:function(){
var partInfo = [];
var count = 0;
//ajax calls to get partInfo
this.setState({
partInfo:partInfo
});
},
showMoveOptions: function(){
this.setState({moveOptions:!this.state.moveOptions});
},
movePart: function(){
//ajax call
},
handleQuantityChange: function(e){
this.setState({
moveQuantity:e.target.value
});
},
handleFromChange: function(e){
this.setState({
fromLocation:e.target.value
});
},
handleToChange: function(e){
this.setState({
toLocation:e.target.value
});
},
render: function() {
var partInfo = this.state.partInfo;
return(
<div>
<div id="results">
<br/>
<div className="col-sm-6">
<h3>Part Name :{this.props.partname}</h3>
<div className="container">
{
partInfo.map(function(l){
return([
<div>
<h3>Building: {l.building}</h3>
<h3>Location: {l.location}</h3>
<h3>Quantity: {l.qty}</h3>
</div>
]);
}.bind(this))
}
</div>
</div>
<div className="col-sm-6">
<button type="button" onClick={() => this.showMoveOptions()}>Move</button>
</div>
</div>
{ this.state.moveOptions ?
<div>
<div>
<h3>From: </h3>
<select onChange={this.handleFromChange.bind(this)}>
partInfo.map(function(from){
return(
<option value={from.location}>{from.location}</option>
)
}
</select><br/>
<h3>To: </h3>
<select onChange={this.handleToChange.bind(this)} >
partInfo.map(function(to){
return(
<option value={to.location}>{to.location}</option>
)
}
</select><br/>
<h3>Quantity:</h3>
<input type="text" name="quantity" value={this.state.moveQuantity} onChange={this.handleQuantityChange.bind(this)}/>
</div>
<div>
<button type="button" onClick={() => this.movePart()}>Submit</button>
</div>
</div> : null
}
</div>
);
}
});
As shown in the code the first select tag works. After that all tags are rendered but i neither can select the drop down menu nor i can change text in input tag.
You should handle onChange event to update controlled input.
Check the documentation here
A controlled <input> has a value prop. Rendering a controlled <input> will reflect the value of the value prop.
and
User input will have no effect on the rendered element
I've made a fiddle with your code. You have lost some brackets in your snippet, and you should not bind handlers to this when using React.createClass syntax. But the rest is working just fine.
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;
}
}