Я работаю с существующей формой, которая является HTML и Java. Существует один выбор по умолчанию, доступный для «транспортного протокола», который заполняется XML. Мне интересно, как установить значение «по умолчанию» для этого конкретного SelectList при загрузке или даже установить его и сделать поле скрытым. Это мой первый пост, поэтому любая помощь будет очень оценена. < /P>
$(document).ready(function () {
/* Location Search */
$("#locationsTextSearch").on("input", GetTableData);
$("#locationsTextSearch").on("focus", function () {
$("#icon-search").addClass("icon-search-blue");
});
$("#locationsTextSearch").on("focusout", function () {
$("#icon-search").removeClass("icon-search-blue");
});
// default warning to NotWarned in xamarin
if (!CefSharpEnabled) {
$("#transportationwarning").val("NotWarned");
}
// Clicking procced is the same as submit
$("#proceedButton").click(function () {
$("#Form").submit();
});
//Set up Tab control
$('.tabs').tabs();
//handle form submition
$("#Form").submit(function () {
if (ValidateLocationForms() && $(this)[0].checkValidity() == true) {
// Show confim if needed
ShowConfirm($(this));
}
ValidateRequiredSingleSelectOnly($("#transportationprotocol"));
ValidateRequiredSingleSelectOnly($("#transportationpriority"));
return false;
});
//focus on registration id field
$("#currentodometer").focus();
});
function decimalCheck(input, event) {
var str = input.value;
if (event.keyCode == 69) {
return false;
}
else if (str.includes(".") && !isNaN(event.key)) {
var index = str.indexOf(".");
if (str.length - index > 1) {
return false;
}
}
return true;
}
function lengthCheck(input) {
if (input.value.includes(".")) {
if (input.value.length > input.maxLength + 2) {
input.value = input.value.slice(0, input.maxLength);
}
}
else {
if (input.value.length > input.maxLength) {
input.value = input.value.slice(0, input.maxLength);
}
}
return input;
}
function AfterFillForm() {
GenerateSelectBox("transportationprotocol", "transportprotocol.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#protocolvals").prepend(result);
SetSelectBoxFromParameters($("#transportationprotocol"));
$("#transportationprotocol").prop("required", true);
$("#transportationprotocol").change(function () {
ValidateRequiredSingleSelectOnly($(this));
// Reload divert panel when changing protocol
LoadDiverts();
});
// Load diverts on initial load when diverts are passed in. Wait till this time so that the protocol has been set and the list is filtered correctly
LoadDiverts();
GenerateSelectBox("transportationpriority", "transportpriority.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#priorityvals").prepend(result);
SetSelectBoxFromParameters($("#transportationpriority"));
$("#transportationpriority").prop("required", true);
$("#transportationpriority").change(function () {
ValidateRequiredSingleSelectOnly($(this));
});
GenerateSelectBox("gender", "Gender.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#gendervals").prepend(result);
SetSelectBoxFromParameters($("#gender"));
GenerateSelectBox("transportstate", "state.xml", "genericselectvalue.xsl", false, false, false, 1, false, false).then(function (result) {
$("#statevals").prepend(result);
SetSelectBoxFromParameters($("#transportstate"));
setVerifiedAddress();
AfterAllControlsInitialized(); // must go after last select intialized
//GenerateSelectBox("Race", "Race.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
// $("#racevals").prepend(result);
// SetSelectBoxFromParameters($("#Race"));
//});
});
});
});
});
// initialze modal
if (!CefSharpEnabled)//xamarin only
{
$('.modal').modal();
}
setDefaultLocation();
SetCurrentTab();
}
function SetCurrentTab() {
var selectedAddressTab = $("#SelectedAddressTab").val();
if (selectedAddressTab == "locationtab") {
$("#tab1").children()[0].click();
}
else {
$("#tab2").children()[0].click();
$("#SelectedAddressTab").val(selectedAddressTab);
}
}
function GetCurrentTab() {
var selectedAddressTab = $("#SelectedAddressTab").val();
if (selectedAddressTab == "locationtab") {
return "locationtab";
}
else {
return "addresstab";
}
}
function GetFacilityDiverts(locationName) {
// request facility divert for location
if (!CefSharpEnabled) { // Xamarin only
var param = {
_method: 'getFacilityDiverts',
_locationName: locationName
}
invokeCSharp(JSON.stringify(param));
}
}
// called by c# whenthe facility divert request returns
function FacilityDivertReturn(diverts) {
if (diverts) {
var response = JSON.parse(diverts);
var currentTab = GetCurrentTab();
// if the user has selected another location or changed the tab since this facility divert status was requested just throw away the response
if (response.locationName == $("#Form").data("lastQueriedLocation") && currentTab == $("#Form").data("selectedTabForLastQuery")) {
LoadDiverts(response.diverts);
}
}
}
// call by c# when loading the transport form from a status error with divert information already contained
function SetDiverts(diverts) {
diverts = JSON.parse(diverts);
var currentTab = GetCurrentTab();
$("#" + currentTab).data("diverts", diverts);
}
function LoadDiverts(diverts) {
if (!diverts) {
diverts = $("#" + GetCurrentTab()).data("diverts")
}
// clear diver panel if there are no diverts
if (diverts && diverts.length > 0) {
BuildDiverts(diverts);
}
else {
ClearDiverts();
}
}
function BuildDiverts(diverts) {
// cache diverts to current tab
var currentTab = GetCurrentTab();
$("#" + currentTab).data("diverts", diverts);
// clear DOM
$("#divertListRow,#divertChipList,#divert_modal_reasons").empty();
var allReasons = [];
var visibleDiverts = 0;
var currentProtocol = $("#protocolvals .dropdown-trigger").val();
// process all diverts
for (var i = 0; i < diverts.length; i++) {
var divert = diverts;
// find if current divert matches selected protocol
var divertReasons = "";
for (var j = 0; j < divert.Reason.length; j++) {
var reason = divert.Reason[j];
if (!currentProtocol || !reason.Protocols || reason.Protocols.split(",").includes(currentProtocol)) {
divertReasons += reason.Name + " \u2014 "; // add dash character
if (!allReasons.includes(reason.Name)) {
allReasons.push(reason.Name); // keep list of unique reasons so we dont duplicate chips also used by modal
// Add chip for each reason
var $chip = $('' + reason.Name + '');
$chip.click((e) => {
var $e = $(e.currentTarget);
$("#divertListRow div:contains(" + $e.text() + ")")[0].scrollIntoView();
})
$("#divertChipList").append($chip);
}
}
}
// Build card for divert if it has matching reasons
if (divertReasons) {
visibleDiverts++;
$("#divertLocationName").text(divert.LocationName.toUpperCase());
divertReasons = divertReasons.substring(0, divertReasons.length - 3);
if (!divert.EndDate) {
divert.EndDate = "N/A";
}
var $divertRow = $('');
$divertRow.append('' + divertReasons + '');
var $timeRow = $('');
$timeRow.append('Starts:' + divert.StartDate + '');
$timeRow.append('Ends:' + divert.EndDate + '');
$divertRow.append($timeRow);
if (divert.Comments) {
$divertRow.append('' + divert.Comments + '');
}
$("#divertListRow").append($divertRow);
}
}
// if we have divert that matches selected protocol show divert panel
if (visibleDiverts > 0) {
// Show chips
if (visibleDiverts > 1) {
$("#divertChipsRow").show();
}
else {
$("#divertChipsRow").hide();
}
// Update modal
$("#divert_modal_msg").text("You will procced to " + divert.LocationName + ", which has the follow diverts:");
for (var k = 0; k < allReasons.length; k++) {
if (k % 2 == 0) {
var $modalRow = $('');
$("#divert_modal_reasons").append($modalRow);
}
$modalRow.append('- ' + allReasons[k] + '');
}
ShowDivertPanel();
}
else {
HideDivertPanel();
}
}
function ClearDiverts() {
// clear cached diverts
var currentTab = GetCurrentTab();
$("#" + currentTab).removeData("diverts");
HideDivertPanel();
}
function ShowDivertPanel() {
// Update html to not shrink when divert panel is shown
$(".Flex-Form-Diverts").show();
$(".Flex-Form-MainContent > div").css("margin-right", "20px");
$(".Flex-Form-MainContent > .col > .row > .s2").removeClass("s2").addClass("s4");
$(".Flex-Form-MainContent > .col > .row > .s6").removeClass("s6").addClass("s12");
$(".Flex-Form-MainContent > .col > .row > .row .s8").removeClass("s8").addClass("s12");
$(".Flex-Form-MainContent .tab.s2").removeClass("s2").addClass("s4");
$("#addresstab .input-field.s2").removeClass("s2").addClass("s3");
$("#addresstab .input-field.s4").removeClass("s4").addClass("s6");
$('.tabs').tabs();
}
function HideDivertPanel() {
// Update html to not grow when divert panel is hidden
$(".Flex-Form-Diverts").hide();
$(".Flex-Form-MainContent > div").css("margin-right", "41px");
$(".Flex-Form-MainContent > .col > .row > .s4").removeClass("s4").addClass("s2");
$(".Flex-Form-MainContent > .col > .row > .s12").removeClass("s12").addClass("s6");
$(".Flex-Form-MainContent > .col > .row > .row .s12").removeClass("s12").addClass("s8");
$(".Flex-Form-MainContent .tab.s4").removeClass("s4").addClass("s2");
$("#addresstab .input-field.s3").removeClass("s3").addClass("s2");
$("#addresstab .input-field.s6").removeClass("s6").addClass("s4");
$('.tabs').tabs();
}
function LocationSelected(value) {
if (value) {
// if a different location is selected rerun query
if (value != $("#Form").data("lastQueriedLocation")) {
GetFacilityDiverts(value);
$("#Form").data("selectedTabForLastQuery", GetCurrentTab());
// always clear diverts when requesting diverts for a new location
ClearDiverts();
}
}
// if selecting an address without a value we still want to invalidate previous queries
$("#Form").data("lastQueriedLocation", value);
}
function LocationCleared() {
// clear last queried location when clearing location so that outstanding divert request are ignored
$("#Form").data("lastQueriedLocation", "");
ClearDiverts();
}
function AfterTabChanged(value) {
// each tab can have different cached set of diverts for the location selected under that address.
// reload panel after changing tab
LoadDiverts();
}
async function ShowConfirm($form) {
// if divert panel is visible show modal for confirmation
var allowSubmit = true;
if ($(".Flex-Form-Diverts").is(":visible")) {
allowSubmit = await openModal('PROCEED TO LOCATION?');
if (allowSubmit) {
// if the select confim then updat this flag to allow the server to bypass validation of divert status
$("#transportationwarning").val("Warned");
}
}
if (allowSubmit) {
$(':disabled').each(function (e) {
$(this).removeAttr('disabled');
})
// If we are submitting with the address tab selected dont submit a location.
// This can cause a bug were the wrong location is passed to the business layer
var currentTab = GetCurrentTab();
if (currentTab != "locationtab") {
$("#location").val("");
}
var values = $form.serialize();
SubmitQuery(values, $form.attr('action'));
}
}
< /code>
TRANSPORT
Current Odometer
Transport Protocol
Transport Priority
Number Transported
< /code>
I've tried looking for solutions, unfortunately all i can find are solutions where the values are laid out in the html and set as selected there. The form is not complete due to the character limit, but i attempted to include the relevant sections
Подробнее здесь: https://stackoverflow.com/questions/795 ... selectlist
Установка значения по умолчанию на динамически сгенерированный SelectList ⇐ Javascript
Форум по Javascript
1741988815
Anonymous
Я работаю с существующей формой, которая является HTML и Java. Существует один выбор по умолчанию, доступный для «транспортного протокола», который заполняется XML. Мне интересно, как установить значение «по умолчанию» для этого конкретного SelectList при загрузке или даже установить его и сделать поле скрытым. Это мой первый пост, поэтому любая помощь будет очень оценена. < /P>
$(document).ready(function () {
/* Location Search */
$("#locationsTextSearch").on("input", GetTableData);
$("#locationsTextSearch").on("focus", function () {
$("#icon-search").addClass("icon-search-blue");
});
$("#locationsTextSearch").on("focusout", function () {
$("#icon-search").removeClass("icon-search-blue");
});
// default warning to NotWarned in xamarin
if (!CefSharpEnabled) {
$("#transportationwarning").val("NotWarned");
}
// Clicking procced is the same as submit
$("#proceedButton").click(function () {
$("#Form").submit();
});
//Set up Tab control
$('.tabs').tabs();
//handle form submition
$("#Form").submit(function () {
if (ValidateLocationForms() && $(this)[0].checkValidity() == true) {
// Show confim if needed
ShowConfirm($(this));
}
ValidateRequiredSingleSelectOnly($("#transportationprotocol"));
ValidateRequiredSingleSelectOnly($("#transportationpriority"));
return false;
});
//focus on registration id field
$("#currentodometer").focus();
});
function decimalCheck(input, event) {
var str = input.value;
if (event.keyCode == 69) {
return false;
}
else if (str.includes(".") && !isNaN(event.key)) {
var index = str.indexOf(".");
if (str.length - index > 1) {
return false;
}
}
return true;
}
function lengthCheck(input) {
if (input.value.includes(".")) {
if (input.value.length > input.maxLength + 2) {
input.value = input.value.slice(0, input.maxLength);
}
}
else {
if (input.value.length > input.maxLength) {
input.value = input.value.slice(0, input.maxLength);
}
}
return input;
}
function AfterFillForm() {
GenerateSelectBox("transportationprotocol", "transportprotocol.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#protocolvals").prepend(result);
SetSelectBoxFromParameters($("#transportationprotocol"));
$("#transportationprotocol").prop("required", true);
$("#transportationprotocol").change(function () {
ValidateRequiredSingleSelectOnly($(this));
// Reload divert panel when changing protocol
LoadDiverts();
});
// Load diverts on initial load when diverts are passed in. Wait till this time so that the protocol has been set and the list is filtered correctly
LoadDiverts();
GenerateSelectBox("transportationpriority", "transportpriority.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#priorityvals").prepend(result);
SetSelectBoxFromParameters($("#transportationpriority"));
$("#transportationpriority").prop("required", true);
$("#transportationpriority").change(function () {
ValidateRequiredSingleSelectOnly($(this));
});
GenerateSelectBox("gender", "Gender.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
$("#gendervals").prepend(result);
SetSelectBoxFromParameters($("#gender"));
GenerateSelectBox("transportstate", "state.xml", "genericselectvalue.xsl", false, false, false, 1, false, false).then(function (result) {
$("#statevals").prepend(result);
SetSelectBoxFromParameters($("#transportstate"));
setVerifiedAddress();
AfterAllControlsInitialized(); // must go after last select intialized
//GenerateSelectBox("Race", "Race.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
// $("#racevals").prepend(result);
// SetSelectBoxFromParameters($("#Race"));
//});
});
});
});
});
// initialze modal
if (!CefSharpEnabled)//xamarin only
{
$('.modal').modal();
}
setDefaultLocation();
SetCurrentTab();
}
function SetCurrentTab() {
var selectedAddressTab = $("#SelectedAddressTab").val();
if (selectedAddressTab == "locationtab") {
$("#tab1").children()[0].click();
}
else {
$("#tab2").children()[0].click();
$("#SelectedAddressTab").val(selectedAddressTab);
}
}
function GetCurrentTab() {
var selectedAddressTab = $("#SelectedAddressTab").val();
if (selectedAddressTab == "locationtab") {
return "locationtab";
}
else {
return "addresstab";
}
}
function GetFacilityDiverts(locationName) {
// request facility divert for location
if (!CefSharpEnabled) { // Xamarin only
var param = {
_method: 'getFacilityDiverts',
_locationName: locationName
}
invokeCSharp(JSON.stringify(param));
}
}
// called by c# whenthe facility divert request returns
function FacilityDivertReturn(diverts) {
if (diverts) {
var response = JSON.parse(diverts);
var currentTab = GetCurrentTab();
// if the user has selected another location or changed the tab since this facility divert status was requested just throw away the response
if (response.locationName == $("#Form").data("lastQueriedLocation") && currentTab == $("#Form").data("selectedTabForLastQuery")) {
LoadDiverts(response.diverts);
}
}
}
// call by c# when loading the transport form from a status error with divert information already contained
function SetDiverts(diverts) {
diverts = JSON.parse(diverts);
var currentTab = GetCurrentTab();
$("#" + currentTab).data("diverts", diverts);
}
function LoadDiverts(diverts) {
if (!diverts) {
diverts = $("#" + GetCurrentTab()).data("diverts")
}
// clear diver panel if there are no diverts
if (diverts && diverts.length > 0) {
BuildDiverts(diverts);
}
else {
ClearDiverts();
}
}
function BuildDiverts(diverts) {
// cache diverts to current tab
var currentTab = GetCurrentTab();
$("#" + currentTab).data("diverts", diverts);
// clear DOM
$("#divertListRow,#divertChipList,#divert_modal_reasons").empty();
var allReasons = [];
var visibleDiverts = 0;
var currentProtocol = $("#protocolvals .dropdown-trigger").val();
// process all diverts
for (var i = 0; i < diverts.length; i++) {
var divert = diverts[i];
// find if current divert matches selected protocol
var divertReasons = "";
for (var j = 0; j < divert.Reason.length; j++) {
var reason = divert.Reason[j];
if (!currentProtocol || !reason.Protocols || reason.Protocols.split(",").includes(currentProtocol)) {
divertReasons += reason.Name + " \u2014 "; // add dash character
if (!allReasons.includes(reason.Name)) {
allReasons.push(reason.Name); // keep list of unique reasons so we dont duplicate chips also used by modal
// Add chip for each reason
var $chip = $('' + reason.Name + '');
$chip.click((e) => {
var $e = $(e.currentTarget);
$("#divertListRow div:contains(" + $e.text() + ")")[0].scrollIntoView();
})
$("#divertChipList").append($chip);
}
}
}
// Build card for divert if it has matching reasons
if (divertReasons) {
visibleDiverts++;
$("#divertLocationName").text(divert.LocationName.toUpperCase());
divertReasons = divertReasons.substring(0, divertReasons.length - 3);
if (!divert.EndDate) {
divert.EndDate = "N/A";
}
var $divertRow = $('');
$divertRow.append('' + divertReasons + '');
var $timeRow = $('');
$timeRow.append('[i][/i]Starts:' + divert.StartDate + '');
$timeRow.append('Ends:' + divert.EndDate + '');
$divertRow.append($timeRow);
if (divert.Comments) {
$divertRow.append('' + divert.Comments + '');
}
$("#divertListRow").append($divertRow);
}
}
// if we have divert that matches selected protocol show divert panel
if (visibleDiverts > 0) {
// Show chips
if (visibleDiverts > 1) {
$("#divertChipsRow").show();
}
else {
$("#divertChipsRow").hide();
}
// Update modal
$("#divert_modal_msg").text("You will procced to " + divert.LocationName + ", which has the follow diverts:");
for (var k = 0; k < allReasons.length; k++) {
if (k % 2 == 0) {
var $modalRow = $('');
$("#divert_modal_reasons").append($modalRow);
}
$modalRow.append('- ' + allReasons[k] + '');
}
ShowDivertPanel();
}
else {
HideDivertPanel();
}
}
function ClearDiverts() {
// clear cached diverts
var currentTab = GetCurrentTab();
$("#" + currentTab).removeData("diverts");
HideDivertPanel();
}
function ShowDivertPanel() {
// Update html to not shrink when divert panel is shown
$(".Flex-Form-Diverts").show();
$(".Flex-Form-MainContent > div").css("margin-right", "20px");
$(".Flex-Form-MainContent > .col > .row > .s2").removeClass("s2").addClass("s4");
$(".Flex-Form-MainContent > .col > .row > .s6").removeClass("s6").addClass("s12");
$(".Flex-Form-MainContent > .col > .row > .row .s8").removeClass("s8").addClass("s12");
$(".Flex-Form-MainContent .tab.s2").removeClass("s2").addClass("s4");
$("#addresstab .input-field.s2").removeClass("s2").addClass("s3");
$("#addresstab .input-field.s4").removeClass("s4").addClass("s6");
$('.tabs').tabs();
}
function HideDivertPanel() {
// Update html to not grow when divert panel is hidden
$(".Flex-Form-Diverts").hide();
$(".Flex-Form-MainContent > div").css("margin-right", "41px");
$(".Flex-Form-MainContent > .col > .row > .s4").removeClass("s4").addClass("s2");
$(".Flex-Form-MainContent > .col > .row > .s12").removeClass("s12").addClass("s6");
$(".Flex-Form-MainContent > .col > .row > .row .s12").removeClass("s12").addClass("s8");
$(".Flex-Form-MainContent .tab.s4").removeClass("s4").addClass("s2");
$("#addresstab .input-field.s3").removeClass("s3").addClass("s2");
$("#addresstab .input-field.s6").removeClass("s6").addClass("s4");
$('.tabs').tabs();
}
function LocationSelected(value) {
if (value) {
// if a different location is selected rerun query
if (value != $("#Form").data("lastQueriedLocation")) {
GetFacilityDiverts(value);
$("#Form").data("selectedTabForLastQuery", GetCurrentTab());
// always clear diverts when requesting diverts for a new location
ClearDiverts();
}
}
// if selecting an address without a value we still want to invalidate previous queries
$("#Form").data("lastQueriedLocation", value);
}
function LocationCleared() {
// clear last queried location when clearing location so that outstanding divert request are ignored
$("#Form").data("lastQueriedLocation", "");
ClearDiverts();
}
function AfterTabChanged(value) {
// each tab can have different cached set of diverts for the location selected under that address.
// reload panel after changing tab
LoadDiverts();
}
async function ShowConfirm($form) {
// if divert panel is visible show modal for confirmation
var allowSubmit = true;
if ($(".Flex-Form-Diverts").is(":visible")) {
allowSubmit = await openModal('PROCEED TO LOCATION?');
if (allowSubmit) {
// if the select confim then updat this flag to allow the server to bypass validation of divert status
$("#transportationwarning").val("Warned");
}
}
if (allowSubmit) {
$(':disabled').each(function (e) {
$(this).removeAttr('disabled');
})
// If we are submitting with the address tab selected dont submit a location.
// This can cause a bug were the wrong location is passed to the business layer
var currentTab = GetCurrentTab();
if (currentTab != "locationtab") {
$("#location").val("");
}
var values = $form.serialize();
SubmitQuery(values, $form.attr('action'));
}
}
< /code>
TRANSPORT
Current Odometer
Transport Protocol
Transport Priority
Number Transported
< /code>
I've tried looking for solutions, unfortunately all i can find are solutions where the values are laid out in the html and set as selected there. The form is not complete due to the character limit, but i attempted to include the relevant sections
Подробнее здесь: [url]https://stackoverflow.com/questions/79510287/setting-a-default-value-on-a-dynamically-generated-selectlist[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия