How to make on click on input search in Js? - javascript

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()

Related

When the cursor leaves the input box #select-or-enter-category, this code checks whether the given input exists in the dropdown or not

I have this code I use for showing a warning message:
<div class="row clearfix">
<div class="col-sm-8 col-sm-offset-2">
<div>
<div class="form-line focus">
<span class="category-status" style="color: red;">
This entered category is not found in the category list.<br>
Press button on the right to save this new category.
</span>
</div>
</div>
</div>
</div>
Then, I have another code use for typeahead dropdown:
<div class="row clearfix">
<div class="col-sm-7 col-sm-offset-2">
<div class="form-group form-float">
<div class="form-line focus">
<input type="hidden" id="cat-id" name="category_id" value="">
<input type="text" id="select-or-enter-category" name="category" data-provide="typeahead"
placeholder="Enter/Select a category" value="" required="required" class="form-control">
</div>
</div>
</div>
<div class="col-sm-1">
<button type="button" id="save-category" data-toggle="tooltip" data-placement="top" title=""
class="btn btn-warning" data-original-title="Save this input as New Category">
<i aria-hidden="true" class="fa fa-bookmark-o" style="display: inline;"></i>
</button>
</div>
</div>
And this is my javascript/jquery code:
When the user types keyword in an input box #select-or-enter-category,
this javascript code will give a dropdown as typeahead for the given keyword.
/**
* Autocomplete for category - ADD TASK MODAL
* #return {[type]} [description]
*/
$(document).ready(function(){
axios_get('/axiosCategory', function(data) {
var cat = [];
var $input = $("#select-or-enter-category");
let temp;
data.forEach(function(item) {
temp = {
id: item.id,
name: item.categoryName
}
cat.push(temp);
});
$input.typeahead({
source: cat,
autoSelect: true
});
$input.change(function() {
// console.log($input);
var current = $input.typeahead("getActive");
if (current) {
$('#cat-id').val(current.id);
}
});
});
});
When the cursor leaves the input box #select-or-enter-category, this code checks whether the given input exists in the dropdown or not. If not, the warning message will show up that will ask the user to save the input as a new category.
/**
* Display the message asking the user to save the
* new category
*
* #return void
*/
$('#select-or-enter-category').focusout(function() {
let val = $(this).val();
axios_get('/axiosCategory', function(data) {
let search = false;
data.forEach(function(item) {
if (val == item.categoryName) {
search = true;
}
});
if (search == false) {
$('.category-status').removeAttr('hidden');
} else {
$('.category-status').attr('hidden', true);
}
});
});
Then problem is that when the user clicks an item from the dropdown using the mouse, the error message shows up which is not what I want to happen.
I want the error message to show up only when the cursor actually leaves the input box #select-or-enter-category.
But if the user only uses keyboard for choosing an item from the dropdown and enter it, there is no problem.
Do you have any suggestions?
Try this one
$(document).ready(function(){
axios_get('/axiosCategory', function(data) {
dataGlobal = data;
var cat = [];
var $input = $("#select-or-enter-category");
let temp;
data.forEach(function(item) {
temp = {
id: item.id,
name: item.categoryName
}
cat.push(temp);
});
$input.typeahead({
source: cat,
autoSelect: true
});
$input.change(function() {
var current = $input.typeahead("getActive");
if (current) {
$('#cat-id').val(current.id);
}
});
$input.focusout(function() {
let val = $('#select-or-enter-category').val();
let current = $input.typeahead("getActive");
let search = false;
let str = current.name.substring(0,val.length);
if (str == val) {
val = current.name;
}
dataGlobal.forEach(function(item) {
if (val == item.categoryName) {
search = true;
}
});
if (search == false) {
$('#category-status').removeAttr('hidden');
} else {
$('#category-status').attr('hidden', 'hidden');
}
});
});
});

Update the multiple value and display using AngularJS and laravel

[{"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: '...'
}
}

ASP MVC: Ajax change textbox value which is implemented in a different view

I have a view named Index, and 2 partial views _Grid and _Project.
The partialview _Project is a pop-up which is visible once the user clicks on the button to add data, think of it like adding a user.
Now, I am trying to change a textbox value which is inside the partial view _Grid once the user click on the button inside the _Project pop-up.
Inside the _Grid partialview:
<input id="CurrentOrder" type="hidden" value=""/>
In javascript once the button inside the pop-up(partialview _Project) is pressed:
function AddTimeReg() {
//code
if (date && shopdoc && ((convertedStartTime && convertedEndTime) || hours)) {
$.ajax({
// more code
// change the value of textbox
$("#Grid #CurrentOrder").val(salesorder);
The input type is inside the Grid partialview in a div named Grid.
What exactly am I doing wrong here?
I want the textbox have the value of salesorder.
Edit: For the one who wants the entire code:
Javascript File:
function AddTimeReg() {
var salesorder = $("#SalesOrder").val();
var shopdoc = $("#Shopdoc").val().trim();
var starttime = $("#StartTime").val().trim()
var convertedStartTime = starttime.replace(/\./g, ':')
var endtime = $("#EndTime").val().trim()
var convertedEndTime = endtime.split('.').join(':');
var hours = Math.round(Number($("#Hours").val().trim().replace(DecimalSeparator(), '.')) * 100 / 100);
var date = $("#Date").val().trim();
var info = $("#Info").val().trim();
var timeRegLineNr = 0;
var isEditing = $("#Project #Date").prop('disabled');
if (isEditing) {
timeRegLineNr = $($(".highlight")[0]).children(".td-TimeRegLineNr").text();
}
if (date && shopdoc && ((convertedStartTime && convertedEndTime) || hours)) {
$.ajax({
type: 'post',
url: appPath + '/TimeReg/ShopDoc',
data: {
regDate: date, salesOrder: salesorder, shopDoc: shopdoc, startTime: convertedStartTime, endTime: convertedEndTime,
hours: hours, info: info, timeRegLineNr: timeRegLineNr
},
success: function (response) {
if (response.success) {
var mySessionVariable = shopdoc
ClosePopup();
ShowGrid();
$("#Grid #CurrentOrder").val(salesorder);
var timerId = setTimeout(function () {
$("#dialog #TimerId").val("");
$("#dialog").modal("hide");
}, timeToClose);
$("#dialog #TimerId").val(timerId);
}
$("#dialog .modal-body").html(response.message);
$("#dialog #dialog-title").html(response.title);
$("#dialog").modal("show");
},
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
});
}
}
Inside Index:
<div id="Main" style="#mainDisplay">
<div style="margin:10px;">
<input id="regDate" type="#regDateType" value="#DateTime.Now.ToShortDateString()" />
<input type="button" class="btn btn-default" value="#Resources.Ok" onclick="ShowGrid()">
</div>
<div id="Grid">
#if ((bool)ViewBag.ShowGrid)
{
Html.RenderAction("Grid", new { login = (string)ViewBag.Login, regDate = DateTime.Now });
}
Inside the _Grid partialview there is the textbox:
<input id="CurrentOrder" type="hidden" value=""/>
And inside the Project partial view there is a button which calls the javascript Action
You have two partial.Call first partial then if call other partial, you might use ajax call.

Cannot post Id with Twitter Bootstrap Typeahead

I use Twitter Bootstrap Typeahead in my MVC5 project and it list the related records properly. Although I can retrieve the Id value of the selected record on updater section, I cannot post it on form submit. I tried many different combinations of the Id parameter, but did not make any sense. How to post Id parameter with Twitter Bootstrap Typeahead?
View:
#Html.HiddenFor(m => m.StudentId)
<input id="StudentId" name="StudentId" type="text" class="form-control tt-input"
autocomplete="off" spellcheck="false" dir="auto">
<script>
$("#StudentId").typeahead({
minLength: 1,
source: function (query, process) {
var lookups = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Grade/StudentLookup?query=%QUERY', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, lookup) {
map[lookup.Name] = lookup;
lookups.push(lookup.Name);
});
// Process the details
process(lookups);
});
},
updater: function (item) {
var selectedId = map[item].Id;
console.log("Selected : " + selectedId);
return item;
}
});
</script>
Controller:
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name + " " + m.Surname
})
.Where(m => m.Name.StartsWith(query));
return Json(students, JsonRequestBehavior.AllowGet);
}
Seperate the fields into Name and Id, you can even make the ID field hidden or readonly.
<input id="StudentName" type="text" class="form-control tt-input"
autocomplete="off" spellcheck="false" dir="auto">
<input id="StudentId" name="StudentId" type="text">
<script>
$("#StudentName").typeahead({
minLength: 1,
source: function (query, process) {
var lookups = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Grade/StudentLookup?query=%QUERY', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, lookup) {
map[lookup.Name] = lookup;
lookups.push(lookup.Name);
});
// Process the details
process(lookups);
});
},
updater: function (item) {
var selectedId = map[item].Id;
console.log("Selected : " + selectedId);
$("#StudentId").val(selectedId)
return item;
}
});
</script>

Select input only select one value using angularjs?

So far, my code binds data to choices object, and then add field input dynamically when clicking "add course" button. Then, uses $http.get to return json data from the server and binds it to select option. Although when I choose an option, it only selects applied option.
HTML:
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button ng-click="addNewCourse()">Add New Course</button>
<fieldset ng-repeat="choice in choices">
<select ng-model="choice.type"
ng-options="s.value as s.name for s in coursetoAdd">
<option value="{{s.value}}">{{s.value}}</option>
</select>
<input ng-model="choice.course">
</fieldset>
<button ng-click="convertAndSend()">Submit</button>
</div>
Javascript:
var timeTable = angular.module("timeTable",[]);
timeTable.controller("addCoursesCtrl", function ($scope,$http) {
$scope.choices = [{ course: '', type: '' }];
$scope.coursetoAdd = $scope.choices;
$http.get("/Semster/getSuggtedCourses").then(function (response) {
$scope.coursetoAdd = response.data;
});
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ course: '', type: '' });
};
$scope.convertAndSend = function () {
var asJson = angular.toJson($scope.choices);
console.log(asJson);
$http.post('/Semster/Add', asJson);
};
});

Categories