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.
Related
This is the index file code:
public IList<Employee> Employee { get; set; }
public async Task OnGetAsync()
{
Employee = await _context.Employee.ToListAsync();
}
public JsonResult EmployeeList()
{
var data = _context.Employee.ToList();
return new JsonResult(data);
}
[HttpPost]
public JsonResult AddEmployee(Employee e)
{
var emp = new Employee()
{
Name = e.Name,
Age = e.Age,
Email = e.Email
};
_context.Employee.Add(emp);
_context.SaveChanges();
return new JsonResult("Success!!!");
}
Button to open Modal:
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
The Modal:
<!-- The Modal -->
<div class="modal Add-Emp">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off"/>
</div>
<div class="form-group">
<label>Age</label>
<input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off"/>
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
<button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The Js Code:
$("#btn1").click(function () {
$(".Add-Emp").modal("show")
})
function AddEmployee() { debugger
var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
$.ajax({
url: "Pages/Employees/Index/AddEmployee",
type: "Post",
data: objData,
contentType: "application/xxx-www-form-url-encoded; charset=utf-8",
dataType: "json",
success: function () { alert("Data Saved"); },
error: function () { alert("Error!!!"); }
})
}
Modal opens on click But data does not get posted on clicking the save button it displays alert "Error!!!" defined in failure of ajax requestㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
1.You maybe not familiar with Razor Pages, Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. If you need another Get or Post method in current PageModel, you need define the method name like: OnGetHandlerName or OnPostHandlerName.
2.If your .cshtml.cs file located like: Pages/Employees/Index.cshtml.cs, the request url should be:/Employees/Index. If you set the handler in your PageModel, the request url should be:/Employees/Index?handler=xxx.
3.For how to use Ajax in Razor Pages, Razor Pages enable anti-forgery token validation by default, so you need add this token to header in ajax.
If you use form in Razor Pages, it will default generate an input with token. If not, you need add #Html.AntiForgeryToken() manually.
A whole working demo you could follow:
Page(Pages/Employees/Index.cshtml):
#page
#model IndexModel
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
<div class="modal Add-Emp">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off" />
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
<button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts
{
<script>
$("#btn1").click(function () {
$(".Add-Emp").modal("show")
})
function AddEmployee() {
debugger
var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
$.ajax({
url: "/Employees/Index?handler=AddEmployee",
type: "Post",
data: JSON.stringify(objData), //change here...
contentType: "application/json; charset=utf-8", //change here...
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
}, //add this....
dataType: "json",
success: function () { alert("Data Saved"); },
error: function () { alert("Error!!!"); }
})
}
</script>
}
Pages/Employees/Index.cshtml.cs:
public class IndexModel : PageModel
{
//...
public IList<Employee> Employee { get; set; }
public async Task OnGetAsync()
{
Employee = await _context.Employee.ToListAsync();
}
public JsonResult OnGetEmployeeList()
{
var data = _context.Employee.ToList();
return new JsonResult(data);
}
public JsonResult OnPostAddEmployee([FromBody]Employee e)
{
var emp = new Employee()
{
Name = e.Name,
Age = e.Age,
Email = e.Email
};
return new JsonResult("Success!!!");
}
}
I'm trying to submit data using a pop-pup form but my submit button just closes the windows instead of saving all the data into my data base.
Everything seems to be in order but I have the impression that the form cannot read the lines of code contained in my controller
Here my codes
<div class="modal" id="exampleModalLong" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>ADD A NEW CLIENT</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Select an existing user from the database. </label>
<div class="row">
<div class="form-group col-xs-5">
<select id="Clients" class="choices form-select" title="Selectionner"
name="user_id">
<optgroup label="{{ count($Users) }} clients retrouvés">
<option value="" disabled selected>-- choisir --</option>
#foreach($Users as $User)
<option value="{{ $User->id }}">{{ $User->fullname }}</option>
#endforeach
</optgroup>
</select>
</div>
<label>Profession</label>
<div class="form-group">
<select class="choices form-select" title="Selectionner"
name="profession_id">
<option value="" disabled selected>-- choisir --</option>
#foreach($Professions as $Profession)
<option value="{{ $Profession->id }}">{{ $Profession->name }}</option>
#endforeach
</select>
</div>
<label>Phone</label>
<div class="form-group">
<input type="text" name="phone" placeholder="+243 " class="form-control">
</div>
<label>NID Type</label>
<div class="form-group">
<input type="text" name="nid_type" class="form-control">
</div>
<label>NID Photocopy</label>
<div class="row">
<div class="col-lg-2 col-xs-2">
<div class="form-group">
<img id="outputs" style="width:45px;background-color: whitesmoke;
border:1px solid #bbb;height:45px;border-radius: 2px" >
</div>
</div>
<div class="col-lg-10 col-xs-10">
<div class="form-group">
<div class="form-file">
<script type="text/javascript">
function previewImg(event) {
var outputs = document.getElementById('outputs');
outputs.src = URL.createObjectURL(event.target.files[0]);
}
</script>
<input type="file" name="nid_photocopie" accept=".png, .jpeg, .jpg"
class="form-control" id="clientImges"
onchange="return previewImg(event)">
</div>
</div>
</div>
</div>
<label>Profile Image</label>
<hr>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<img id="output" style="width:50px;height:50px;border-radius: 50px " >
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<div class="form-file">
<script type="text/javascript">
function previewImage(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
}
</script>
<input type="file" name="image" accept=".png, .jpeg, .jpg"
class="form-file-input" id="clientImgz"
onchange="return previewImage(event)">
<label class="form-file-label" for="clientImgz">
<span class="form-file-text">Choose image...</span>
<span class="form-file-button "><i data-feather="upload"></i></span>
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">Close</span>
</button>
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
HERE IS MY CONTROLLER
public function storeProfile(Request $request)
{
$this->validate($request, [
'user_id' => 'required',
'profession_id'=> 'required',
'nid_type'=> 'required',
'nid_photocopie'=> 'required',
]);
$slug = str_slug($request['fullname']);
$image = $request->file('image');
$image3 = $request->file('nid_photocopie');
//INSERTS PROFILE IMAGE
if (isset($image))
{
$image = $request->file('image');
$currentData = Carbon::now()->toDateString();
$fileToStore = $slug .'-'. $currentData .'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if(!file_exists('uploads/MicroCredit/ClientImage'))
{
mkdir('uploads/ClientImage', 0777 , true);
}
$image->move('uploads/ClientImage',$fileToStore);
}
else {
$fileToStore = 'default.png';
}
//INSERT ID PHOTOCOPIE
if (isset($image3))
{
$image3 = $request->file('nid_photocopie');
$currentData = Carbon::now()->toDateString();
$IdToStore = $slug .'-'. $currentData .'-'. uniqid() .'.'. $image3->getClientOriginalExtension();
if(!file_exists('uploads/MicroCredit/IDs'))
{
mkdir('uploads/IDs', 0777 , true);
}
$image3->move('uploads/IDs',$IdToStore);
}
else {
$IdToStore = 'default.png';
}
$CredNew = new Client();
$CredNew->user_id = $request->user_id;
$CredNew->profession_id = $request->profession_id;
$CredNew->nid_type = $request->nid_type;
$CredNew->nid_photocopie = $IdToStore;
$CredNew->image = $fileToStore;
$CredNew->slug = $slug;
$CredNew->save();
return redirect(route('/bienvenue'));
}
HERE MY ROUTES
// ========= FINANCE - CLIENTS ======== //
Route::get('/finance/creditor', [FinanceController::class,'indexCreditor'])
->name('finance.creditor');
Route::post('/finance/store', [FinanceController::class,'store'])
->name('finance.store');
Route::post('/finance/{id}/update', [FinanceController::class,'update'])
->name('finance.update');
Route::delete('/finance/{id}/destroy', [FinanceController::class,'destroy'])
->name('finance.destroy');
HERE MY MODEL
public function storeProfile(Request $request)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $with = ['Userz'];
protected $fillable = [
'user_id',
'profession_id',
'nid_type',
'nid_photocopie',
'image',
'slug'
];
public function profesn()
{
return $this->belongsTo(Profession::class,'profession_id');
}
public function Userz()
{
return $this->belongsTo(User::class,'user_id');
}
public function getRouteKeyName()
{
return 'slug';
}
}
HERE'S MY MIGRATIONS
class CreateCreditorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->integer('profession_id');
$table->string('nid_type');
$table->string('nid_photocopie');
$table->string('image')->nullable();
$table->string('slug')->nullable();
$table->timestamps();
});
}
By using dd(), I was able to see which input field was causing the popup modal not to submit the data. Thanks for everyone who reached out!
dd($CredNew);
I want to take the id, name image and content of tinymce editor which i want to show on another page using controller. I am using array through which i want to take id, name, image and content but i don't know how to retrive it on another controller.
<div class="col-sm-4">
<div class="form-group">
<label class="settinglabel">Name</label>
<input type="text" maxlength="20" class="form-control" ng-model="data.name">
</div>
</div>
<div class="col-sm-3" style="margin-bottom: 4px;">
<div class="BoardCardWithCustomProperties BoardCardWithCustomProperties--hover" draggable="true">
<div class="BoardCardWithCustomProperties-contents">
<img class="BoardCardCoverImage" ng-src={{data.thumbnail}}>
<div class="BoardCardWithCustomProperties-nameAndDropdownButton">
</div>
</div>
</div>
</div>
<div id="design-9">
<div class="col-sm-12" style="margin-top:10px; margin-bottom:5px">
<textarea rows="20" cols="100" ui-tinymce="tinymceOptions" ng-model="tinymceModel" />
<input name="image" type="file" id="upload" class="hidden" onchange="">
</div>
</div>
myApp.controller('SampleFormatCntrl', ['$scope', '$http', 'orderProcessService', '$timeout', 'authService', '$routeParams', 'localStorageService', '$q', 'CommonhttpService', function ($scope, $http, orderProcessService, $timeout, authService, $routeParams, localStorageService, $q, CommonhttpService) {
var id = $routeParams.id;
$scope.data = localStorageService.get("formatdata");
$scope.action = $routeParams.action;
if ($scope.action == 'Edit' || $scope.action == 'Copy') {
$scope.action = "Update"
}
else {
$scope.action = "Save"
}
$scope.tinyArray = [];
$scope.screenshot = function () {
$scope.tinyArray.push($routeScope.tinyArray);
}
<div ng-repeat="elem in data">
<button id="{{elem.id}}" ng-click="showItem($index, elem)">
{{elem.name}}
</button>
</div>
Controller:
$scope.showItem = function(elementIndex, dataItem){
console.log(elementIndex); // 0
console.log(dataItem.id + ':' + dataItem.name); // 1:Abhishek
}
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 trying to implement the following behavior.
I have a form and I want to require filling at least one of the check boxes or text field.
I am trying to do this with the following code, but I don't know what am I doing wrong. Thanks in advance.
https://jsfiddle.net/AlexLavriv/mc8fj4f9/
// Code goes here
var app = angular.module('App', []).controller("Ctrl", Ctrl);
function Ctrl($scope) {
$scope.formData = {};
$scope.formData.selectedFruits = {};
$scope.fruits = [{'name':'Apple', 'id':1}, {'name':'Orange', 'id':2}, {'name':'Banana', 'id':3}, {'name':'Mango', 'id':4},];
$scope.someSelected = function (object) {
console.log(object);
for (var i in object)
{
if (object[i]){
return true;
}
}
return false;
}
$scope.submitForm = function() {
console.log($scope.formData.selectedFruits);
}
}
<div ng-controller="Ctrl" >
<form class="Scroller-Container" name="multipleCheckbox" novalidate >
<div ng-app>
<div ng-controller="Ctrl">
<div>
What would you like?
<div ng-repeat="(key, val) in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[val.name]">
{{val.name}}
</div>
<p class="error" ng-show="submitted && multipleCheckbox.$error.required">Select check box or input text</p>
</div>
<pre>{{formData.selectedFruits}}</pre>
<input type="text" ng-required="!someSelected(formData.selectedFruits)" />
<input type="submit" id="submit" value="Submit" ng-click="submitted=true" />
</div>
</div>
</form>
</div>
You can't use ng-required with a function
You can find another solution here: https://jsfiddle.net/mc8fj4f9/2/
var app = angular.module('App', []).controller("Ctrl", Ctrl);
function Ctrl($scope) {
$scope.formData = {};
$scope.formData.selectedFruits = {};
$scope.fruits = [{'name':'Apple', 'id':1}, {'name':'Orange', 'id':2}, {'name':'Banana', 'id':3}, {'name':'Mango', 'id':4},];
$scope.submited=false;
$scope.someSelected = function (object) {
console.log(object);
for (var i in object)
{
if (object[i]){
$scope.checkboxSelected =true;
return true;
}
}
$scope.checkboxSelected =false;
return false;
}
$scope.submitForm = function() {
console.log("submit "+ $scope.formData.selectedFruits);
$scope.submitted=true;
$scope.someSelected($scope.formData.selectedFruits);
}
}
<div ng-controller="Ctrl" >
<form class="Scroller-Container" name="multipleCheckbox" novalidate>
<div ng-app>
<div ng-controller="Ctrl">
<div>
What would you like?
<div ng-repeat="(key, val) in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[val.name]" ng-required = "!inputVal">
{{val.name}}
</div>
<p class="error" ng-show="submitted && !checkboxSelected && !inputVal">Select check box or input text</p>
</div>
<pre>{{formData.selectedFruits}}</pre>
<input type="text" ng-required="!checkboxSelected" ng-model="inputVal"/>
<input type="submit" id="submit" value="Submit" ng-click="submitForm()" />
</div>
</div>
</form>
</div>