Usng Vue.js to push dynamically created inputs to an array - javascript

What would the best process be to push dynamically created inputs to an array. Ideally I would like an array in the data like.
customer_answers: [1,4,5,6,8]
The items in the array being the values of the answers. I understand that each answer would need to be pushed and probably use on:change to run a a method.
However how would I identify each question where the questions and answers and dynamic?
The questions code is below:
<div v-for="(question, item) in questions.questions">
{{question.question}}
<div v-if="grouped_answers">
<div v-for="a in grouped_answers[item].answers">
<label>{{a.answer}}</label>
<div v-if= "question.type === 'radio'">
<input type="radio" v-bind:value="a.id">
</div>
<div v-if= "question.type === 'checkbox'">
<input type="checkbox" v-bind:value="a.id">
</div>
</div>
</div>
</div>
The full code if it helps is below:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div v-for="app in appliances">
<input type="radio" id="one" v-model="appliance" v-bind:value="app.id" v-on:change="getQuestions">
<label for="one">{{app.appliance}}</label>
</div>
<br>
<span>Picked: {{appliance}}</span>
</br>
</br>
<div v-for="co in brands">
<input type="radio" id="two" v-model="brand" v-bind:value="co.id">
<label for="one">{{co.brand}}</label>
</div>
<span>Picked: {{ brand }}</span>
</br>
</br>
<input type="radio" id="one" value=1 v-model="age">
<label for="one">1 Year</label>
<br>
<input type="radio" id="two" value=2 v-model="age">
<label for="two">2 Years</label>
<br>
<input type="radio" id="two" value=3 v-model="age">
<label for="two">3 Years</label>
<br>
<input type="radio" id="two" value=4 v-model="age">
<label for="two">4 Years</label>
<br>
<input type="radio" id="two" value=5 v-model="age">
<label for="two">5 Years</label>
<br>
<input type="radio" id="two" value=6 v-model="age">
<label for="two">6 Years</label>
<br>
<input type="radio" id="two" value=7+ v-model="age">
<label for="two">7+ Years</label>
<br>
<span>Picked: {{ age }}</span>
<br>
<br>
<div v-for="(question, item) in questions.questions">
{{question.question}}
<div v-if="grouped_answers">
<div v-for="a in grouped_answers[item].answers">
<label>{{a.answer}}</label>
<div v-if= "question.type === 'radio'">
<input type="radio" v-bind:value="a.id">
</div>
<div v-if= "question.type === 'checkbox'">
<input type="checkbox" v-bind:value="a.id">
</div>
</div>
</div>
</div>
<br>
<br>
<br>
<br>
<input v-model="first_name" placeholder="First Name">
<p>First Name is: {{ first_name }}</p>
<input v-model="last_name" placeholder="Last Name">
<p>Last Name is: {{ last_name }}</p>
<input v-model="phone_number" placeholder="Phone Number">
<p>Phone Number is: {{ phone_number }}</p>
<input v-model="email" placeholder="Email">
<p>Email is: {{ email }}</p>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
mounted() {
console.log('Component ready.');
console.log(JSON.parse(this.a));
console.log(JSON.parse(this.b));
this.appliances = JSON.parse(this.a);
this.brands = JSON.parse(this.b);
},
props: ['a','b'],
data: function() {
return {
appliances: '',
appliance: '',
brands: '',
brand: '',
age: '',
first_name: '',
last_name: '',
phone_number: '',
email: '',
questions: '',
answers: '',
result: '',
grouped_answers:'',
customer_answers: [],
}
},
methods: {
incrementItem: function(item) {return item + 1},
getQuestions: function (){
console.log(this.appliance);
var self = this;
axios.get('/get_questions/' + this.appliance, {
})
.then(function(response) {
console.log(response.data);
self.questions = response.data;
self.getAnswers();
})
.catch(function(error) {
console.log(error);
});
},
getAnswers: function (){
console.log(this.appliance);
var self = this;
axios.get('/get_answers/' + this.appliance, {
})
.then(function(response) {
console.log(response.data);
self.answers = response.data;
self.putAnswers();
})
.catch(function(error) {
console.log(error);
});
},
putAnswers: function (){
var result = {};
for (var i = 0; i < this.answers.answers.length; i++) {
var question_id = this.answers.answers[i].question_id;
console.log(question_id);
if(!result[question_id]) {
result[question_id] = {question_id: question_id, answers: []};
}
result[question_id].answers.push({
id: this.answers.answers[i].id,
question_id: question_id,
answer: this.answers.answers[i].answer})
}
result = Object.keys(result).map(function (key) { return result[key]; });
console.log(result);
this.grouped_answers = result;
console.log(this.grouped_answers[0].answers);
},
},
}
</script>
UPDATE
nextQuestion: function (){
this.holding_answers = [];
},
saveAnswer (question, groupedAnswerItem, value, type, event) {
console.log(value);
console.log(type);
if(type === "radio"){
this.holding_answers = [];
this.holding_answers.push(value);
};
if(type === "checkbox"){
this.holding_answers.push(value);
};
},
<div v-for="(question, item) in questions.questions">
{{question.question}}
<div v-bind:id="item">
<div v-if="grouped_answers">
<div v-for="a in grouped_answers[item].answers">
<label>{{a.answer}}
<input #change="saveAnswer(question, grouped_answers[item], a.id, question.type)" :type="question.type" :value="a.id" :name="a.question_id">
</div>
</div>
</div>
<button #click="nextQuestion()">Next</button>
</div>

I simply use on:change="findAnswers" and then a Javascript event
methods: {
findAnswers: function(e) {
console.log(e.target.value);
},
}
Before pushing to a data array.

A couple of notes first:
You can remove the v-if for checkbox or radio and use a dynamic type like, :type="question.type"
Try to set the initial data as the possible real type, like grouped_answers shouldn't be an Array instead of String ?
Ok, so if I understand correctly, you want to save the the correct answer in the right question ? You should consider use the '#change' or '#click' with a function that gets the data that you need as parameter.
For example:
<input #change="saveAnswer(question, grouped_answers[item], a.id)" :type="question.type" :value="a.id">
saveAnswer:
saveAnswer (question, groupedAnswerItem, value, event) {...}
That's a general idea, not the implementation, the point is that you can pass the dynamically data as parameter and change as you want. Usually this is the way to go, pass all the information necessary in your function to achieve the change with that data. Inside the function you have access to your data, that should make things easier.

Related

VueJS Input Binding for dynamic radio buttons

I am trying to render several radio buttons with dynamic data.
Users can create markets and then products and unlock these products for each market and give more properties. Among other things, radio buttons should be available for this purpose.
I've tried:
<div v-for="market in markets" :key="market.id">
<div>
<span>{{ market.name }}</span>
</div>
<div>
<div v-for="(field, index) in market.market_fields" :key="index">
<label :for="field.name">{{field.label}}</label>
<div v-if="field.type != 'radio'"><input :type="field.type" v-model="field.value"></div>
<div>
<input type="radio" :name="field.name" :value="true" v-model="field.value">
<label :for="field.name">ja</label><br>
<input type="radio" :name="field.name" :value="false" v-model="field.value">
<label :for="field.name">nein</label><br>
</div>
</div>
</div>
</div>
The problem seems to be with the v-model because the selection of a radio button is only ever for one market.
for example:
I click a radio button for market1, then the radio button is checked, but if I select the same radio button for market2, it is no longer checked for market1.
EDIT:
For every market the radio buttons had the same name attribute (field.name). So i changed it to market.name_field_name
Try to add index to input id :id="field.name + index":
const { ref } = Vue
const app = Vue.createApp({
data() {
const markets = ref(
[{market_fields: [{id:1, name:'market1', label: 'aaa', value: '', type: 'radio'}, {id:2, name:'market1', label: 'bbb', value: '', type: 'radio'}, {id:3, name:'market2', label: 'ccc', value: '', type: 'radio'}]}]
)
return {
markets
}
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="market in markets" :key="market.id">
<div>
<span>{{ market.name }}</span>
</div>
<div>
<div v-for="(field, index) in market.market_fields" :key="index">
<label :for="field.name">{{field.label}}</label>
<div v-if="field.type != 'radio'">
<input :type="field.type" v-model="field.value">
</div>
<div>
<input type="radio" :id="field.name + index + 'ja'" :value="true" v-model="field.value">
<label :for="field.name + index + 'ja'">ja</label><br>
<input type="radio" :id="field.name + index + 'nein'" :value="false" v-model="field.value">
<label :for="field.name + index + 'nein'">nein</label><br>
</div>
</div>
</div>
</div>
{{ markets }}
</div>

how to set value form input vue js from json

please have a problem here. I want to display the value from the input form: name and position. but the data is in the form of json.
{"id":5,"name":"the name","pos":"the position"}
This is template html vue js
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
Edit <b>{{name}}</b>
</div>
<div class="card-body">
<form #submit="edit()" method="post" onclick="return false">
<div class="form-group">
<label for="">Name</label>
<input v-model="input.nameInput" type="text" value="?" autocomplete="off" class="form-control">
</div>
<div class="form-group">
<label for="">Position</label>
<input v-model="input.posInput" value="?" type="text" autocomplete="off" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Edit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
And this is java script of template file vue js
<script>
export default {
data(){
return{
name:'',
pos:'',
input:{
nameInput:'',
posInput:''
}
}
},
methods:{
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.data.name;
this.pos = response.data.pos;
});
},
edit(){
axios.put('/employes_api/'+this.$route.params.id, {
name: this.name,
pos: this.position,
}).then(response => {
this.$route.employe;
});
}
},
mounted(){
this.getEmploye();
}
}
</script>
Thanks for your help.
As described in your question, if the data received is
{"id":5,"name":"the name","pos":"the position"}
then you getEmploye method should be :
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.name;
this.pos = response.pos;
});
On element’s value, you may use the following to display data you have received from the api:
value=“{{name}}”
That means you are getting the value from name data.
Also, to test if that works, you may assign first a dummy data/value to name.
You don't need to make two separate variables one for the inputs and the other for the display, just keep the same variable for both, it will be automatically updated on the display and in the inputs while the user is typing, that's the beauty of Vue.
So instead of
data(){
return{
name:'',
pos:'',
input:{
nameInput:'',
posInput:''
}
}
},
Just keep
data(){
return{
name:'',
pos:''
}
},
For the template inputs use :
<input v-model="name" type="text" autocomplete="off" class="form-control">
...
<input v-model="pos" type="text" autocomplete="off" class="form-control">
The overall result should look like this :
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
Edit <b>{{name}}</b>
</div>
<div class="card-body">
<form #submit="edit()" method="post">
<div class="form-group">
<label for="">Name</label>
<input v-model="name" type="text" autocomplete="off" class="form-control">
</div>
<div class="form-group">
<label for="">Position</label>
<input v-model="position" type="text" autocomplete="off" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Edit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
name:'',
pos:''
}
},
methods:{
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.data.name;
this.pos = response.data.pos;
});
},
edit(){
axios.put('/employes_api/'+this.$route.params.id, {
name: this.name,
pos: this.pos,
}).then(response => {
this.$route.employe;
});
}
},
created(){
this.getEmploye();
}
}
Ps : Didn't test the code, if there is any error just let me know
Use :value=“name”, e.g <input :value="name"/>.

[Vue warn]: Error in nextTick: "TypeError: Cannot read property 'key' of undefined"

I am fairly new to Vue (and using Vue components in particular), and I can't figure out what i'm doing wrong here. Essentially I have a signup wizard (using vue-good-wizard) which if the user never clicks the back button works fine, but if at some point they click back I get the error message described in the title. I think it has something to do with the following template being rendered a second time:
<template>
<div class="playerSelectionBox">
<table style="width:100%">
<tr v-for="i in 10" track-by="$index">
<td>Row: {{i}}</td>
<td><player-entry-box></player-entry-box></td>
</tr>
</table>
</div>
</template>
Here is the code for the template from the player-entry-box component:
<template>
<div class="PlayerEntryBox">
<input class="numberBox" type="text" #blur="sendData" v-model="number" placeholder="#">
<input class="nameBox" type="text" #blur="sendData" v-model="playerName" placeholder="Player Name"><br>
</div>
</template>
My best guess is that something is happening when the code is rendered where the player-entry-box components inside of the v-for have something which conflicts with the others, but it works as expected the first time it is rendered. Is there something here I am doing wrong?
Any advice or insights into what I am missing would be great, thanks!
Other information:
All of the components are currently registered globally in the main.js file.
Here is the code for the wizard:
<div id="TeamWizard" v-if="isCreatingTeam" style="padding-top=100px;">
<vue-good-wizard
:steps="teamSteps"
:onNext="nextClickedTeam"
:onBack="backClickedTeam">
<div slot="teamPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="teamPage2">
<h4>Add Players</h4>
<h1></h1>
<player-selection-box></player-selection-box>
</div>
<div slot="teamPage3">
<h4>Step 3</h4>
<label class="myLabel">Team ID:</label>
<input type="text" v-model="teamID" placeholder="Team ID"><br>
<br>
<label class="myLabel">Team Token:</label>
<input type="text" v-model="teamToken" placeholder="Team Token"><br>
<br>
</div>
</vue-good-wizard>
</div>
Here is where I called this.$nextTick():
mounted () {
this.$nextTick(() => {
this.loggedInUser = firebase.auth().currentUser;
});
}
The following is from the main component :
<template>
<div class="hello">
<h1>{{ tkdSport }}</h1>
<div id="mainPage" v-if="!(isCreatingTeam || isCreatingPlayer)">
<div id="mySidenav" class="sidenav">
×
<img src="../assets/images/testUser.png" width="100px" height="100px">
About
Services
Clients
Contact
<div style="scroll">
<div v-for="i in 50">
<div style="margin=10px; color=red;"><p>Test {{ i }}</p></div>
</div>
</div>
</div>
<h1>{{ loggedInUser.email }}</h1>
<button #click="logout">Logout</button>
<button #click="openNav">Open Nav</button>
<br>
<br>
<br>
<br>
<br>
<button #click="showTeam">New Team Account</button>
<br>
<br>
<br>
<button #click="showPlayer">New Player Account</button>
</div>
<div v-else>
<div id="createTeam" v-if="isCreatingTeam">
<h1>TEAM</h1>
<br>
</div>
<div id="createPlayer" v-if="isCreatingPlayer">
<h1>PLAYER</h1>
</div>
<div id="PlayerWizard" v-if="isCreatingPlayer" style="padding-top=100px;">
<div>
<vue-good-wizard
:steps="playerSteps"
:onNext="nextClickedPlayer"
:onBack="backClickedPlayer">
<div slot="playerPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="playerPage2">
<h4>Add Players</h4>
<h1>Player Selection will go here</h1>
</div>
</vue-good-wizard>
</div>
</div>
<div id="TeamWizard" v-if="isCreatingTeam" style="padding-top=100px;">
<vue-good-wizard
:steps="teamSteps"
:onNext="nextClickedTeam"
:onBack="backClickedTeam">
<div slot="teamPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="teamPage2">
<h4>Add Players</h4>
<h1></h1>
<player-selection-box></player-selection-box>
</div>
<div slot="teamPage3">
<h4>Step 3</h4>
<label class="myLabel">Team ID:</label>
<input type="text" v-model="teamID" placeholder="Team ID"><br>
<br>
<label class="myLabel">Team Token:</label>
<input type="text" v-model="teamToken" placeholder="Team Token"><br>
<br>
</div>
</vue-good-wizard>
</div>
</div>
</div>
</template>
<script>
import firebase from 'firebase';
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
loggedInUser: '',
teamName: '',
teamToken: '',
teamID: '',
playerName: '',
tkdSport: 'basketball',
isCreatingPlayer: false,
isCreatingTeam: false,
playerSteps: [
{
label: 'Name and Sport',
slot: 'playerPage1',
},
{
label: 'Link (OPTIONAL)',
slot: 'playerPage2',
}
],
teamSteps: [
{
label: 'Name and Sport',
slot: 'teamPage1',
},
{
label: 'Add Players',
slot: 'teamPage2',
},
{
label: 'Setup Linking (OPTIONAL)',
slot: 'teamPage3',
}
]
}
},
mounted () {
this.$nextTick(() => {
this.loggedInUser = firebase.auth().currentUser;
});
},
methods: {
logout: function() {
firebase.auth().signOut().then(() => {
this.$router.replace('login')
})
},
openNav: function() {
document.getElementById("mySidenav").style.width = "250px";
},
closeNav: function() {
document.getElementById("mySidenav").style.width = "0";
},
showTeam: function() {
this.isCreatingTeam = true
this.isCreatingPlayer = false
},
hideCreating: function() {
this.isCreatingTeam = false
this.isCreatingPlayer = false
},
showPlayer: function() {
this.isCreatingPlayer = true
this.isCreatingTeam = false
},
onComplete: function() {
alert('Yay. Done!');
},
nextClickedPlayer(currentPage) {
console.log('next clicked', currentPage)
if(currentPage==1){
this.hideCreating()
}
return true; //return false if you want to prevent moving to next page
},
backClickedPlayer(currentPage) {
console.log('back clicked', currentPage);
return true; //return false if you want to prevent moving to previous page
},
nextClickedTeam(currentPage) {
console.log('next clicked', currentPage)
if(currentPage==2){
this.hideCreating()
}
return true; //return false if you want to prevent moving to next page
},
backClickedTeam(currentPage) {
console.log('back clicked', currentPage);
return true; //return false if you want to prevent moving to previous page
}
}
}
</script>
The user logs in from a separate Login Component, and then gets routed to this component, I just need to have access to the user object within this component.
Here is the stack trace:
Error stack trace

Auto populate dropdown fields doesn't work

I have 2 drop down fields which both auto populated.
Example :
car_model -> dropdown_field1
car_model_variants -> dropdown_field2
When I select a model in car_model field, car_model_variants must update its values.
In my case, I have index.php where you can click a button that will show the modal box and you'll find the auto populated drop down fields.
First attempt, when selecting a car_model it works the car_model_variants field is updating its values. But it doesn't work if I submit a form when car_model_variants is empty, If I try to select a car_model again? the dropdown 2 field is not updating. Below is my code.
(function ($) {
$('.edit').formPopup({
'modalParams': {
'parent_container': $('div.autodeal')
},
'callback': function (settings)
{
$('.modal')
.addClass('large')
.css({'z-index': 101});
$('#used_car_car_model').change(function () {
var select = $(this);
$.ajax({
'url': '{{ path("autodeal_backend_filter_select") }}',
'data': {'carModelId': select.val(), 'carGuideOnly': 0, 'isVerified': 1, 'showCompleteName': 1},
success: function (html)
{
$('#used_car_car_model_variant').html(html);
}
});
});
},
'formSubmitParams': {
'retainFormUrl': false,
'submit_callback': function ()
{
window.location.reload();
},
'error_callback': function (form, settings)
{
$('.close, .exit', $(settings.container))
.click(function () {
window.location.reload();
});
}
}
});
})(jQuery);
Here's the full code.
<form novalidate="" action="/app_dev.php/used-car-listings/164/edit" method="POST">
<div class="marginbottom row gutters">
<div class="col span_12">
<div>
<div>
<label for="used_car_plate_number" class="required">Plate number</label>
<input type="text" id="used_car_plate_number" name="used_car[plate_number]" required="required" value="GS0909">
</div>
<div>
<label for="used_car_year" class="required">Year</label>
<input type="text" id="used_car_year" name="used_car[year]" required="required" value="2015">
</div>
<div>
<label for="used_car_car_model" class="required">Car Model</label>
<select id="used_car_car_model" name="used_car[car_model]" required="required">
<option value="">Select A Model</option><option value="102">Mercedes-Benz A-Class</option><option value="401" selected="selected">Mercedes-Benz AMG</option><option value="103">Mercedes-Benz B-Class</option><option value="105">Mercedes-Benz C-Class Coupe</option><option value="104">Mercedes-Benz C-Class Sedan</option><option value="115">Mercedes-Benz CLA-Class</option><option value="576">Mercedes-Benz CLC-Class</option><option value="577">Mercedes-Benz CLK-Class</option><option value="106">Mercedes-Benz CLS-Class</option><option value="107">Mercedes-Benz E-Class</option><option value="578">Mercedes-Benz G-Class</option><option value="108">Mercedes-Benz GL-Class</option><option value="109">Mercedes-Benz GLK-Class</option><option value="110">Mercedes-Benz M-Class</option><option value="111">Mercedes-Benz S-Class</option><option value="112">Mercedes-Benz SL-Class</option><option value="113">Mercedes-Benz SLK-Class</option><option value="114">Mercedes-Benz SLS-Class</option><option value="579">Mercedes-Benz Viano</option></select>
</div>
<div>
<label for="used_car_car_model_variant" class="required">Car Model Variant</label>
<select id="used_car_car_model_variant" name="used_car[car_model_variant]" required="required"><option value="">Select Mercedes-Benz A-Class Variant</option><option value="343">2014 Mercedes-Benz A-Class A 250 Sport 4MATIC</option><option value="344">2014 Mercedes-Benz A-Class A 45 AMG</option></select>
</div>
<div>
<label for="used_car_mileage" class="required">Mileage</label>
<input type="text" id="used_car_mileage" name="used_car[mileage]" required="required" value="1700">
</div>
<div>
<label for="used_car_price" class="required">Price</label>
<input type="text" id="used_car_price" name="used_car[price]" required="required" value="3288300">
</div>
<div>
<label for="used_car_used_car_color" class="required">Color</label>
<select id="used_car_used_car_color" name="used_car[used_car_color]" required="required">
<option value="">Select A Color</option><option value="1">Red</option><option value="2">Blue</option><option value="3">Black</option><option value="4">White</option><option value="5">Green</option><option value="6">Silver</option><option value="7" selected="selected">Grey</option><option value="8">Yellow</option><option value="9">Brown</option><option value="10">Beige</option><option value="11">Orange</option><option value="12">Purple</option><option value="13">Pink</option><option value="14">Turquoise</option><option value="15">Bronze</option></select>
</div>
<div>
<label for="used_car_description" class="required">Description</label>
<textarea id="used_car_description" name="used_car[description]" required="required" cols="4" rows="3">Body color, Tenorite Gray</textarea>
</div>
<div>
<label class="required">City</label>
<input type="hidden" id="used_car_city_id" name="used_car[city][id]" value="20"><input type="text" id="used_car_city_text" name="used_car[city][text]" required="required" autocomplete="off" value="San Juan, Metro Manila">
</div>
<div>
<label class="required">Is service record submitted</label>
<div id="used_car_is_service_record_submitted"><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_0" name="used_car[is_service_record_submitted]" required="required" value="1">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_1" name="used_car[is_service_record_submitted]" required="required" value="0" checked="checked">No</label></div>
</div>
<div>
<label class="required">Is LTO verified</label>
<div id="used_car_is_lto_verified"><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_0" name="used_car[is_lto_verified]" required="required" value="1" checked="checked">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_1" name="used_car[is_lto_verified]" required="required" value="0">No
</label></div>
</div>
<div>
</div>
</div>
<input type="hidden" id="used_car__token" name="used_car[_token]" value="4e4UOHBr5SmtV7Pb0WoWv4xSz90LoVarNG8hw0dy_RY"> <hr class="nomargin marginbottom30 margintop20">
<div class="row">
<button type="submit" class="button">Save</button>
</div>
</form>

Clear form after submit

I am submitting a form - and adding the contents to an array, however whenever the item is added to the array, it is still bound to the form.
I would like to add the item, clear the form. Something like jquery's reset();
Here's my template:
<div class="col-xs-12" ng-controller="ResourceController">
<div class="col-md-4">
<h3>Name</h3>
</div>
<div class="col-md-8">
<h3>Description</h3>
</div>
<form class="form-inline" role="form" ng-repeat="item in resources">
<div class="form-group col-md-4">
<input type="text" class="form-control" value="{{ item.name }}"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" value="{{ item.description }}"/>
</div>
</form>
<form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
<div class="form-group col-md-4">
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-default">Add</button>
</div>
</form>
</div>
And my controller:
(function(){
var app = angular.module('event-resources', []);
app.controller('ResourceController', function($scope){
$scope.addResource = function(){
$scope.resources.push(this);
}
var defaultForm = {
name : '',
description: ''
};
$scope.resources = [
{
name: 'Beer',
description: 'Kokanee'
},
{
name: 'Pucks',
description: 'Black Round Things'
}
]
});
})();
Use angular.copy() to copy the item data to the resources array, and then you can safely clear the item data. The angular.copy() makes a deep copy of the object, which is what you want.
Alternately, here is a simpler method, which doesn't use any extra method calls:
$scope.addResource = function() {
$scope.resources.push({
name: $scope.name, // recreate object manually (cheap for simple objects)
description: $scope.description
});
$scope.name = ""; // clear the values.
$scope.description = "";
};
$scope.addResource = function(){
$scope.resources.push(angular.copy(this));
$scope.name="";
$scope.description=""
}
Push the copy to the resources array and change name and description back to ""

Categories

Resources