make the checkbox single choice - javascript

I want to apply this code on vuejs
I replaced onclick by #click but it doesn't work!
ps: I'm beginner on vuejs
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">

A basic approach to the question you stated:
new Vue({
el: "#app",
data() {
return {
checkboxes: [{
checked: false
},
{
checked: false
},
{
checked: false
},
{
checked: false
},
]
}
},
methods: {
onChange(cb) {
this.checkboxes = this.checkboxes.map(checkbox => ({ checked: cb == checkbox }))
},
},
template: `
<div>
<div
v-for="(checkbox, i) in checkboxes"
:key="i"
>
<input
type="checkbox"
:checked="checkbox.checked"
#change="() => onChange(checkbox)"
/>
{{ checkbox.checked }}
</div>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Related

Delete updated v-model checkbox property in vuejs

I have a input checkbox tag which I'm trying to delete after it has been updated in my v-model please how can I go about this.
This is my input tag:
<input
v-model="checked"
type="checkbox"
id=""
value="jackets"
>
I get the v-model value property by doing this
{{checked}}
Please how can I add a delete function to my v-model property in which if I click on the delete function the checkbox would be unchecked.
If I understood you correctly try like following snippet (just set your checked property to false):
new Vue({
el: '#demo',
data() {
return {
checked: true,
filters: [{name: 'XXL', state: false}, {name: 'Grey', state: false}]
}
},
methods: {
del() {
this.filters.forEach(f => f.state = false)
},
rem(i) {
this.filters[i].state = false
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div v-for="(filter, i) in filters" :key="i">
{{ filter.name }}
<input
v-model="filter.state"
type="checkbox"
id=""
:value="filter.name"
/>
<button #click="rem(i)">X</button>
</div>
Remove All
<input
type="checkbox"
id=""
#input="del"
/>
</div>

How to display selected checkbox value in Vuejs?

Reference link https://jsfiddle.net/8xom729c/
<div class="checkbox-alignment-form-filter">
<input type="checkbox" id="HR 3502 : 2004" class="vh-product" value="HR 3502 : 2004" v-model="checkboxestwo[0]" v-on:click="checkAlltwo()" />
<label class="productlist-specific" for="HR 3502 : 2004">HR 3502 : 2004</label
>
</div>
<div class="checkbox-alignment-form-filter7">
<input
type="checkbox"
id="E250A2"
class="vh-product"
v-model="checkboxestwo[1]"
value="E250A"
/>
<label class="productlist-specific" for="E250A2">E250A</label>
</div>
How to print selected checkbox value, I mean like when i click on any checkbox value, I need to display the selected value.
Is there any alternative way of doing it in vuejs.
Can anyone please give some inputs. Thanks
In spite of being usingv-model you can use click event as the code below #click="checkedInput. But the elegant solution is using v-model.If you need additional filtering before selecting a checkbox. You can use this type of click event
let vue = new Vue({
el: '#app',
data: {
checkedNames: [],
checkedName: true,
close: false
},
methods: {
uncheck: function(checkedName) {
this.checkedNames = this.checkedNames.filter(name => name !== checkedName);
this.$refs[checkedName.toLowerCase()].checked = false
},
uncheckall: function(event) {
this.checkedNames.forEach(e => this.$refs[e.toLowerCase()].checked = false)
this.checkedNames = [];
},
mouseOver: function() {
this.close = true;
},
mouseOut: function() {
this.close = false;
},
checkedInput(event) {
if (this.checkedNames.includes(event.target.value)) {
this.uncheck(event.target.value)
} else {
this.checkedNames.push(event.target.value)
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<div id='app'>
<ul class="checkboxes">
<li><input type="checkbox" ref="jack" value="Jack" #click="checkedInput">
<label for="jack">Jack</label></li>
<li><input type="checkbox" ref="john" value="John" #click="checkedInput">
<label for="john">John</label></li>
<li><input type="checkbox" ref="mike" value="Mike" #click="checkedInput">
<label for="mike">Mike</label></li>
</ul>
<br/>
<ul class="tags">
<li #mouseover="mouseOver" #mouseleave="mouseOut" #click="uncheck(checkedName)" class="badge badge-pill badge-primary" v-for="checkedName in checkedNames">
{{ checkedName }}<span v-show="close" aria-hidden="true">×</span>
</li>
<li class="badge badge-pill badge-danger" #mouseover="mouseOver" #mouseleave="mouseOut" #click="uncheckall" v-show="checkedNames != ''">Clear</li>
</ul>
</div>

Vue can't check the recently unchecked, checkbox even its binding

I have a list of checkboxes, I want when I click on input 4th all previous boxes being checked and the rest unchecked.
I almost did it, but there is an issue that when I back to the those checked boxes and uncheck one of them, its still okay and the next being unchecked, but when again going forward and check another one from those unchecked the recently unchecked item being still unchecked and not changed.
here is the demo, and I think the GIF will describe my issue better.
Demo https://jsfiddle.net/j5dpkut8/1/
<script src="https://unpkg.com/vue"></script>
<div id="app">
<input type="checkbox" v-model="checked[0]" value="0" #change="printState(0)"> checked 0 <br>
<input type="checkbox" v-model="checked[1]" value="1" #change="printState(1)"> checked 1 <br>
<input type="checkbox" v-model="checked[2]" value="2" #change="printState(2)"> checked 2 <br>
<input type="checkbox" v-model="checked[3]" value="3" #change="printState(3)"> checked 3 <br>
<input type="checkbox" v-model="checked[4]" value="4" #change="printState(4)"> checked 4 <br>
<input type="checkbox" v-model="checked[5]" value="5" #change="printState(5)"> checked 5 <br>
<input type="checkbox" v-model="checked[6]" value="6" #change="printState(6)"> checked 6 <br>
<input type="checkbox" v-model="checked[7]" value="7" #change="printState(7)"> checked 7 <br>
</div>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
checked: [
false,false,false,false,false,false,false,false,
],
},
methods: {
printState(x) {
this.checked = [
false,
false,
false,
false,
false,
false,
false,
false,
],
for (let i = 1; i < this.checked.length; i++) {
if (i <= x) {
this.checked[i] = true;
}
}
console.log(this.checked);
},
}
})
In your code change change handler into click handler and all will be okey.
Or.
new Vue({
el: '#app',
data: {
checked: [
{ state: false },
{ state: false },
{ state: false },
{ state: false },
{ state: false },
{ state: false },
{ state: false },
{ state: false },
],
},
methods: {
printState(x) {
for (let i = 0; i < this.checked.length; i++) {
this.checked[i].state = i <= x ? true : false;
}
},
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div v-for="(n, index) in checked" :key="index">
<input
type="checkbox"
v-model="n.state"
#click="printState(index)"
>
<span>checked {{ index }} {{ n.state }}</span>
</div>
</div>
As #TigranAbrahamyan mentioned, #click will fix it. But here is a solution in very few lines that also uses v-model and value as intended and lets you easily adjust the number of boxes.
new Vue({
el: "#app",
data: () => ({ num: 10, values: [] }),
methods: {
mark(index) {
this.values = [...Array(index).keys()];
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="index in num" :key="index-1">
<input type="checkbox" v-model="values" :value="index-1" #click="mark(index-1)" />
</div>
</div>

Check-all stops working when I add v-model attribute to the checkboxes

Check-all feature stops working when I try to get value of each checkbox in an array using v-model. I read lot of questions on different portals including stackoverflow, people are saying that v-model doesn't work with :checked attribute which I understand but could not find a solution / alternate code to make it work.
The 1st code that I tried was to select all checkboxes using the 1st checkbox. This works well. Code below:
new Vue({
el: "#app",
data: {
selectAll:false
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3">
Item 3
</label>
</div>
The 2nd code that I tried was to get value of each checkbox in an array but in this case 'select all' automatically stops working. Code below:
new Vue({
el: "#app",
data: {
selectAll:false,
eachCheckbox: [],
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1" v-model="eachCheckbox">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2" v-model="eachCheckbox">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3" v-model="eachCheckbox">
Item 3
</label>
<br>
Selected checkbox values: {{eachCheckbox}}
</div>
I don't know how to make this work. Can someone help please?
Use Vue.set to create objects in the checkbox array once an API call completes.
This shows a simulated async api call which takes 2.5 seconds to complete.
new Vue({
el: '#app',
data () {
return {
loading: false,
checkall: false,
checkboxes: []
}
},
methods: {
toggleAll () {
this.checkall = !this.checkall
this.checkboxes.forEach(c => {
c.checked = this.checkall
})
}
},
watch: {
checkboxes: {
deep: true,
handler: function () {
this.checkall = this.checkboxes.every(c => c.checked)
}
}
},
mounted () {
// simulate an async api call which takes 2.5 seconds to complete
this.loading = true
setTimeout(() => {
Array.from(Array(3), (c, i) => ({ checked: false, text: `Option ${i + 1}` })).forEach((c, i) => {
Vue.set(this.checkboxes, i, c)
})
this.loading = false
}, 2500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="checkbox" #click="toggleAll" v-model="checkall"/> Check All<br/>
<div v-for="(c, i) in checkboxes" :key="i">
<input type="checkbox" v-model="c.checked"/>{{ c.text }}<br/>
</div>
<p v-if="!loading">Checked: {{ checkboxes.filter(c => c.checked).map(c => c.text).join(',') }}</p>
<p v-else>Fetching data...</p>
</div>
i had faced the same problem before and i didn't find a good solution, but i had tried something like the following :
new Vue({
el: "#app",
data: {
selectAll: false,
eachCheckbox: [],
},
methods: {
selectAllItems() {
this.selectAll ? this.eachCheckbox = ["Item 1", "Item 2", "Item 3"] : this.eachCheckbox = [];
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll" #change="selectAllItems">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1" v-model="eachCheckbox">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2" v-model="eachCheckbox">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3" v-model="eachCheckbox">
Item 3
</label>
<br> Selected checkbox values: {{eachCheckbox}}
</div>

In react, how do select/checked the radio buttons?

I am not able to click or select on any of my radio buttons. Can someone help me out how to work with radio buttons in react?
I tried removing e.preventDefault() but that didn't help either.
Here's what my code looks like:
File 1:
this.state = {
fields: {
gender: ''
}
}
fieldChange(field, value) {
this.setState(update(this.state, { fields: { [field]: { $set: value } } }));
}
<Form
fields={this.state.fields}
onChange={this.fieldChange.bind(this)}
onValid={() => handleSubmit(this.state.fields)}
onInvalid={() => console.log('Error!')}
/>
File 2:
render() {
const { fields, onChange, onValid, onInvalid, $field, $validation } = this.props;
return (
{/* Gender */}
<div id={styles.genderField} className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label className="col-sm-2 control-label">Gender:</label>
<div className="col-sm-10">
<label className="radio-inline">
<input type="radio" name="gender" id="male"
checked={fields.gender === "Male"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Male
</label>
<label className="radio-inline">
<input type="radio" name="gender" id="female"
checked={fields.gender === "Female"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Female
</label>
</div>
</div>
<div className={`modal-footer ${styles.modalFooter}`}>
<button
className={`btn btn-primary text-white ${styles.saveBtn}`}
onClick={e => {
e.preventDefault();
this.props.$submit(onValid, onInvalid);
}}
>
Save
</button>
</div>
)
}
That's not how the docs handle onChange events. https://reactjs.org/docs/handling-events.html
You need to provide the full code to be able to help with that particular component.
Check out this working example: https://stackblitz.com/edit/react-radiobtns
class App extends Component {
constructor(props) {
super(props);
this.state = {selectedOption: 'option1'};
// This binding is necessary to make `this` work in the callback
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(changeEvent) {
this.setState({
selectedOption: changeEvent.target.value
});
}
render() {
return (
<form>
<label>
<input
onChange={this.handleOptionChange}
type="radio" value="option1"
checked={this.state.selectedOption === 'option1'}
name="radio1"/>
Option 1
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option2'}
type="radio"
value="option2"
name="radio1"/>
Option 2
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option3'}
type="radio"
value="option3"
name="radio1"/>
Option 3
</label>
</form>
);
}
}

Categories