Make checkbox field mandatory using React - reactjs

I want to make the checkbox field mandatory to select atleast 1 using react js.
Below is my code:
renderCheckboxes() {
const { zones_to_render_to_render, filter } = this.state;
console.log(zones_to_render_to_render, filter)
return zones_to_render_to_render
.filter(checkbox =>
filter === 'ALL' ||
filter === 'CHECKED' && checkbox.checked ||
filter === 'UNCHECKED' && !checkbox.checked
)
.map((checkbox, index) =>
// console.log(checkbox, index)
<div key={index}>
<label>
<input
type="checkbox"
checked={checkbox.checked}
onChange={this.toggleCheckbox.bind(index)}
/>
{checkbox.zone_name}
</label>
</div>
);
}
Any help would be appreciated...

Please add a required property to the checkbox.
required="required"
And wrap the input boxes into a form element. Define an onSubmit handler to the form which can make an ajax call with the input filled data.
More references here
Reactjs - Form input validation

You can use Required property it is used to set or return whether the input checkbox field should be checked or not before submitting the form.
for more details check https://www.geeksforgeeks.org/html-dom-input-checkbox-required-property/
<form >
<input
type="checkbox"
checked={checkbox.checked}
onChange={this.toggleCheckbox.bind(index)}
required="required"
/>
</form >

Related

URL search parameters gets replaced - Remix Run

I'm working on a search UI where I have quite a few filters which I want as URL parameters when someone selects/checks the options. I've used the technique as advised on the Remix.run docs to come up with multiple forms within the filters. Each time a group of Filters gets submitted, the selected old parameters get disappeared. Heres my code,
<Panel header="Status" key="status">
<Form
name="search"
action='/search'
method="get"
onChange={(e) => submit(e.currentTarget, { replace: false })}
>
<ul>
<li>
<Checkbox
name="status"
value="buy_now"
defaultChecked={status.includes('buy_now')}
>
Buy Now
</Checkbox>
</li>
<li>
<Checkbox
name="status"
value="on_auction"
defaultChecked={status.includes('on_auction')}
>
On Auction
</Checkbox>
</li>
</ul>
</Form>
</Panel>
<Panel header="Price" key="price">
<Form name="search" action='/search' method="get">
<Select
name="blockchain"
value={
blockchain
? options.filter((a) => a.value === blockchain)
: undefined
}
options={options}
placeholder="Blockchain"
type="white"
/>
<div className="d-flex align-center price">
<TextInput
value={min ? min : undefined}
name="min"
placeholder="Min"
/>
<span>to</span>
<TextInput
value={max ? max : undefined}
name="max"
placeholder="Max"
/>
</div>
<button
onClick={(e) => {
e.stopPropagation()
submit(e.currentTarget, { replace: false })
}}
className="btn primary-btn btn-lg w-100"
>
Apply
</button>
</Form>
</Panel>
How Can I get around this to have all the parameters without having to manage them on my own using React state?
Edit:- I want the first filter to be submitted automatically and the latter to be submitted on a button click.
Bit of a UI of what I'm trying to achieve,
Answer: After investing enough time to look through for shortcuts, finally understood that it's not one of the magic that remix.run does. use something like formik and update the state imparatively.
When you submit a form, the only values included are the one under the submitted form. The values from any other form are not included (fortunately!).
So I'd use a single Form with all the inputs under it (checkboxes as well as text inputs).
Then instead of a onChange on the Form, you can add something like an onChange handler on the checkboxes and submit the form inside imperatively (using a ref click on the submit button or something, I think using a ref on the form you need to submit all values in the submit function so a button ref click may be simpler).
Keep in mind that if you want to "restore" the field values after submitting, you need to return them from the loader function like this:
// Loader function
const url = new URL(request.url);
return {
results: [...],
values: Object.fromEntries(url.searchParams.entries())
};
Then in the component, use values from useLoaderData:
<input type="text" name="max" defaultValue={values.max || ""}/>
Added benefit: if you come back to this page (by clicking browser back for example), your search parameters and search results are still there!
I actually put up a stackblitz for you but I lost all my changes :(
It seems like you could just keep all fields in a single form and submit that form when the submit button is pressed.
Then onChange, check if the target's name is 'status', and submit the form anyway.
export default function App() {
const submit = (form) => {
form.submit();
};
return (
<form
name="search"
action="/search"
method="get"
onChange={(e) => {
if (e.target.name === "status") {
submit(e.currentTarget);
}
}}
>
<fieldset>
<legend>status</legend>
<label>
<input type="checkbox" name="status" value="buy_now" />
buy_now
</label>
<label>
<input type="checkbox" name="status" value="on_auction" />
on_auction
</label>
</fieldset>
<fieldset>
<legend>price</legend>
<label>
<div>blockchain</div>
<select name="blockchain">
<option value="option_1">Blockchain Option 1</option>
<option value="option_2">Blockchain Option 2</option>
</select>
</label>
<label>
min <input type="number" name="min" />
</label>
<label>
max <input type="number" name="max" />
</label>
</fieldset>
<button type="submit">Apply</button>
</form>
);
}
demo
Note: not sure what your motivation is to want to separate this into separate forms, but I think the magic you're referring to is that server state, URLSearchParams, FormData and UI are all aligned because they are using the same underlying data using only common web APIs.

React validation on multiple checkboxes

anyone can point me to an example of a react multiple checkboxes validation? I have some questions, every one of them has a checkbox when it's done and when all are checked, a continue button must be activated.. I know how to do this with only one checkbox, but don't know how to handle more of them. I would rather do this in plain react and not by installing any package. Any help will be appreciated.
You can control all your inputs using useState. Example for two inputs.
import React, { useState } from "react"
const ControlledCheckboxes = () => {
const [ firstCheckbox, setFirstCheckbox ] = useState(false);
const [ secondCheckbox, setSecondCheckbox ] = useState(false);
return(
<form>
<div >
<div className="form-check">
<input type="checkbox" id="first" className="form-check-input"
onClick={()=>setFirstCheckbox(!firstCheckbox)}
value={firstCheckbox}
/>
<label className="form-check-label" htmlFor="first">FIRST</label>
</div>
<div className="form-check">
<input type="checkbox" id="second" className="form-check-input"
onClick={()=>setSecondCheckbox(!secondCheckbox)}
value={secondCheckbox}
/>
<label className="form-check-label" htmlFor="second">SECOND</label>
</div>
</div>
<button type="submit" className="btn btn-outline-success" disabled={ !(firstCheckbox && secondCheckbox) } >SUBMIT</button>
</form>
)
};
You can achieve this by using controlled inputs.
Basically you would make the value of the checkboxes correspond to variables in the state of your component. After that it is as simple as if (boolean1 && boolean2) with a conditionally rendered save button.
Controlled inputs
Conditional rendering
You can achieve most of what you want with just HTML.
<form>
<input type="checkbox" required />
<input type="checkbox" required />
<button>submit</button>
</form>
The form cannot be submitted until all checkboxes are checked.
Let's say that's not enough, you want to access the form validity in your render logic to apply styles or whatever so you need component state.
const [valid, setValid] = useState(false);
All form control change events bubble up to their form (unless explicitly stopped). We can spy on form control changes by adding a change event listener that updates component state to the form element.
event => setValid(event.target.form.checkValidity())
If your form isn't as simple as my example and you need to specifically check certain checkboxes you can find all form controls in event.target.form.elements. You can use the elements property to not even need HTML form validation.
event => setValid(Array.from(event.target.form.elements).every(
input => input.type !== 'checkbox' || input.checked
))
You can then pass valid as a prop to your submit button.

set ng-model to null on disabled an input

new in angular here.
I have an input field disabled base on the radio button, if the radio button was selected, I first want the input field value to null and then disabled it.
Here is my current example:
<input type="radio" ng-model="vm.radio" value="selected" /> Sample
<input type="text" ng-model="vm.input" ng-disabled="vm.radio='selected'" />
When input have the value, it just disabled and keep the input value.
I can do check inside the controller like
if(vm.radio=='selected') { vm.input = null }
But it only work when I active the function via the button. Is there any good way to handle it at HTML page, on the change event? Not in a controller script.
take a look at this plnkr: https://plnkr.co/edit/IygRaPlBmLzdnI0jhAQn?p=preview
You can use ng-change specifying an expression
<input type="radio" ng-model="vm.radio" value="selected" ng-change="vm.radio === 'selected' ? vm.input = '' : '' " /> Sample
<input type="radio" ng-model="vm.radio" value="b" /> Sample2
<input type="text" ng-model="vm.input" ng-disabled="vm.radio === 'selected'" />

Checkboxes group and only one required, in AngularJs

I have checkbox group:
<div class="checkbox">
<input type="checkbox" name="zainteresowany1" ng-model="zainteresowany1">Stażem
</div>
<div class="checkbox">
<input type="checkbox" name="zainteresowany2" ng-model="zainteresowany2">Pracą
</div>
And I would like to validate form if nothing checkbox is selected.
If nothing is selected: form is invaild.
How to make?
Make the ng-model attribute the same for both checkboxes and set the value attribute for what value you want each to have when that checkbox is selected. Then you can validate the form by making sure the variable you use for ng-model is not undefined.
Example:
<div class="checkbox">
<input type="checkbox" name="zainteresowany1" ng-model="zainteresowany" value="foo" /> Stażem
</div>
<div class="checkbox">
<input type="checkbox" name="zainteresowany2" ng-model="zainteresowany" value="bar" /> Pracą
</div>
Then in your controller:
if (!$scope.zainteresowany) {
// Form is invalid
} else {
// Form is valid
var value = $scope.zainteresowany;
}
Anyone have other solution ? '
I want to validate form and IF ANY CHECKBOX is selected i want to make form $inval

angularjs additional form validation rules (not input field validation)

What's the angular way to add validation rules to a form, that do not belong to a single input field, but on multiple field values together?
E.g.:
Check if at least one of x checkboxes is checked
Check if the sum of multiple number inputs is equal to a given Number
...
It would be nice if the errors can be shown with ng-messages. I'm using angular 1.3.10.
There's no built-in functionality, but it requires little effort.
ng-messages does not depend on anything specific. It just needs an object whose keys can be referenced by ng-message. The simplest solution would be to hook into the submit event (which you probably do anyway) and run additional validation.
<form ng-submit="post()" name="myForm">
<input type="checkbox" name="one" ng-model="one" />
<input type="checkbox" name="two" ng-model="two" />
<input type="submit" />
<div ng-messages="formErrors">
<p ng-message="tooMany">Please, check one checkbox only</p>
<p ng-message="required">Please, check a checkbox</p>
</div>
</form>
On submission the function post() is called which adds any error to the object formErrors:
$scope.post = function() {
...
var hasErrors = false;
$scope.formErrors = {
};
if ($scope.one && $scope.two) {
$scope.formErrors.tooMany = hasErrors = true;
}
if (!$scope.one && !$scope.two) {
$scope.formErrors.required hasErrors = true;
}
if (hasErrors) {
return;
}
}

Resources