I'm trying to test whether content is in a text field, this works with initially loaded elements, but not the elements (which share the same class name) added using beginCollectionItem.
For example a textbox is added through bci and gets filled in, when filled in and focus goes elsewhere, the textbox will be given the 'makeitred' class.
What's wrong with the javascript I'm using?
partial using BCI
<div class="editorRow">
#using (Html.BeginCollectionItem("ispDetails"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.type, new { #class = "isitempty" })
</span>
</div>
</div>
}
</div>
Index segment calling partial - on page load elements the jQuery works, anything there after using the add button doesn't
#using (Html.BeginForm())
{
<div id="editorRowsEQM">
#foreach (var item in Model.ispDetails)
{
#Html.Partial("EquipView", item)
}
</div>
#Html.ActionLink("Add", "ispManager", null, new { id = "addItemEQM", #class = "button" });
}
JS from the Index
$(function () {
$('#addItemEQM').on('click', function () {
$.ajax({
url: '#Url.Action("ispManager")',
cache: false,
success: function (html) { $("#editorRowsEQM").append(html); }
});
return false;
});
$(document).on('change', '.isitempty', function checkFill (e) {
if ($(this).val().length == 0) {
$(this).removeClass('makeitred');
} else $(this).addClass('makeitred');
});
});
Related
I have a razor page where evrything is displaying fine, but I need to be able to read the values inside a few controllers to pass them as parameters in an call to prefilter some data:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filters</h3>
<div class="col-12">
<select id="portMultiselect" name="lsPorts" asp-items="#Model.Ports" multiple></select>
<input id="searchString" type="text" name="searchString">
</div>
</div>
#* A "REFRESHABLE" TABLE GOES HERE...*#
#section scripts{
#* REFRESH SCRIPT *#
<script type="text/javascript">
$(function () {
setInterval(loadTable, 60000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value;
if (searchString != "" || selectedPorts.length != 0) {
debugger;
}
fetch('/Index?handler=IndexPartial', {
data: {
searchString: searchString,
selectedPorts: selectedPorts
}
})
.then((response) => {
return response.text();
})
.then((result) => {
document.getElementById('refreshable').innerHTML = result;
});
}
</script>
}
As you can see, I'm trying to capture the selected values in my multiselect and in a text input to pass as parameters in the refresh script.
I'm correctly arriving to the expected endpoint, but Im never getting any values (It's always empty and zero) I even added a debugger in the Javascript code that I'm never hitting.
Why can't I read those values?
EDIT:
I have seen other ways of dealing with these, such as databindings, but as mentioned here, the only way to avoid page reload is javascript and AJAX, so I still need to get these values from the javascript.
At the end, I found a solution to my predicament as follows:
I changed the way I render the selectPicker, following the examples shown in this page:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filtros</h3>
<div class="row">
<div class="col-6">
<p>Puertos</p>
#Html.DropDownListFor(x =>
x.selectPort,
(IEnumerable<SelectListItem>)ViewData["MyPorts"],
new
{
#id = "portMultiselect",
#class = "form-control selectpicker",
#Value = #Model.Ports,
data_live_search = "true",
multiple = "multiple"
})
</div>
<div class="col-6">
<p>Nombre de variable</p>
<input id="searchString" type="text" name="searchString">
</div>
</div>
</div>
This comes with certain changes to the model you're working with, you can follow instructions to bind data as T.Trassoudaine commmented, here
for this to work you need to add the specified references in your _Layout (for the bootstrap-select), you can check all the things you need to add here
And finally, you will need to work with AJAX in javascript to pass the parameters back:
<script type="text/javascript">
$(function () {
setInterval(loadTable, 1000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value.toUpperCase();
var searchPorts = "";
if (selectedPorts.length != 0) {
searchPorts = selectedPorts.join(",");
}
$.ajax({
url: '/?handler=IndexPartial',
data: {
searchString: searchString,
searchPorts: searchPorts
},
success: function (data) {
document.getElementById('refreshable').innerHTML = data;
}
})
}
</script>
I have a search functionality which already works by searching the data that the user requests. I would like to add a clear button for the user to be able to clear the search bar, at the moment the user has to clear the search using the "backspace" button and press "enter to go back the page with all the data. I am a expert in front end so would appreciate some help thank you in advance.
Javascript
$(function () {
$("#SearchString").autocomplete({
source: '#Url.Action("GetUserJSON")',
minLength: 1
})
});
$(function () {
$("#SearchString").focus();
});
$(function () ) {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
});
};
Razor HTML
#using (Html.BeginForm("Index", "User", FormMethod.Get, null))
{
<div class="search-wrap">
#Html.TextBoxFor(m => m.SearchString, new { id = "SearchString", #class = "lookup txt-search js-autocomplete-submit", #placeholder = "Search", #type ="search" })
#*<img src="~/Content/Images/close.png" id ="closebutton"/>*#
<button type="button" id="clearbutton">Click Me!</button>
<i onclick="submitform()" class="btn-search fa fa-search"></i>
</div>
}
C# Class where data get pull from
public JsonResult GetUserJSON(string term)
{
var stores = (from st in UserLogic.GetUserIndex(1, term).IndexList
select new { st.Username, st.FirstName, st.LastName }).ToList();
List<String> returnList = new List<string>();
foreach (var item in stores)
{
if (item.Username.ToString().ToUpper().StartsWith(term.ToUpper()))
{
returnList.Add(item.Username.ToString());
}
else if (item.FirstName.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.FirstName);
}
else if (item.Username.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.Username);
}
}
returnList = returnList.Distinct().OrderByAlphaNumeric(s => s).ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}
I think this is what you need:
$(function () {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
$("#SearchString").val("")
});
});
Add $("#SearchString").val("") to your clearbutton click event
Edit:
You have mistyped the function for clearSearch
this is working example
please try using this
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close').val('');
});
My page has 2 main parts:
1: part one is shown with form load.
2: part two is shown using ajax call based on clicking the button in part 1.
In part two, I have 3 subparts:
2-1: first is info.
2-2: second is a checkbox.
2-3: third is as a form for create a request (contains input text boxes).
2-2 will be shown if an int parameter is less or equal to zero.
2-3 will be shown if the parameter is bigger than zero, or the checkbox above is checked.
But it doesn't work.
UPDATE: The conditions has no affects on the useNextPeriodConfirm and the request div. Their display is none as initial time.
[HttpGet]
public ActionResult Create()
{
return View();
}
The view:
....
<script>
var id;
$(function() {
$("#getCipContent").click(function() {
loadCipContent();
});
});
function loadCipContent() {
$.ajax({
url: ........../GetFilledContent/' + id,
type: 'get',
success: function(data) {
$("#cipContent").html(data);
}
});
};
</script>
The action method for ajax call:
[HttpGet]
public ActionResult GetFilledContent(string id)
{
.......
ViewBag.Requests = Requests;
if (Requests[0].RemaindQuota <= 0)
{
ViewBag.FromNextPeroidQuota = true;
}
return PartialView("_GetFilledContent", myModel);
}
And the partial view:
#model MyModel
<div>
PAERT 2-1
</div>
<div id="useNextPeriodConfirm" class="row" style="display: none">
#Html.CheckBox("useNextPeriod", false, new { style = "display: inline-block", onchange ="useNextPeriod(this);" })
<label style="display: inline">I am agree</label>
</div>
<div id="request" style="display: none;">
</div>
<script>
window.setTimeout(function() {
if (#ViewBag.FromNextPeroidQuota === true) {
$("#request").hide();
$("#useNextPeriodConfirm").show();
} else {
$("#useNextPeriodConfirm").hide();
$("#request").show();
};
}, 100);
function useNextPeriod(item) {
if (item.checked) {
$("#request").show();
} else {
$("#request").hide();
}
}
</script>
I have the following checkbox:
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Once this is checked, I want it to auto update my dropdown
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets)
The dropdown selectlist is populated from my controller like this,
ViewBag.CoreSheets = new SelectList(db.CoreSheets, "sheetID", "Abb");
So in summary, I want to click the check box and have the current dropdown value be updated.
Cheers,
B
N J
Try this code
#Html.CheckBox("Norm", false, new { #class = "checkbox",#onclick="clickNorm()" })
<script type="text/javascript">
function clickNorm(){
$.ajax({
url:'#Url.Action("LoadSelectedCoreList")'
dataType:'json',
success:function(res){
if(res && res.length>0){
$('#selectedCore).empty();
$.each(res,function(index,item){
$('#selectedCore').append(new Option(item.Abb,item.sheetID));
});
}
}
});
</script>
In Coltroller
public ActionResult LoadSelectedCoreList()
{
var selectedCoreList=..
return Json(selectedCoreList,
JsonRequestBehavior.AllowGet);
}
I solved this myself by doing the following,
Check box
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Jquery
<script type="text/javascript">
$(document).ready(function() {
$("#Norm").on("click", function () {
if ($(this).is(":checked")) {
$("#kammcoreauto").val(1);
$("#kammfaceauto").val(1);
$("#spacecoreauto").val(1);
$("#Washercoreauto").val(1);
$("#IsoCoreauto").val(1);
$("#IsoFaceauto").val(1);
}
});
});
</script>
and this just refers to the id of the dropdowns that you can add like this
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets, new { id = "kammcoreauto" })
Big Thanks to everyone who tried to help
I try to make following parts run, but always failed. The objective is: if a target in combobox is selected, the mediaId's combobox should be filled with respective values. At this moment I just emulate the values of mediaId combobox. Can anyone show me how to combine them correctly? Thx in advance.
The view Medium.cshtml:
<script src="#Url.Content("~/Scripts/PartialLoad.js")" type="text/javascript"></script>
<div class="editor-label">
#Html.LabelFor(model => model.Files[i].TargetId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Files[i].PTargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId))
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Files[i].MediaId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Files[i].MediaId, (ViewData["mediaIds"] as SelectList).MakeSelection(1))
</div>
The javascript partialload.js
$(document).ready(function () {
$("#targets").change(function () { GetMValues("#targets", "#mediaIds"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMValues(objSource, objDest) {
var url = '/GetMValues/';
$.getJSON(url, { id: $(objSource).val() },
function (data) {
ClearDrop(objDest); $.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
The homecontroller.cs
public ActionResult GetMValues(String id)
{
int myId = 0;
int.TryParse(id, out myId);
var mediumIds = new List<long>();
int max = myId + 3;
// just to emulate the data in the list
for ( long l = 1 ; l < max ; l++ ){
mediumIds.Add(l);
}
var select = new SelectList(mediumIds, "PTargetId", "TargetId");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}
Here you are using an id selector for the dropdownlist: $("#targets") but your dropdown doesn't seem to have such id. Maybe you want to assign it an id or a class:
#Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { id = "targets" }
)
But because this seems to be repeated and you cannot have multiple elements with the same id a class selector is probably more appropriate:
#Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { #class = "targets" }
)
and then:
$(document).ready(function () {
$(".targets").change(function () {
...
});
});
Same remark obviously for #mediaIds.