My web form model(AdtFormModel) has this variable:
public List<String> TemoinsVille { get; set; }
I use a list because I want the user to be able to dynamically add more 'TemoinsVille' in the form. For now I have two textboxfor, when I fill both of them, my controller receives a string list with 2 items in it. I will add the feature to dynamically add TemoinsVille later.
In my form, I want to use an auto-complete field for this TemoinVille variable. I use a method called 'AutocompleteTous' that works, I use it somewhere else in the form. I don't know how to write the script so that the autocomplete works for a second TemoinVille input.
My JQuery code is:
var auto5 = $('#AdtFormModel_TemoinsVille').autocomplete({
source: '#Url.Action("AutocompleteTous", "InvForm")',
minLength: 3,
delay: 400
}).data("ui-autocomplete");
auto5._renderItem = function (ul, item) {
return $("<li>")
.attr("ui-autocomplete-item", item)
.append(item.label.split("|")[0])
.appendTo(ul);
};
auto5._renderMenu = function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).addClass("dropdown-menu");
};
In my view, I have t TemoinVille textboxfor inputs:
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
the autocomplete works for the first input, but not for the second...
Here is the html code for the two inputs:
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
Any suggestions?
You are targeting an id #AdtFormModel_TemoinsVille, that's the input right?
The ID must be unique on page. So it will work only on first input it finds.
You need to target the elements by class, then the autocomplete should work in all inputs.
try something like this:
var auto5 = $('.form-control input').autocomplete({ // I suppose .form-control is a div that contains the input
Related
I have this code
<script type="text/javascript">
$(function () {
$("#temperature").change(function (e) {
// elaboration
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group" id="TemperatureGroup">
#Html.LabelFor(model => model.temperature, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.temperature, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.temperature, "", new { #class = "text-danger" })
<div id="infoPaintTemperature" class="col-md-10">
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Salva" class="btn btn-default" />
</div>
</div>
</div>
}
I need to catch if the user have press Enter key inside the input "Temperature", to prevent elaboration of "change" javascript. I can't find anywhere how to get the info of which key has been pressed inside "change" function.
Thanks for who can help
EDIT
I would like to do two different elaboration in .change() if I leave the textbox or if I press Enter inside textbox.
I am assuming you want to trigger some function (elaboration inside "change" event callback) only if the user leaves the input box.
If that is the case then you can try using the .focusout((event) => {}) method of javascript.
It will be only triggered when input is focused out and inside which you can compare the currentInput value with previousInput value and accordingly trigger run the logic.
$(function () {
let previousInput = '' // blank for first time use
$("#temperature").focusout(function(e){
// console.log(e.target.value)
if (previousInput !== e.target.value) {
// Input changed
previousInput = e.target.value
// rest of elaboration
} else {
// Input not changed
}
});
});
You could try something like this;
$('input').on('keypress', function(e) {
if (e.keyCode == '13') {
e.preventDefault();
$(this).blur()
};
});
Which when the user presses ENTER will enact blur which can also enact the change.
.preventDefault(); will stop the form submitting when ENTER is pressed.
you muse use delegate to attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements, and you can use .temperature
$( ".form-horizontal" ).delegate( ".temperature", "change", function()
{ }
I have a dropdown, when i select an item its categoryId is assigned to textbox. Then i Have 2 checkboxes 'IsAnonymous' and 'ShowReport'. I want to implement that is the value in textbox is 1 then both checkbox will be visible and when value will be 2 then 'ShowReport' checkbox must be hidden.
javascript
var ReportDiv = $('#ReportDiv');
$('#cmbCategories').on('change', function () {
if ($(this).val() == '1') {
ReportDiv.hide();
}
else {
ReportDiv.show();
}
});
View
#Html.DropDownListFor(p => p.PollSurveyId, Model.PollSurveyDetails, "Select Poll/Survey", new { #class = "form-control", required = "required", #id= "DDPollName" })
#Html.TextAreaFor(p => p.CategoryID, new {id= "cmbCategories" })
<div class="form-group">
#Html.Label("Is Anonymous")
#Html.CheckBoxFor(p => p.IsAnonymous)
</div>
</div>
<div class="col-lg-3">
<div class="form-group" id="ReportDiv">
#Html.Label("Show Report")
#Html.CheckBoxFor(p => p.ShowReport, new { id= "CBReport" })
</div>
<!-- /.col-lg-6 (nested) -->
</div>
Added a picture to give idea of my page
I am using below code for dropdown
#if (ViewBag.EventContentTypeId == Convert.ToInt32(EventContentType.Events))
{
<div class="col-sm-3 form-group input" style="padding-left:0">
<div class="input-group">
#Html.DropDownList("EventCategoryDDL", #ViewBag.EventCategories as IEnumerable<SelectListItem>, "-- Select Category --", new { #class = "form-control" })
<span class="input-group-addon">
<i class="fa fa-file-text" aria-hidden="true"></i>
</span>
</div>
</div>
}
I want to change these to multi-select dropdown with checkbox.
And this is my controller code and this is in selectlist and I am unable to modify to multiselectlist is there a way to change to multiselectlist of selectlist.
ViewBag.EventCategories = ViewBag.EventContentTypeName == EventContentTypeString.Events.Value ? _commonService.GetEventCategoriesModel().Where(category =>category.OptionText != "Camp Kaufmann").Select(i => new SelectListItem()
{
Text = i.OptionText,
Value = i.OptionValue.ToString()
})
_commonService.GetEventCategoriesModel().Select(i => new SelectListItem()
{
Text = i.OptionText,
Value = i.OptionValue.ToString()
});
And how should I change to multiselectlist in my controller side and also how to bind dropdown with check boxes of multiselect.
You can use bootstrap-multiselect plugin check this link.
Action Methods
public ActionResult Index()
{
List <SelectListItem> vegList = new List<SelectListItem>
{
new SelectListItem {Text = "Cheese",Value="1" },
new SelectListItem {Text = "Mushrooms",Value="2" },
new SelectListItem {Text = "Tomatoes",Value="3" },
new SelectListItem {Text = "Onions",Value="4" }
};
ViewBag.Vegetables = vegList;
return View();
}
[HttpPost]
public ActionResult AddVegetables(string[] VegetablesDDL)
{
var selectedVegetablesIDs = VegetablesDDL.ToList();
foreach(var selected in selectedVegetablesIDs)
{
// use selected item
}
return View();
}
View:
#using (Html.BeginForm("AddVegetables", "Home", FormMethod.Post))
{
#Html.Label("Vegetables:")
<br />
<br />
#Html.DropDownList("VegetablesDDL", #ViewBag.Vegetables as IEnumerable<SelectListItem>, "-- Select Vegetables
--", new { #class = "form-control", multiple = "multiple" })
<br />
<input type="submit" value="Submit" />
}
Script:
<script type="text/javascript">
$(document).ready(function() {
$('#VegetablesDDL').multiselect();
});
</script>
Note:
Add bootstrap-multiselect.css in head section of your page and bootstrap-multiselect.js in bottom of your page.
Also its better to use ViewModels instead of ViewBag check this.
Reference:
1.
2.
Hi I am trying to set my value in javascript + jquery in mvc 5 for textarea and checkbox but it is not working.
My javscript code is as
document.getElementById("UpdatetxtDescription").value = "abc";
document.getElementById("UpdateActive").checked = true;
my view page code is as
#Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { #class = "form-control", id = "UpdatetxtDescription" } })
#Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { #class = "form-control", id = "UpdateActive" } })
In console I am able to see
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = UpdateActive }" id="Active" name="Active" type="checkbox" value="true">
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }" id="Description" name="Description" rows="2"></textarea>
I can set value with id="Description" and id="Active" nut as I have 2 checkbox and 2 text area I can not make that id use because both the control have same id as decription for textarea and Active for checkbox
2nd textarea and checkbox are as below whose Id I have set as different
#Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { #class = "form-control", id = "txtDescription", rows = "3" } })
#Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { #class = "form-control", id = "txtDescription" } })
but in console I can see there Id as
<textarea cols="20" htmlattributes="{ class = form-control, id = txtDescription, rows = 3 }" id="Description" name="Description" rows="2"></textarea>
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = txtDescription }" id="Active" name="Active" type="checkbox" value="true">
You are setting htmlAttributes parameter of your HTML Helpers the wrong way. If you see the generated HTML, you can see that id and class are not being set. But an attribute called htmlAttributes itself is being added like this:
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }"></textarea>
So you should change it to:
#Html.TextAreaFor(model => model.Description, new { #class = "form-control", id = "UpdatetxtDescription" })
#Html.CheckBoxFor(model => model.Active, new { #class = "form-control", id = "UpdateActive" })
and
#Html.TextAreaFor(model => model.Description, new { #class = "form-control", id = "txtDescription", rows = "3" })
#Html.CheckBoxFor(model => model.Active, new { #class = "form-control", id = "txtDescription" })
(PS: If you were to submit this form, only one textarea and checkbox will be bound to model because you are creating more than one input with the same name.attribute)
The id should be unique in the same document for a valid structure, if you can't change it so you could deal with this duplication using jQuery selectors like :
$('[id="Description"]:eq(0)') //Select the first element with id "Description"
$('[id="Description"]:eq(1)') //Select the second element with id "Description"
The same thing for the second element input :
$('[id="Active"]:eq(0)') //Select the first element with id "Active"
$('[id="Active"]:eq(1)') //Select the second element with id "Active"
Hope this helps.
I am submitting the form which has the css dropdownlist for gender how to submit the gender selected value to controller i am getting tht value null
<div class="regi-field-set">
<div id="ddlgender" class='selectBox' tabindex="7">
<span class='selected' id="gender">gender</span>
<span class='selectArrow'>▼</span>
<div id="disableasterisk5" style="padding-bottom:8px"><span class="required">*</span></div>
<div class="selectOptions" id="genderSelectOptions">
<span class="selectOption" id="ddlgen">male</span>
<span class="selectOption" id="ddlgen1">female</span>
</div>
</div>
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
how to pass both value to controller all other fields in the form are using html.helper fields only gender field is css implemented
Is there any way to pass the entire model and the gender selected value to controller
please help
If I understood your question, the answer of passing to the View both the "model" and a list of something else to use in a dropdown list can be done by the following code:
Controller
....
var model = service.GetMyThing(id);
var genderList= service.GetGenders().Select(p =>
new SelectListItem { Value = p.Id.ToString(), Text = p.Name }).ToList();
ViewBag.GenderList = genderList;
return View(model);
View
....
#Html.DropDownList("GenderId",(IEnumerable<SelectListItem>)ViewBag.GenderList)
....
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
Note: this is NOT the only solution, custom HTMLHelpers can be used to draw the combo.
using ajax you can achieve this : don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hopefully it will help you