How to post value from autocomplete instead of text? - javascript

This is my C# Code:
public JsonResult FillUsers(string term)
{
var Retailers = from us in db.Users
join pi in db.UserPersonalInfoes on us.ID equals pi.UserID into t
from rt in t.DefaultIfEmpty()
where us.Status == true
select new
{
ID = us.ID,
Username = us.Username + ":( " + (rt == null ? String.Empty : rt.FirstName) + " )"
};
List<string> UsersList;
UsersList = Retailers.Where(x => x.Username.Contains(term)).Select(y => y.Username).Take(10).ToList();
return Json(UsersList, JsonRequestBehavior.AllowGet);
}
HTML Code:
<div class="col-md-3">
#Html.TextBox("ddlUser", null, new { #id = "ddlUser", #class = "form-control" })
</div>
Javascript Code:
<script type="text/javascript">
$(function () {
$("#ddlUser").autocomplete({
source: '#Url.Action("FillUsers", "FirebaseNotification")',
select:function(event, ui)
{
var id = ui.item.ID;
var name = ui.item.Username;
}
});
});
I want show 'username' in text field but when form will be post I want to send 'ID'. Instead of that I am getting username.

To achieve that you might need an additional hidden field in which you store the id when a selection is made:
$("#ddlUser").autocomplete({
source: '#Url.Action("FillUsers", "FirebaseNotification")',
select: function(event, ui) {
var id = ui.item.ID;
$('#selectedUserId').val(id);
}
});
Now when the form is submitted you will ignore the username value coming from the text input field, but rather take the hidden field value:
#Html.Hidden("selectedUserId", null, new { id = "selectedUserId" })

$("#ddlUser").keyup(function (e) {
if (e.which != 13) {
$("#hfUserID").val("0");
}
$("#ddlUser").autocomplete({
source: function (request, response) { ... },
select: function (e, i) {
$("#hfUserID").val(i.item.val);
$("#ddlUser").val(i.item.label);
},
minLength: 1
});
});

Related

How to display corresponding value in a input field when a value is selected into another input field JavaScript

I have two input fields which are depends on each other. The value is coming as an array of objects from database. I want to auto fill the input field with the corresponding values when I select the value into one input field.
Here is the code I have tried. But I am still getting it as [object,object]. Where is my mistake? Any help would be appreciated.
if (serviceURL == "myURL") {
var Data = '';
$.get(serviceURL, function(response) {
var Data = $.map(response, function(value, index) {
data = value;
return[value];
})
}).done(function() {
$("#" + id).autocomplete({
source: Data,
minLength: 0;
scroll: true
}).focus(function() {
$(this).autocomplete("search", "");
});
});
$("#1stIpId").change(function() {
var val = $this.val();
$.each(Data, function(key, value) {
if (val == key)
$("#2ndIpId").val(value);
})
});
}
Please help.

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>

Preserve the hidden or visible state of initially hidden textbox on postback in mvc application

Given below is my script.My problem is I have a textbox which is hidden and is diplayed only when we select "other" from dropdownlist.On display when we enter a value after post back that value gets preserved but that textbox becomes invisible.on postback dropdown list value is however preserved and shown as "others" and only when I select someother value of dropdown and then again change it to "other" then textbox along with text gets displayed..how can I preserve that hidden or visible state of it on postback?
<script type="text/javascript">
$(document).ready(function () {
$('#SelectedCategoryId').change(function () {
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
});
});
</script>
My View
<div id="dropdown" class="form-control dropdown">
#Html.ValidationMessageFor(m => m.SelectedCategoryId, "*")
#Html.LabelFor(m => m.Category, "Department :", new { style = "display:inline;" })
#Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Category, "Value", "Text"), "SelectCategory", new { id = "SelectedCategoryId"})
#Html.ValidationMessageFor(m => m.Other, "*")
#Html.TextBoxFor(m => m.Other, new { id = "other", #class = "other" ,style = "display: none;" })
#Html.HiddenFor(m => m.SelectedCategory, new { id = "hiddenId" })
</div>
that's becaue you only check for the value of the select on "change" event. That doesn't happen when you load the page. Do it like that:
function toggleHidden() { //that's your code in a function
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
}
$(document).ready(function () {
toggleHidden(); //execute the toggle on load
$('#SelectedCategoryId').change(toggleHidden); //execute the toggle on change
});

Validation of multiple table fields using Dynamic Rule

I have a dynamic table, which each row contains country and numberOfState fields. Currently I am able to add new record and validate the country and numberOfState field separately (e.g. required) after click the "AddNewRecord" button, which is below code that generate dynamic table unique field name, i.e. name="country_0", "numberOfState_0" for 1st row, and ="country_1", "numberOfState_1" for 2nd row and etc.
Would like to check whether can validate the dynamic country and numberOfState fields together (i.e. Country is US and NumberOfState must be 50), using dynamic rule code as per below addRowRule function. Thanks in advance.
$(document).ready(function(e){
var rowindex = 0;
$("#AddNewRecord").click(function(){
var row =
"<tr><td>input name=country_"+rowindex+" type=text class='countryRule'/></td>
<tr><td>input name=numberOfState_"+rowindex+" type=text class='stateRule'/></td></tr>";
$("#table").append(row);
rowindex++;
addRowRule(rowindex);
});
jQuery.validate.addClassRules({
countryRule:{required:true},
stateRule:{required:true}
});
$('form').validate();
function addRowRule(i) {
var country = '#country_' + i,
var numberOfState = '#numberOfState_' + i;
$(country).rules('add', {
required: true,
numberOfState:{
required: {
depend: function(element){
if ($(country).val() == 'US' &&
$(numberOfState).val() !=50){
return false;
}
return true;
}
messages: {
numberOfState: "Number of state not match with country",
}
},
messages: {
required: "Required input",
}
});
});
Updated code to share with all:
$( document ).ready(function() {
$("#myForm").validate(); //sets up the validator
var rowindex = 0;
$("#AddNewRecord").click(function(){
var row = "<tr><td>input name=country_"+rowindex+" type=text /></td>" +
"<tr><td>input name=numberOfState_"+rowindex+" type=text /></td></tr>";
$("#table").append(row);
addRowRule(rowindex);
rowindex++;
});
function addRowRule(row_index) {
var country = '#country_' + row_index;
var numberOfState = '#numberOfState_' + row_index;
$(country).rules('add', {
required: true,
messages: {
required: "Pls input country."
}
});
$(numberOfState).rules('add', {
required: true,
checkCountryAndState: [country, numberOfState],
messages: {
required: "Pls input number of state."
}
});
}
jQuery.validator.addMethod("checkCountryAndState", function(value, element, params){
var varCountry = params[0];
var varNumberOfState = params[1];
if ($(varCountry).val() === 'America' && $(varNumberOfState).val() !== 50){
return false;
}
return true;
}, jQuery.format("Country is not match with Number of State."));
});
You can specify validation rules with the rules property. This should do what you specified in the question as an example:
$(".selector").validate({
rules: {
field2: {
required: true,
field1: {
depends: function(element) {
if ($('#field1').val() === 'A' && $('#field2').val() === 'Z') {
return false;
}
return true;
}
}
}
}
});
After this, you need to assign a message if the validation fails with the messages property.
Part of your problem is putting invalid objects inside of the .rules() method. Since the .rules() method is already attached to a selector (representing a SINGLE field), you cannot declare rules for additional fields inside of it...
function addRowRule(i) {
var country = '#country_' + i,
var numberOfState = '#numberOfState_' + i;
$(country).rules('add', {
required: true,
numberOfState: { // <- you can NOT put this here
required: { ...
The only objects allowed inside of .rules() is a key: value list of various rules/methods and/or the messages object.
You would have to attach other fields to different instances of .rules()....
function addRowRule(i) {
var country = '#country_' + i,
var numberOfState = '#numberOfState_' + i;
$(country).rules('add', {
required: true,
....
});
$(numberOfState).rules('add', {
required: true,
....
});
....

change textbox value in client side and read it in server side

I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.

Categories