vuejs3 - update computed value from v-model - javascript

I'm using vue-3
I am not familiar with vuejs and I am a newbie developer.
Situation
To add translations in batch on salesforce I wanted to code a tool.
I coded a webservice in rust which gets a json and turns it into a zip for salesforce.
The client provides me with data from a spreadsheet, and I have to format it in json to send it to my webervice.
I wanted to allow a copy / paste in a cell then split each line with "\ n" that I link to an input in order to edit the entry if necessary.
Problem
The input fill well with splited values, but if I change the input, the value in "computed" does not update. see image here
Questions
How can I update my value in my computed array with splited values ?
V-model update my input from the computed but not the reverse.
what is the best function to do this?
I saw that there is reactive but I do not know if this is the right solution.
Here my code
<template>
<div>
<label for="fr">fr</label>
<input type="checkbox" value="fr" id="fr" v-model="fr.state" />
<label for="en">en</label>
<input type="checkbox" value="en" id="en" v-model="en.state" />
<label for="it">it</label>
<input type="checkbox" value="it" id="it" v-model="it.state" />
<label for="es">es</label>
<input type="checkbox" value="es" id="es" v-model="es.state" />
<label for="german">german</label>
<input type="checkbox" value="german" id="german" v-model="german.state" />
</div>
{{ formated.fr }}
<div class="Array">
<table>
<thead>
<tr>
<th>The table header</th>
<th>default Value</th>
<th v-if="fr.state === true">fr</th>
<th v-if="en.state === true">en</th>
<th v-if="it.state === true">it</th>
<th v-if="es.state === true">es</th>
<th v-if="german.state === true">german</th>
</tr>
</thead>
<tbody>
<tr>
<td>C/C</td>
<td><textarea v-model="defaultentry" cols="40" /></td>
<td v-if="fr.state === true"><textarea v-model="fr.value" cols="40" /></td>
<td v-if="en.state === true"><textarea v-model="en.value" cols="40" /></td>
<td v-if="it.state === true"><textarea v-model="it.value" cols="40" /></td>
<td v-if="es.state === true"><textarea v-model="es.value" cols="40" /></td>
<td v-if="german.state === true">
<textarea v-model="german.value" cols="40" />
</td>
</tr>
<tr v-for="(entry, index) in formated.default" :key="index">
<td v-if="formated.default[index]">{{ index }}</td>
<td v-if="formated.default[index]">
<input type="text" v-model="formated.default[index]" />
</td>
<td v-if="formated.fr">
<input type="text" v-model="formated.fr[index]" />
</td>
<td v-if="formated.en">
<input type="text" v-model="formated.en[index]" />
</td>
<td v-if="formated.it">
<input type="text" v-model="formated.it[index]" />
</td>
<td v-if="formated.es">
<input type="text" v-model="formated.es[index]" />
</td>
<td v-if="formated.german">
<input type="text" v-model="formated.german[index]" />
</td>
</tr>
</tbody>
</table>
</div>
<script>
export default {
name: "Array",
entries: {},
data() {
return {
defaultentry: [],
fr: { state: false, value: [] },
en: { state: false, value: [] },
it: { state: false, value: [] },
es: { state: false, value: [] },
german: { state: false, value: [] },
};
},
computed: {
formated: function() {
let entries = {};
let base = this.defaultentry
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
let fr = this.fr.value
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
let en = this.en.value
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
let it = this.it.value
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
let es = this.es.value
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
let german = this.german.value
.toString()
.split("\n")
.map((x) => {
if (x.length > 40) {
return "error";
}
return x.trim();
});
entries.default = base;
if (this.fr.state == true) {
entries.fr = fr;
} else {
delete entries.fr;
}
if (this.en.state == true) {
entries.en = en;
} else {
delete entries.en;
}
if (this.it.state == true) {
entries.it = it;
} else {
delete entries.it;
}
if (this.es.state == true) {
entries.es = es;
} else {
delete entries.es;
}
if (this.german.state == true) {
entries.german = german;
} else {
delete entries.german;
}
return entries;
},
},
};
</script>
Thank you for your time and help

v-model works both ways, so it needs to get something and to set something. You have only defined a get computed property but not a set. You use formated like it is a data property.
So split the computed property in a get() and a set() method make this work.
See the documentation on how this works.

Related

How to pass a list of objects from view

So I'm dynamically creating sections for my objects, where the entered values would be passed to the controller, but I'm having trouble with indexing. Sometimes it works and I think the problem is with my jQuery code, where some some functions are asynchronous and the indexing gets skipped.
The form submit should return a list of KPIs with KPI value, Name and employeeGID. In this example it should return a List of 4 elements, but it returns only one, because it skips 1 and 2 and goes straight to 3
In View HTML code I just have this div to indicate the place to append sections:
<div id="criteriaSections">
</div>
Scripts:
var kpiCount = 0;
function createCriteriaSection(criteria) {
var criterias = #Html.Raw(Json.Serialize(Model.Criterias));
for (var i = 0; i < criterias.length; i++)
{
if (criterias[i].id == criteria.value)
{
var critID = criteria.value;
if (criterias[i].isIndividual)
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<table id="assignIndividualTable">
<thead>
<tr>
<th style="width:25%; text-align:center">
<label>Employee</label>
</th>
<th style="width: 65%; text-align: center">
<label>KPI Name</label>
</th>
<th style="width: 10%; text-align: center">
<label>Value</label>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
showIndividualCiteriaEmployees(critID);
}
else
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<div>
<label>KPI Name: <input type="text" name="KPI[${kpiCount}].Name" class="form-control" required></label>
<label>Value: <input type="text" name="KPI[${kpiCount}].Value" class="form-control" required></label>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
<input name="employeeGID[${kpiCount}]" class="form-control" value="" type="hidden"/>
</div>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
kpiCount++;
}
}
}
}
function showIndividualCiteriaEmployees(critID) {
var resultLength = 0;
$.post("/KPIs/GetFilteredUsers", { critID: critID }, function (result) {
resultLength = result.length;
var rows = "";
$.each(result, function (i, item) {
rows +=
`<tr>
<td style="width:20%; text-align:center">
<p>${item.text}</p>
<input name="employeeGID[${kpiCount + i}]" class="form-control" value="${item.value}" type="hidden"/>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
</td>
<td style="width:65%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Name" class="form-control" required/>
</td>
<td style="width:15%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Value" class="form-control" required/>
</td>
</tr>`;
kpiCount++;
});
$("#assignIndividualTable tbody").html(rows);
});
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Date,Name,Value,ID,CriteriaID,Employee")] List<KPI> KPI, List<string> employeeGID)
{
int? id = HttpContext.Session.GetInt32("ID");
if (ModelState.IsValid)
{
for (int i = 0; i < KPI.Count; i++)
{
KPI[i].ManagersId = id.GetValueOrDefault();
KPI[i].Criteria = await _context.Criterias.FirstOrDefaultAsync(x => x.ID == KPI[i].CriteriaID);
if (KPI[i].Criteria.IsIndividual)
{
KPI[i].EmployeeId = _context.Users.First(x => employeeGID[i] == x.GID).ID;
}
}
_context.AddRange(KPI);
await _context.SaveChangesAsync();
return Create();
}
return Create();
}

Sorting on a column in a table isn't working

I have a table displaying search results and I need to sort one of the columns alphabetically. When I click on a column I want the entries in that column to be sorted, but the method I implemented did not work. I also tried using Lodash's sortBy method but that still did not sort the column properly.
import React, { PropTypes, Component } from 'react';
import {
Panel,
Button,
Col,
PageHeader,
ControlLabel,
FormControl,
HelpBlock,
FormGroup,
Checkbox,
Form,
Radio,
InputGroup,
Glyphicon
} from 'react-bootstrap';
import FormControlFeedback from 'react-bootstrap/lib/FormControlFeedback';
import FormControlStatic from 'react-bootstrap/lib/FormControlStatic';
import InputGroupAddon from 'react-bootstrap/lib/InputGroupAddon';
class App extends Component {
constructor(props) {
super(props);
this.state = {
respData: []
};
this.handleSubmit = this.handleSubmit.bind(this
this.myFunction = this.myFunction.bind(this);
this.setArrow = this.setArrow.bind(this);
this.onSort = this.onSort.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
const arrayValue = [];
var i = 0;
console.log('Data from Form:', data);
for (let name of data.keys()) {
const input = form.elements[name];
const parserName = input.dataset.parse;
const parsedValue = data.get(name);
console.log('name', name);
console.log('parsedValue', parsedValue);
if (typeof parsedValue == 'undefined' || parsedValue == null) {
console.log('Not Undefined or Not Null');
arrayValue[i] = '';
data.set(name, arrayValue[i]);
} else {
data.set(name, parsedValue);
arrayValue[i] = parsedValue;
}
i = i + 1;
}
var response_data = '';
var response_jsonObj;
var txt = '';
var req = {
RequestString: [
{
field1: arrayValue[0],
field2: arrayValue[1],
field3: arrayValue[2],
field4: arrayValue[3],
field5: arrayValue[4],
field6: arrayValue[5],
field7: arrayValue[6],
field8: arrayValue[7],
field9: arrayValue[8],
field10: arrayValue[9],
field11: arrayValue[10],
field12: arrayValue[11],
field13: arrayValue[12]
}
]
};
console.log('req string :' + req);
fetch('API_URL', {
headers: {
Accept: 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type'
},
method: 'POST',
body: JSON.stringify(req)
})
.then(response => {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
// this.setState({respData: response.data});
response.text().then(data => {
console.log('Data in Console', data);
response_data = data;
console.log('Response Data', response_data);
response_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object', response_jsonObj);
});
})
.catch(error => this.setState({ error }));
}
myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById('search');
filter = input.value.toUpperCase();
console.log('input in searchFunction:', input);
console.log('filter in searchFunction:', filter);
table = document.getElementById('Search-Table');
console.log('table in searchFunction:', table);
tr = table.getElementsByTagName('tr');
console.log('tr in searchFunction:', tr);
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName('td')[0];
console.log('td in for before if:', tr);
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = '';
} else {
tr[i].style.display = 'none';
}
}
}
}
onSort = (column) => (e) => {
const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
const sortedData = this.state.respData.sort((a, b) => {
if (column === 'Field1') {
const nameA = a.Field1.toUpperCase(); // ignore upper and lowercase
const nameB = b.Field1.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}
});
if (direction === 'desc') {
sortedData.reverse();
}
this.setState({
respData: sortedData,
sort: {
direction,
column,
}
});
};
setArrow = (column,className) => {
let current_className = className;
if (this.state.sort.column === column) {
current_className += this.state.sort.direction === 'asc' ? ' asc' : ' desc';
}
console.log(current_className);
return current_className;
};
render() {
return (
<div id="SampleDiv">
<form onSubmit={this.handleSubmit}>
<table cellspacing="30">
<tr>
<td>
<FormGroup>
<ControlLabel>Field 1</ControlLabel>
<FormControl
id="field1"
name="field1"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 2</ControlLabel>
<FormControl
id="field2"
name="field2"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 3</ControlLabel>
<FormControl
id="field3"
name="field3"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup>
<ControlLabel>Field 4</ControlLabel>
<FormControl
id="field4"
name="field4"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 5</ControlLabel>
<FormControl
id="field5"
name="field5"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 6</ControlLabel>
<FormControl
id="field6"
name="field6"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup>
<ControlLabel>Field 7</ControlLabel>
<FormControl
id="field7"
name="field7"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 8</ControlLabel>
<FormControl
id="field8"
name="field8"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 9</ControlLabel>
<FormControl
id="field9"
name="field9"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup>
<ControlLabel>Field 10</ControlLabel>
<FormControl
id="field10"
name="field10"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 11</ControlLabel>
<FormControl
id="field11"
name="field11"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup>
<ControlLabel>Field 12</ControlLabel>
<FormControl
id="field12"
name="field12"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup>
<ControlLabel>Field 13</ControlLabel>
<FormControl
id="field13"
name="field13"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td />
<td>
<FormGroup>
<Button bsStyle="primary" type="submit">
Search{' '}
</Button>
{' '}
<Button bsStyle="primary" type="reset">
Clear{' '}
</Button>
</FormGroup>
</td>
</tr>
</table>
<div className="row ng-scope">
<div className="col-lg-15">
<Panel header={<span>Search Results</span>}>
<div
id="dataTables-example_filter"
className="dataTables_filter"
>
<label htmlFor={'search'}>
Search:
<input
type="search"
className="form-control input-sm"
placeholder=""
aria-controls="dataTables-example"
id="search"
onKeyUp={this.searchFunction}
/>
</label>
</div>
<div className="table-responsive">
<table
id="Search-Table"
className="table table-striped table-bordered table-hover"
>
<thead>
<tr>
<th className="sorting_asc" onClick={this.onSort('Field 1','asc')} aria-sort="ascending"
aria-label="Field1 :activate to sort column descending"
aria-controls="dataTables-example"
rowSpan="1"
colSpan="1"
tabIndex="0">Field 1
<span className={this.setArrow('Field 1')}></span>
</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
<th>Field 5</th>
<th>Field 6</th>
<th>Field 7</th>
<th>Field 8</th>
<th>Field 9</th>
<th>Field 10</th>
</tr>
</thead>
<tbody>
{this.state.respData.map((item, i) => {
return (
<tr key={i}>
<td> {item.Field1}</td>
<td> {item.Field2}</td>
<td> {item.Field3}</td>
<td> {item.Field4}</td>
<td> {item.Field5}</td>
<td> {item.Field6}</td>
<td> {item.Field7}</td>
<td> {item.Field8}</td>
<td> {item.Field9}</td>
<td> {item.Field10}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Panel>
</div>
</div>
</form>
</div>
);
}
}
export default App;
In your code
if (column === 'Field1') {
const nameA = a.Field1.toUpperCase(); // ignore upper and lowercase
const nameB = b.Field1.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}
You're comparing strings as if they were numbers. This is not the right way to compare strings in javascript.
You should use
if (column === 'Field1') {
return a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
}
You can read more about localeCompare on the MDN docs

Form not submitting after validation

Good evening,
I currently have a HTML Form with a script to validate the field have data entry into them however after it validating all fields are filled it doesnt submit, can anybody please advise what is wrong? New to this so learning and would really appreciate any help possible.
I have attached the code im using below.
<div id="form">
<form name="contact" method="post" action="contact.php" onsubmit="return !!(validatename()&validateemail()&validatecomments()&validateRecaptcha());">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
<script>
function validatename()
{
if( document.contact.name.value == "" )
{
alert( "Please provide your name!" );
document.contact.name.focus() ;
return false ;
}
}
function validateemail()
{
if( document.contact.email.value == "" )
{
alert( "Please provide your email address!" );
document.contact.email.focus() ;
return false ;
}
}
function validatecomments()
{
if( document.contact.comments.value == "" )
{
alert( "Please provide your comments!" );
document.contact.comments.focus() ;
return false ;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
}
</script>
This is one way how you could do it:
function validatename() {
if (document.contact.name.value == "") {
alert("Please provide your name!");
document.contact.name.focus();
return false;
}
else {
return true;
}
}
function validateemail() {
if (document.contact.email.value == "") {
alert("Please provide your email address!");
document.contact.email.focus();
return false;
}
else {
return true;
}
}
function validatecomments() {
if (document.contact.comments.value == "") {
alert("Please provide your comments!");
document.contact.comments.focus();
return false;
}
else {
return true;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
else {
return true;
}
}
document.getElementById('my-form').addEventListener('submit', function(e) {
e.preventDefault();
if (validatename() && validateemail() && validatecomments() && validateRecaptcha()) {
var formValidation = true;
}
else {
var formValidation = false;
}
if (formValidation) {
this.submit();
}
});
<div id="form">
<form id="my-form" name="contact" method="post" action="contact.php">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
</div>
To make it work correctly, make sure that grecaptcha is defined.

How to prevent insert a duplicate record in Angularjs

I am loading all records from a SQL db table using Angular and web API, what I am trying to do is to prevent the user from inserting a new record in Angular in case some of the data is duplicated with other records returned data, before going to the API.
How to raise an alert to notify and tension the user when press save that there are some fields are already exist like "code", "L_Desk", "A_Desc "with the loaded data from the table.
HTML:
<body ng-app="ContractT" ng-controller="crudController">
<br /><br />
<input type="checkbox" ng-model="Hide" />Hide <input type="button" value="Clear" ng-click="resetform()" />
<input type="submit" value="Save" ng-click="save()"/> <input type="button" value="Delete" ng-click="delete(selectedMember.sys_key)" />
<fieldset>
<legend>Contract Type</legend>
<table>
<tr>
<td>Code</td>
<td><input type="text" size="10" pattern="^[a-zA-Z0-9]+$" title="Alphnumeric" required autofocus ng-model="selectedMember.Code.Staff_Type_Code">
<input type="text" size="10" hidden ng-model="selectedMember.sys_key" /> </td>
</tr>
<tr>
<td>Latin Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Latin.L_Desc"></td>
</tr>
<tr>
<td>Local Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Local.A_Desc"></td>
</tr>
<tr>
<td>No. Of Houres Per Day</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Hours_Day"></td>
</tr>
<tr>
<td>No. Of Days Per Week(s)</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Days_Week"></td>
</tr>
<tr>
<td>End Of Contract By</td>
<td>
<select ng-model="selectedContract">
<option>Age</option>
<option>Number Of Years in Service</option>
</select>
</td>
</tr>
<tr>
<td>Number</td>
<td>
<input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Num_EndWork">
<select ng-model="selectedNumber">
<option >Months</option>
<option>Years</option>
</select>
</td>
</tr>
</table>
</fieldset>
<br />
<table border="1" ng-hide="Hide">
<thead>
<tr>
<!--<th>syskey</th>-->
<th>Code</th>
<th>Latin Description</th>
<th>Local Description</th>
<th>Hours_Day</th>
<th>Days_Week</th>
<th>Num_EndWork</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in Contracts | filter:selectedMember.Code | filter:selectedMember.Latin | filter:selectedMember.Local ">
<td style="display:none;">{{c.sys_key}}</td>
<td>{{c.Staff_Type_Code}}</td>
<td>{{c.L_Desc}}</td>
<td>{{c.A_Desc}}</td>
<td>{{c.Hours_Day}}</td>
<td>{{c.Days_Week}}</td>
<td>{{c.Num_EndWork}}</td>
</tr>
</tbody>
</table>
</form>
Controller :
contractT.controller('crudController', function ($scope, crudService)
{
loadrecords();
function loadrecords()
{
crudService.getContracts().then(function (response) {
$scope.Contracts = (response.data);
$scope.selectedMember = {};
console.log($scope.Contracts);
});
}
$scope.save = function () {
debugger;
if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 1,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Years')
{
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 2,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Number Of Years in Service' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 3,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 4,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
if (!$scope.selectedMember.sys_key) {
var promisePost = crudService.post(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
else
{
var promisePost = crudService.put(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
}
$scope.resetform = function () {
$scope.selectedMember = {};
//$scope.selectedMember = {};
//$scope.Local = {};
//$scope.Nhd = null;
//$scope.Ndw = null;
//$scope.Num = null;
}
$scope.selectedMember = { Code: "",sys_key:"", Latin:"" , Local:"", Hours_Day :"", Days_Week:"", Num_EndWork:"" }
$scope.showInEdit = function (member)
{
$scope.selectedMember = member;
//$scope.selectedMember.Code = member;
//$scope.selectedMember.Latin = member;
//$scope.selectedMember.Local = member;
//$scope.selectedMember.Hours_Day = member;
//$scope.selectedMember.Days_Week = member;
//$scope.selectedMember.Num_EndWork = member;
}
You can use filter here inorder to check for duplicates
var filtered= $filter('filter')($scope.contracts, function(value){
return value.Staff_Type_Code === Contract.Staff_Type_Code ;
});
if(filtered.length > 0){
console.log("duplicate exists");
}

the onblur and onsubmit function are not working could someone please help me out here

i am working on project using php,html,javascript. i am using on blur and onsubmit both the functions to provide dynamic kind of feel for errors. the following logic is working in every file except for this one .
The form functions like onsubmit and onblur are not working , i used an alert also to check but its not being called could someone please check and tell me where i am going wrong
<script language="Javascript">
//the flags are used to check if all the fields are filled and none is empty
var flag1;
var flag2;
var flag3;
function test(){
alert("fn called");
return true;
}
function fun1()
{
var donated_date=document.forms["myform"]["donated_date"];
if(donated_date==null||donated_date=="")
{
document.getElementById('ddate').innerHTML = "Choose the date of your last donation " ;
document.getElementById('ddate').style.display = "block" ;
flag1=false;
return false;
}
document.getElementById('ddate').style.display = "none" ;
flag1=true;
return true;
}
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
function fun3()
{
var hospital_name=document.forms["myform"]["hospital_name"];
if(hospital_name==null||hospital_name==""||!isNaN(hospital_name))
{
document.getElementById('hname').innerHTML = "Mention the Hospital Name where you last donated " ;
document.getElementById('hname').style.display = "block" ;
flag3=false;
return false;
}
document.getElementById('hname').style.display = "none" ;
flag3=true;
return true;
}
function validate()
{
alert("hello");
}
</script>
<form name="myform" method="post" action="o.php" onsubmit="return validate()">
<table width="94%" cellpadding="3px" class=" lastDonatedblood_table" cellspacing="0" style="border: 1px solid #CCCCCC;margin: -18px 0 14px 6px;width: 98.5%;">
<tr>
<td style="text-align:left;">Donated Date:</td>
<td style="text-align:left;">
<input type="text" name="donated_date" id="donated_date" onblur="return test();" style="width:300px;"/>
<div id="ddate"></div>
</td>
</tr>
<tr>
<td style="text-align:left;">Location:</td>
<td style="text-align:left;"><textarea name="location" id="location" onblur="return fun2();" style="width:300px;"></textarea></td>
</tr>
<center></center>
<tr>
<td style="text-align:left;">Hospital Name:</td>
<td style="text-align:left;"><input type="text" name="hospital_name" id="hospital_name" onblur="return fun3();" style="width:300px;"/></td>
</tr>
<center><div id="hname"></div></center>
<tr>
<td style="text-align:left;">Type of Donation:</td>
<td style="text-align:left;">
<select title="" name="donationtype" id="donationtype" style="width:317px;">
<option value="blood">Blood</option>
<option value="platelets">Platelets</option>
</select>
</td>
</tr>
<tr >
<td colspan="2">
<input name="submit" id="submit" value="ADD" type="submit" style="margin-top:5px; margin-left:185px; font-size:14px; width:100px;">
</td>
</tr>
</table>
</form>
you are missing closing curly bracket (function close) for fun2(),
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
} <-- added closing curly bracket here
Check in console and you will get the error

Categories