[{"user_id":78936,"social_id":null,"type":2,"name":"Get Raj","first_name":"Get","last_name":"Raj","email":"test1#yopmail.com"},
{"user_id":78937,"social_id":null,"type":2,"name":"James thomas","first_name":"James","last_name":"thomas","email":"jamesthoms#yopmail.com"}]
<div ng-repeat="user in profiles">
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="entry_{{user.user_id}}"
ng-model="update.entry"
ng-change="save(user, update)"
>
</div>
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="info_{{user.user_id}}"
ng-model="update.info"
ng-change="save(user, update)"
>
</div>
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="textual_{{user.user_id}}"
ng-model="update.textual"
ng-change="save(user, update)"
>
</div>
</div>
function makeOrderItemUrl(user_id, order_id){
return 'v1/update/' + user_id + '/order_id/' + order_id;
}
$scope.save = function (person, update) {
var person = person;
var order = null,
matchCount = 0;
for (var i = 0; i < $scope.order.items.length; i++) {
if ($scope.order.items[i].user_id == person.user_id) {
order = $scope.order.items[i];
matchCount++;
}
}
if(order){
$http.post(makeOrderItemUrl(person.user_id, order.order_id), update)
.success(function(res){
$scope.update = res.data;
}).error(function () {
notify.message('There was an issue saving your changes, please try again later.');
});
}
};
Since we have two users so we will get twice input fields i.e ng-model="update.entry" two times then whenever I type in the first textbox it get reflected the same value in the second textbox as well because of the same model they are using how can I set different models and value to be saved into the database and display respectively.
Laravel
$orderItem = OrderItem::firstOrNew([
'user_id' => $user_id,
'order_id' => $order_id
]);
if($orderItem->exists){
$orderItem->entry = Input::get('entry');
$orderItem->save();
}
//This is working fine but it's hard to display.
Make update a deeper object where the user id's are used as first level keys
<input
type="text"
name="entry_{{user.user_id}}"
ng-model="update[user.user_id].entry"
ng-change="save(user, update[user.user_id])"
>
Then $scope.update would look like:
{
id1: {
textual: '...',
entry: '...',
info: '...'
},
id2: {
textual: '...',
entry: '...',
info: '...'
}
}
Related
So I have this code
$(document.body).on('click', '.btn-create-tournament', function () {
var title = $(".create-tournament-title").val();
var format = $(".create-tournament-format").val();
var sport = $(".create-tournament-sport").val();
var prize = $(".create-tournament-prize").val();
var date = $(".create-tournament-date").val();
var location = $(".create-tournament-location").val();
var teams = $(".create-tournament-teams").val();
$.post('/Tournament/Create', {
title: title,
format: format,
sport: sport,
prize: prize,
date: date,
location: location,
teams: teams
}, function (response) {
if (response > 0) {
window.location.href = "/Tournament/Details/" + response;
}
})
}).on('input', '.search-teams', function () {
var query = this.value;
$.get('/Teams/Search', { name: query }, function (response) {
$('.search-team-results').html($(response).find('.team-results-search').html());
})
})
and then I call the input function here
#model List<TeamViewModel>
<div class="search-team-results">
#foreach (var item in Model)
{
<div>
<label class="team-results-search" data-team-id="#item.Id">#item.Name</label>
</div>
}
</div>
and finally it goes there
<h6>Players</h6>
<div class="form-outline">
<input class="search-teams" type="search" placeholder="Type query" aria-label="Search" />
<div class="search-team-results">
</div>
</div>
so I'm searching in a input field for the teams but they are showing below the field as label only and my question is how to make a script to actually add them to my list which is in my viewmodel?
$(response).find('.team-results-search').html()
will only get you the inner html (only text in this case) of the first label in the result list. To get the whole list use
$(response).find('.search-team-results').html()
I want to serialize my html form and submit it to my sever via ajax, but before submitting the form, I want to rename the variable names and remove the initiali part, which is: BranchViewModels[0]. for example, I want to change:
change: BranchViewModels[0].BranchName to: BranchName
change: BranchViewModels[1].AddressViewModel.AddressId to : AddressViewModel.AddressId
Basically when I generate form, all the input names are rendered as an array, but before submitting the form, I want to get rid of array section of the input name (BranchViewModels[0]. in this example).
I have explained why I am doing this here
I have also created a jsfiddle for the following example.
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serialize();
alert('I want to change the input names in this serialized form: \n\n' + serializedform );
// 1. iterated through serialized form
//
// remove BranchViewModels[i]. from the name, e.g.
// replace: BranchViewModels[0].BranchName
// with: BranchName
// 2. Submit the form
/* $.ajax({
url: "/my-server",
data: {branchViewModel: <-- serialized model},
dataType: 'json',
type: "POST"}); */
});
}
jQuery(document).ready(function($) {
updateBranch();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="return false;" novalidate="novalidate">
<div class="form">
<div class="form-group">
<label>Branch name</label>
<input class="form-control" data-val="true" id="BranchViewModels_0__BranchName" name="BranchViewModels[0].BranchName" type="text" value="branch 1">
</div>
<hr />
<div class="form-group">
<label>Branch location</label>
<div>
<input data-val="true" id="BranchViewModels_0__AddressViewModel_AddressId" name="BranchViewModels[0].AddressViewModel.AddressId" value="1956">
</div>
<div>
<input class="address-street-address" data-val="true" id="BranchViewModels_0__AddressViewModel_StreetAddress" name="BranchViewModels[0].AddressViewModel.StreetAddress" value="Wellington 6011, New Zealand">
</div>
</div>
<input type="button" class="btn btn-primary-action save-branch-button" value="Save">
</div>
</form>
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serializeArray();
console.log(serializedform);
const obj = {};
for(let d of serializedform){
obj[d.name.split('.').pop()] = d.value
}
console.log(obj);
}
Return serialize data to Deserialize then change to you want anything Hope this help you.
console.log(deparam(serializedform));
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}
I'm working on an ASP.NET Core MVC web project and I want to populate values of ComboBox B (Churches) based on selection of ComboBox A (Stations) using JavaScript (Json). I have tried to research with no success.
Here are my codes:
MVC View Code:
<div class="form-group">
<label asp-for="RSTATIONID" class="col-sm-4 control-label">Station:</label>
<div id="station" class="col-sm-8">
<select asp-for="RSTATIONID" class="form-control" asp-items="ViewBag.RSTATIONID"
onchange="LoadChurches(this)"></select>
<span asp-validation-for="RSTATIONID" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="RCHURCHID" class="col-sm-4 control-label">Church:</label>
<div id="church" class="col-sm-8">
<select asp-for="RCHURCHID" class="form-control" asp-items="ViewBag.RCHURCHID"></select>
<span asp-validation-for="RCHURCHID" class="text-danger" />
</div>
</div>
JavaScript Code:
function LoadChurches(e) {
var stationID = e.value;
//alert(stationID);
$.ajax
({
url: '/CaptureReceipts/LoadChurches',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stationID: +stationID
}),
success: function (result) {
var res = result.value;
alert(JSON.stringify(res));
/*$("#church").html("");
$.each($.parseJSON(result), function (i, church) {
SetSel(this);
}); */
},
error: function () {
alert("Churches can not load");
}
});
}
Controller Code:
public JsonResult LoadChurches(string statID)
{
int stationID = Convert.ToInt32(statID);
var churches = new SelectList(_context.v_Church.Where(m => m.StationID == stationID), "ID", "churchName");
return Json(ViewData);
}
The Controller name is CaptureReceiptsController. Please help me know what may be wrong.
In controller return simple json array:
var churches = _context.v_Church
.Where(m => m.StationID == stationID)
.Select(x => new {id = x.ID, name = x.churchName })
.ToArray();
return JSON(churches);
In success callback:
success: function (data) {
var churchSelect = $("#church > select")
churchSelect.html(""); //clear select
for (var i =0;i<data.length;i++){
var opt = document.createElement('option');
opt.innerHTML = data[i].name;
opt.value = data[i].id;
churchSelect.append(opt);
}
}
When addrow() is called we want to add dynamic rows using id="rowTemplate".
I want to load data to dropdownlist (id="selectitem") using "myfunction()".
But here issue is every time when "myfunction()" is called the data is loaded only for dropdownlist of the first row :
//adding dynamic rows
function addRow() {
$('#orderItem').append($('#rowTemplate').html());
console.log($('#rowTemplate').html());
myFunction();
}
function myFunction() {
document.getElementById("selectitem").options.length = 0
var SupID = document.getElementById("selectSup").value;
document.getElementById("demo").innerHTML = "Supplier Id: " + SupID;
var dataString = 'SupID='+ SupID;
// AJAX Code To Submit Form.
var postForm1 = { //Fetch form data
'functionName': "itemLoad",
'SupID': SupID
};
$.ajax({
type: 'POST',
url: 'suppierOrderdb.php',
data: postForm1,
//dataType: 'json',
success: function (data) {
var dd = data;
var data = (typeof dd) == 'string' ? eval('(' + dd + ')') : dd;
for (var i = 0; i < dd.length; i++) {
$('#selectitem').append($('<option>',
{
value: data[i].ItemId,
text : data[i].ItemId +" - "+ data[i].ItemName
}));
}
}
, error: function (e) {
alert(e);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group row">
<label for="selectitem" class="control-label col-xs-2">Item Name</label>
<div class="col-xs-2">
<select name='selectItem[]' class='form-control form-control-sm' id='selectitem'>
</select>
</div>
<label for="Qty" class="control-label col-xs-2">QTY</label>
<div class="col-xs-2">
<input class="form-control" name="Qty[]" type="text" value="" id="Qty">
</div>
</div>
Remove
</div>
id should be unique in the same document alse also you got an invalid HTML and the first element with duplicate id will be called, so replace your dep id's by common class in :
$('#orderItem').append($('#rowTemplate').html());
Could be :
$('#orderItem').append($('.rowTemplate').html());
Hope this helps.
Like wlh and Zakaria Acharki said, ID's are unique within the DOM.
Take a look at this link from css-tricks to learn more about the differences between Classes and IDs.
Also, to access a class in jQuery, use $('.classname'), replacing the # for IDs with a . for classes.
$('[id=selectitem]').append($('<option>', {
value: data[i].ItemId,
text: data[i].ItemId + " - " + data[i].ItemName
}));
Hello new to AngularJS and I am trying to wrap my head around something...
Basically I have a form that can accept 1 to many "Guests" for an event. Using ng-repeat I display the fields like so:
<div ng-repeat="guest in guests">
<input type="text" ng-model="guests[$index].first_name" />
<input type="text" ng-model="guests[$index].last_name" />
<select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select>
<select ng-model="guests[$index].rsvp">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="controls"><button ng-click="submit()" class="btn btn-success">Save</button></div>
And in the controller:
//DETERMINE TOTAL IN PARTY
var totalInParty = 2;
$scope.meals = RSVPRes.Meals.query();
//EDIT
if ($scope.rsvpId) {
}
//NEW RSVP SUBMISSION
else {
$scope.rsvp = new RSVPRes.RSVP();
//INITIALIZE EMPTY GUESTS
$scope.guests = [];
for (var i = 0; i < totalInParty; i++) {
$scope.guests[i] = {
first_name: '',
last_name: '',
meal: 1,
rsvp: 0
};
}
}
And my Resource
.factory( 'RSVPRes', function ( $resource ) {
return {
RSVP: $resource("../reservations/:id.json", {id:'#id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Meals: $resource('../meals.json')
};
})
Now all this works really well - I am just having trouble saving the data. I would like to save each Guest (First Name, Last Name, Meal & RSVP) as it's own row.
If I try this:
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};
It creates two rows (total_in_party set to 2) but it's always the 2nd persons data.
Feel like I am close, I looked a quite a few ng-repeat examples, but couldn't find one that deals with my specific case!
Any help is appreciated.
SOLVED
I totally duffed my thinking about the Resource, creating a new RSVP object now everytime in the loop.
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp = new RSVPRes.RSVP();
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};
Move $scope.rsvp.$save(); outside the loop