I have a html template like following which is generally a form
<script type="text/template" id="brands-form">
<legend class="label label-info">
<fmt:message key="......"/>
</legend>
<fieldset <# if (typeof brandId === 'undefined') { #>class="hide"<# } #>>
<legend>
<# if (typeof brandId === 'undefined') { #>
<span class="font-small"><font color="gray"><fmt:message key="....."/></font></span>
<# } else { #>
<span class="font-small"><font color="gray"><fmt:message key=".."/></font></span>
<# } #>
</legend>
<div class="control-group">
<span class="control-label font-small" for="name">
<b><fmt:message key="daydiary.brand.add.title"/></b>
</span>
<div class="controls">
<input name="name" type="text" required="required" size="30" maxlength="50" class="input-xlarge span11" value="<#= name #>" />
</div>
</div>
<div class="control-group">
<span class="control-label font-small" for="name">
<b><fmt:message key="..."/></b>
</span>
<div class="controls">
<img id="brandImage" name="brandImage" class="avatar-large" src="<# if (typeof brandId === 'undefined') {#>/img/default_brand_picture.jpg<#}else{#><#= brandImage #><#}#>" />
<input type="file" id="brandImageFileUpload" name="brandImageFileUpload"/>
</div>
</div>
<div class="control-group">
<span class="control-label font-small" for="description">
<b><fmt:message key="....."/></b>
</span>
<div class="controls">
<textarea name="description" class="input-xlarge span11" required="required" style="resize:none" maxlength="750"><#= description #></textarea>
</div>
</div>
<div class="control-group">
<span class="control-label font-small" for="showPro">
<b><fmt:message key="....."/></b>
</span>
<div class="controls">
<input type="radio" name="showPro" value="true" <# if (showPro) { #> checked<# } #>>
<span class="label label-info"><fmt:message key="....."/></span>
<input type="radio" name="showPro" value="false" <# if (!showPro) { #> checked<# } #>>
<span class="label label-info"><fmt:message key="...."/></span>
</div>
</div>
<div class="control-group">
<span class="control-label font-small" for="proDescription">
<b><fmt:message key="..."/></b>
</span>
<div class="controls">
<textarea name="proDescription" class="input-xlarge span11" style="resize:none" maxlength="700"><#= proDescription #></textarea>
</div>
</div>
<div class="form-actions alert-info">
<# if (typeof brandId === 'undefined') { #>
<button type="submit" class="btn btn-info btn-mini">
<fmt:message key="...."/>
</button>
<button type="reset" class="btn btn-mini">
<fmt:message key="....."/>
</button>
<# } else { #>
<button type="submit" class="btn btn-info btn-mini">
<i class="icon-edit"></i> <fmt:message key="..."/>
</button>
<# } #>
</div>
</fieldset>
When i do like following on form submit
this.model.set('name', form.find('[name="name"]').val());
this.model.set('description', form.find('[name="description"]').val());
this.model.set('proDescription', form.find('[name="proDescription"]').val());
this.model.set('showPro', form.find('[name="showPro"]:checked').val() === 'true');
everything works well but when i do
this.model.set('imageData',form.find('[name="imageData"]').val());
the html form element values are getting reset to "".It's very surprising to me.
I have no idea were the values getting vanished?? I am using backbone technology if someone need more info.
backbone code
app.View.EditBrand = Backbone.View.extend({
tagName: 'form',
attributes : {
'class' : 'form-horizontal row-fluid'
},
initialize: function(){
this.model.bind('change', this.render, this);
},
template:_.template($('#brands-form').html()),
template_success: _.template($('#notifications-brand-edit-success').html()),
template_error: _.template($('#notifications-brand-edit-error').html()),
events:{
'submit': 'submit'
},
render: function(){
this.delegateEvents();
this.$el.html(this.template(this.model.toJSON()));
this.$("#brandImageFileUpload").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#brandImage').attr('src', e.target.result);
$('#imageData').val(e.target.result);
},
reader.readAsDataURL(this.files[0]);
}
},
submit: function(e){
e.preventDefault();
var form = $(e.target);
this.model.set('name', form.find('[name="name"]').val());
this.model.set('description', form.find('[name="description"]').val());
this.model.set('proDescription', form.find('[name="proDescription"]').val());
this.model.set('showPro', form.find('[name="showPro"]:checked').val() === 'true');
this.model.set('imageData',form.find('[name="imageData"]').val());
var self = this;
self.model.save(null, {
success: function(){
notifications('success' , self.template_success());
},
error: function(){
notifications('error' , self.template_error());
}
});
}
});
Related
Here I have written a code for validating form input fields in Vue. And it is working fine when input fields are empty the form is not navigating to the next step. My issue is that while the field is empty, and the user tries to navigate to the next step, the input field border color should change in red. If one field is empty and the user is trying to navigate another step, the navigation should prevent, and the empty fields' border should be displayed in red.
<div id="vk_app">
<form>
<div v-if="step === 1">
<h1>Step One</h1>
<p>
<legend for="name">Your Name:</legend>
<input id="name" name="name" v-model="name">
<input id="name" name="name" v-model="age">
</p>
<button #click.prevent="next()">Next</button>
</div>
<div v-if="step === 2">
<template>
<input id="name" name="name" v-model="address">
<input id="name" name="name" v-model="h_no">
<input id="name" name="name" v-model="mobile">
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="next()">Next</button>
</template>
</div>
<div v-if="step === 3">
<template>
<input id="name" name="name" v-model="subject">
<input id="name" name="name" v-model="occupation">
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="next()">Next</button>
</template>
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="submit()">Save</button>
</div>
</form>
</div>
vue.js
const app = new Vue({
el:'#vk_app',
data() {
return {
step:1,
name:null,
age:null,
city:null,
state:null,
}
},
methods:{
prev() {
if(this.checkForm()) {
this.step--;
}
},
next() {
if(this.checkForm()) {
this.step++;
}
},
checkForm: function (e) {
if (this.name && this.age) {
return true;
}
this.errors = [];
if (!this.name) {
this.errors.push('Name required.');
}
if (!this.age) {
this.errors.push('Age required.');
}
e.preventDefault();
}
}
});
Here is my answer for your code example, it will work when you click on next button.
Updated HTML and Inputs:
<div id="vk_app">
<form>
<div v-if="step === 1">
<h1>Step One</h1>
<legend for="name">Your Name:</legend>
<input id="name" :class="errorField.name ? 'error-input' : ''" name="name" v-model="name" />
<input id="name" :class="errorField.age ? 'error-input' : ''" name="name" v-model="age" />
<button #click.prevent="next()">Next</button>
</div>
<div v-if="step === 2">
<template>
<input id="name" name="name" :class="errorField.address ? 'error-input' : ''" v-model="address" />
<input id="name" name="name" :class="errorField.h_no ? 'error-input' : ''" v-model="h_no" />
<input id="name" name="name" :class="errorField.mobile ? 'error-input' : ''" v-model="mobile" />
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="next()">Next</button>
</template>
</div>
<div v-if="step === 3">
<template>
<input id="name" name="name" v-model="subject">
<input id="name" name="name" v-model="occupation">
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="next()">Next</button>
</template>
<button #click.prevent="prev()">Previous</button>
<button #click.prevent="submit()">Save</button>
</div>
</form>
</div>
Vue Functions and Data Update:
data() {
return {
errorField: { name: false, age: false, city: false, state: false },
step:1,
name:null,
age:null,
city:null,
state:null,
}
},
methods:{
prev() {
if(this.checkForm()) {
this.step--;
}
},
next() {
if(this.checkForm()) {
this.step++;
}
},
checkForm: function (e) {
if (this.name && this.age) {
return true;
}
this.errors = [];
if (!this.name) {
this.errorField.name = true
this.errors.push('Name required.');
}
if (!this.age) {
this.errorField.age = true
this.errors.push('Age required.');
}
}
}
Since this feature(red border on invalid input) is required more often, we can use dynamic classes :
in style section define a class
.input--error{
border-color:red;
}
and in template section add
:class="{'input--error':!name}"
to input tag making it look like :
<input id="name" name="name" v-model="name" :class="{'input--error':!name}"/>
The whole code would look something like this:
<template>
<div>
<!-- Using dynamic classes -->
<input id="name" name="name" v-model="name" :class="{'input--error':!name}"/>
<input id="name" name="name" v-model="age" :class="{'input--error':!age}"/>
</div>
</template>
<script>
export default {
data(){
return{
name:null,
age:null
}
}
}
</script>
<style scoped>
.input--error{
border-color:red;
}
</style>
We could also add this directly in style attribute in input tag:
<input id="name" name="name" v-model="mobile" :style="!mobile ? 'border-color:red':''">
This would overcrowd the code unnecessarily.
We have a blur event.
When blur event fired, if the input box was empty (or whatever you want), add a class such as "red" to the input box.
<input id="name" name="name" v-model="name" #blur="validation($event.target)">
const validation = el => {
if (!el.value) {
// this is a very simple examples. I don't recommend using jQuery.
$(el).addClass('red');
}
};
Add.
You can use the method on Next() method.
<input id="name" name="name" v-model="name" ref="name">
const next = () => {
const inputName = this.$refs.name; // this if for just Vue2.
if (!inputName.value) {
$(inputName).addClass('red');
}
};
I want to display two columns from two different tables.
I have table "offices" and "cash_desks"
Table "offices" have the column "name" which I want to display.
Table "cash_desks" have the columns "name" and "office_id"(which refers to offices id).
I want to display offices name and cash_desks name in HTML table.
Here is my HTML code:
<table class="table">
<tr ng-repeat="cash_desks in items" ng-click="editItem(cash_desks)">
<td>{{cash_desks.name}}</td>
<td>{{offices.name}}</td>
</tr>
</table>
<label><input type="checkbox" ng-model="myVar">Редактирай офис</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(cash_desksForm.$valid)" name="cash_desksForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="offices_name">Код на валута</label>
<input type="text" class="form-control" required ng-model="activeItem.name" placeholder="Офис.." />
</div>
<div class="form-group">
<label for="value_name">Локация на офис</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.location" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="cash_desksForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
And Angular Code:
app.controller("CashDesksCtrl", function($rootScope, $scope){
$scope.items = [];
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh = function () {
$scope.items = [];
window.defaultAdapter.query("SELECT offices.name,cash_desks.name FROM offices LEFT JOIN cash_desks ON offices.id = cash_desks.office_id LIMIT 8", { type: Sequelize.QueryTypes.SELECT})
.then(cash_desks => {
$scope.items = cash_desks;
$scope.$apply();
})
};
You have same key (name) from your select , try to use alias to make them differents.
<table class="table">
<tr ng-repeat="itemin items" ng-click="editItem(cash_desks)">
<td>{{item.cash_desk_name}}</td>
<td>{{item.office_name}}</td>
</tr>
</table>
<label><input type="checkbox" ng-model="myVar">Редактирай офис</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(cash_desksForm.$valid)" name="cash_desksForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="offices_name">Код на валута</label>
<input type="text" class="form-control" required ng-model="activeItem.name" placeholder="Офис.." />
</div>
<div class="form-group">
<label for="value_name">Локация на офис</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.location" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="cash_desksForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
app.controller("CashDesksCtrl", function($rootScope, $scope){
$scope.items = [];
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh = function () {
$scope.items = [];
window.defaultAdapter.query("SELECT offices.name as office_name,cash_desks.name as cash_desk_name FROM offices LEFT JOIN cash_desks ON offices.id = cash_desks.office_id LIMIT 8", { type: Sequelize.QueryTypes.SELECT})
.then(cash_desks => {
$scope.items = cash_desks;
$scope.$apply();
})
};
I am able to get values into ViewBag and then I am passing those values into the HTML page. The Problem I am facing is that once i am passing the value into HTML, I am not able to populate the value into the Dropdown List.
Following is my code for the same:
#using PagedList;
#using PagedList.Mvc;
#model IPagedList<NurseOneStop.SC.NurseProfile>
#{
ViewBag.Title = "People";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="peoplemain-container" ng-controller="connectCtrl">
<div class="row">
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_searchName">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Search</button></center>
</div>
}
</div>
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_search">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search">
<input class="form-control" name="LastName" placeholder="Search by LastName" value="#ViewBag.FilterNurseSearch.LastName" />
</div>
<div class="j_search">
<input id="pinput" name="JobLocation" class="form-control" type="text" value="#ViewBag.FilterNurseSearch.JobLocation" placeholder="Enter a location">
<input id="Latitude" name="Latitude" type="hidden" value="#ViewBag.FilterNurseSearch.Latitude">
<input id="Longitude" name="Longitude" type="hidden" value="#ViewBag.FilterNurseSearch.Longitude">
</div>
<div class="j_search">
<select class="form-control" name="Profession">
<option value="#ViewBag.Profession" selected>Select Profession</option>
#for (int i = 1; i < ViewBag.Profession.Count + 1; i++)
{
<option value=#i #(ViewBag.FilterNurseSearch.Profession == i ? "selected" : "")>#ViewBag.Profession[i].Text</option>
}
</select>
</div>
<div class="form-group">
#Html.LabelFor(model => model., new { #class = "control-label" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)ViewBag.Profession, new { #class = "form-control" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)TempData["TempModel"], new { #class = "form-control" })
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Advance Search</button></center>
</div>
}
</div>
</div>
#foreach (var item in Model)
{
<div class="people_container">
<div class="connect_profile"><img src="#(item.ProfileUrl== "" ?"/image/placeholder.jpg" : #item.ProfileUrl)" title="#item.Title #item.FirstName #item.LastName" /></div>
<div class="clear"></div>
<div class="job_box">
<p><b>#item.Title #item.FirstName #item.LastName</b></p>
<p><span>#item.Profession</span></p>
</div>
<div class="job_box_btn">
<button class="details_btn">
#Html.ActionLink("View Nurse", "NurseView", "Nurse", new { NurseId = item.NurseId }, new { #class = "" })
</button>
<button class="details_btn">
<a style="display:#(item.Status==0? "block": "none")" id="connect_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId, 1)">Connect</a>
<a style="display:#(item.Status==1? "block": "none")" id="cancel_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3)">Cancel</a>
<a style="display:#(item.Status==2 || item.Status==3? "block": "none")" id="message_#item.NurseId" NurseFriendId="#item.NurseFriendId" href="/Nurse/GetInbox?FromNurseId=#NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseId&ToNurseId=#item.NurseId&FromRecruiterId=&ToRecruiterId=">Message</a>
<div class="tick-right"><a style="display:#(item.Status==4? "block": "none")" id="accept_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,2);"> <i class="fa fa-check"></i></a></div>
<div class="tick-wrong"><a style="display:#(item.Status==4? "block": "none")" id="reject_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3);"><i class="fa fa-times"></i></a></div>
</button>
</div>
</div>
}
<!--Confirm Modal -->
<div id="confirm" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content cancel-invitemodal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Cancel the Invitation to Connect</h4>
</div>
<div class="modal-body cancel-invitetion">
<h2>Are you sure you want to Cancel the Invitation to Connect</h2>
<div class="cancel-box">
<input type="button" class="btn" ng-click="RequestCancel(SelectedNurseId,3)" value="CANCEL INVITE">
<input type="button" class="btn" ng-click="Cancel()" value="DO NOT CANCEL INVITE">
</div>
</div>
</div>
</div>
</div>
<div class="pagination">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("People", new { page, Connected = ViewBag.Connected, SearchName = ViewBag.SearchName }), PagedListRenderOptions.OnlyShowFivePagesAtATime)
</div>
</div>
#section scripts{
<script>
function initMap() {
var input = document.getElementById('pinput');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
console.log(JSON.stringify(place));
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var latlong = JSON.parse(JSON.stringify(place.geometry.location));
document.getElementById('Latitude').value = latlong.lat;
document.getElementById('Longitude').value = latlong.lng;
});
}
initMap();
function showhide(id) {
$("ul").hide();
$("#newpost" + id).toggle();
}
$('#pinput').on('input', function () {
document.getElementById('Latitude').value = '';
document.getElementById('Longitude').value = '';
// do your stuff
});
</script>
}
Following is how I am using my controller:
public void DropDown()
{
ProfessionDAL objProfessionDAL = new ProfessionDAL();
Profession objProfession = new Profession();
List<Profession> objProfessionList = new List<Profession>();
SelectListItem objSelect = new SelectListItem { Text = "Select Profession", Value = "", Selected = true };
objProfessionList = objProfessionDAL.GetProfessionList().Results;
var profession = (from kl in objProfessionList
select new SelectListItem
{
Text = kl.ProfessionName,
Value = kl.ProfessionId.ToString(),
Selected = false
}).ToList();
profession.Insert(0, objSelect);
ViewBag.Profession = profession;
}
public ActionResult People(bool Connected, int? page, FilterNurseSearch objFilterNurseSearch)
{
if (ApplicationSession.CurrentUser == null)
{
//redirect
return RedirectToAction("Login", "Account");
}
DropDown();
long NurseId = ApplicationSession.CurrentUser.NurseId;
ViewBag.FilterNurseSearch = objFilterNurseSearch;
Result objResult = objNurseDAL.GetNurses(NurseId, Connected, objFilterNurseSearch);
int pageSize = 12;
int pageNumber = (page ?? 1);
ViewBag.Connected = Connected;
return View(((List<NurseProfile>)objResult.Results).ToPagedList(pageNumber, pageSize));
}
I know I am making a silly mistake which I am not able to catch and henceforth, ask my fellow developers to help me.
I am using dropzone with a form on a modal. I have one button that is 'Add Slider'. When I click on that button the modal is opened. In that modal I have attached an image on dropzone and click on cancel button. When I click on 'Add Slider' button again it shows the previously selected image in dropzone. I want to remove the previously selected image.
Html Code
<modal title="Manage HomeSlider" modaltype="modal-primary" visible="IsFormVisible">
<form name="frmHomeSlider" method="post" class="form-horizontal bv-form" novalidate="novalidate" ng-submit="frmHomeSlider.$valid && fnSaveHomeSlider()">
<modal-body>
<input type="hidden" class="form-control" name="ID" ng-model="HomeSlider.ID" />
<div class="form-group">
<label class="col-lg-3 control-label">Upload Slider Photo</label>
<div class="col-lg-9">
<div class="dropzone profileImage" customdropzone="dropzoneConfig">
<div class="dz-default dz-message">
<div ng-show="HomeSlider.FullPathPhoto==''">
<span>Upload photo here</span>
</div>
<img src="{{HomeSlider.FullPathPhoto}}" required />
</div>
</div>
<input type="hidden" name="Photo" ng-model="HomeSlider.HomeSliderPhoto" required />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Image Name</label>
<div class="col-lg-9">
<input type="text" class="form-control input-sm" name="ImageName" ng-model="HomeSlider.ImageName" placeholder="Enter Image Name" required />
</div>
</div>
</modal-body>
<modal-footer>
<button type="submit" class="btn btn-blue" ng-disabled="frmHomeSlider.$invalid">Submit</button>
<button type="reset" class="btn btn-default" ng-click="fnShowHomeSliderForm(false)">Cancel</button>
</modal-footer>
</form>
</modal>
Js Code
$scope.dropzoneConfig = {
'options': { // passed into the Dropzone constructor
'url': ContentService.UploadHomeSliderPhoto,
'addRemoveLinks': true,
'acceptedFiles': 'image/*',
'uploadMultiple': false,
'maxFiles': 1,
'dictDefaultMessage': 'Upload your photo here',
'init': function () {
this.on('success', function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
});
this.on('thumbnail', function (file) {
if (file.width < 1800 || file.height < 1200 || file.width > 1800 || file.height > 1200) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
'accept': function (file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function () {
done("The image must be at least 1800 x 1200px");
};
}
},
'eventHandlers': {
'sending': function (file, xhr, formData) {
},
'success': function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
},
'error': function () {
$rootScope.Common.notifyDanger("Error accure while upload photo.")
}
}
};
I have the below popup where the user can encode item information.
My requirement is that, when Foreign Currency and Conversion Rate are both have values, it should multiply Foreign Currency * Conversion Rate to get the Amount. And when both Foreign Currency and Conversion Rate are 0, then Amount field should accept user input.
Currently, I have the below HTML.
<div class="form-group" show-errors>
<label for="foreignCurrency" class="control-label col-md-3 text-muted">Foreign Currency</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-dollar fa-lg"></i> </span>
<input type="number" id="foreignCurrency" name="foreignCurrency" class="form-control" placeholder="Foreign Currency" ng-model="vm.newItem.newItemEnt.ForeignCurrency" value="{{vm.newItem.newItemEnt.ForeignCurrency || 0}}" min="0" />
</div>
<p class="help-block" ng-if="perksFrm.foreignCurrency.$error.min">The minimum foreign currency value is 0</p>
</div>
<div class="form-group" show-errors>
<label for="convRate" class="control-label col-md-3 text-muted">Conversion Rate</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-money"></i></span>
<input type="number" id="convRate" name="convRate" class="form-control" placeholder="Conversion Rate" ng-model="vm.newItem.newItemEnt.ConversionRate" ng-required="vm.newItem.newItemEnt.ForeignCurrency" value="{{vm.newItem.newItemEnt.ConversionRate || 0}}" min="0" />
</div>
<p class="help-block" ng-if="perksFrm.convRate.$error.required">The conversion rate is required</p>
<p class="help-block" ng-if="perksFrm.convRate.$error.min">The minimum conversion rate is 0</p>
</div>
<div class="form-group" show-errors>
<label for="amount" class="control-label col-md-3 text-muted">Amount</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-money"></i></span>
<input type="number" id="amount" name="amount" class="form-control" placeholder="Amount" ng-model="vm.newItem.newItemEnt.Amount" required />
</div>
<p class="help-block" ng-if="perksFrm.amount.$error.required">The first name is required</p>
</div>
In Amount html, I can do it like this {{vm.newItem.newItemEnt.ForeignCurrency * vm.newItem.newItemEnt.ConversionRate}}. But, what if they have a 0 value and my requirement is to accept the user input from Amount textbox.
Any advise to achieve my requirements?
TIA
According to your requirment, I tried to provide you answer.
Please find Code for this, also JS fiddle demo.
HTML
<style>
.error{
border-color:red;
}
</style>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="row">
<div class="col-lg-2">Foreign Currency</div>
<div class="col-lg-2"><input type="number" ng-model="FCurrency" /></div>
</div>
<div class="row">
<div class="col-lg-2">Rate</div>
<div class="col-lg-2"><input type="number" ng-model="Rate" /></div>
</div>
<div class="row">
<div class="col-lg-2">Amount</div>
<div class="col-lg-2"><input ng-class="{error : RateAmount <= 0}" ng-disabled="isAmountDisable"
type="number" ng-model="RateAmount" /></div>
</div>
</div>
JS
var myApp = angular.module("myApp", []);
myApp.controller('myCtrl', function ($scope) {
$scope.RateAmount = 0;
$scope.isAmountDisable = false;
function setRateAmount() {
if ($scope.FCurrency > 0 && $scope.Rate > 0) {
$scope.RateAmount = ($scope.FCurrency * $scope.Rate);
$scope.isAmountDisable = true;
}
else {
$scope.RateAmount = 0;
$scope.isAmountDisable = false;
}
}
$scope.$watch('FCurrency', function (newval, oldval) {
setRateAmount();
});
$scope.$watch('Rate', function (newval, oldval) {
setRateAmount();
});
});
JS Fiddle Demo
Did you tried to use ng-change on foreignCurrency and convRate input.
when those input change you can calcul your amount value and disable it.
if they are both 0, you can enable it.
Something like this :
function change() {
var foreignCurrency = vm.newItem.newItemEnt.ForeignCurrency;
var conversionRate = vm.newItem.newItemEnt.ConversionRate;
if (foreignCurrency === 0 && conversionRate === 0) {
vm.enableAmout = true;
} else {
vm.enableAmout = false;
vm.vm.newItem.newItemEnt.Amount = foreignCurrency * conversionRate;
}
}