What's happening:
I have a form in a modal where the user inputs data. The form is only populated with data when opening the modal, not after submission. The form's action InsertLabelDefectRobotsT returns a return NoContent(); When the form is submitted the modal stays open and I clear the input values to allow new submissions.
Now, I have two dropdowns (Célula and Defeito), when changing the first one the visible options of the second one will change. My problem is that after submitting a set of values, if I change the first dropdown value and then change it back the option I submitted before disappears (this only happens if I submit the form and only the option I submitted disappears).
I have no clue why this is happening... and this is a very specific question, but if you have any leads I appreciate it.
Modal
Modal.html
<form id="formDefectsRobots" method="post" asp-action="InsertLabelDefectRobotsT" asp-controller="Labels" onsubmit="onSubmit(this);onSubmit2()">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="CellId"></label>
<select id="select1DefectsRobots" asp-for="CellId" asp-items="Model.Cells" class="custom-select">
<option value="">--</option>
</select>
<span asp-validation-for="CellId" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="DefectName"></label>
<select id="select2DefectsRobots" asp-for="DefectName" asp-items="Model.Defects" class="custom-select defectsSelect">
<option value="">--</option>
</select>
<span asp-validation-for="DefectName" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Quantity"></label>
<input class="form-control form-control-sm numpad defectsSelect" asp-for="Quantity" />
<span asp-validation-for="Quantity" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label asp-for="Details"></label>
<input type="text" class="form-control form-control-sm defectsSelect" asp-for="Details" />
<span asp-validation-for="Details" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<div class="col-md-12">
<button type="button" class="btn btn-dark" data-dismiss="modal"><i class="fas fa-arrow-left mr-2"></i>Cancelar</button>
<button type="button" class="btn btn-success" onclick="doSomething();submitDefectsRobots(this)"><i class="fas fa-play-circle mr-2"></i>Introduzir Defeito</button>
</div>
</div>
</form>
<script>
//Changes second Select based on the first
$("#select1DefectsRobots").change(function () {
if ($(this).data('options') === undefined) {
//Taking an array of all options-2 and kind of embedding it on the select1
$(this).data('options', $('#select2DefectsRobots option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2DefectsRobots').html(options);
});
//This changes the val of the select option to it's text.
function doSomething() {
$('#select2DefectsRobots option:selected').val($('#select2DefectsRobots option:selected').text());
};
//Clear some values
function onSubmit2() {
setTimeout(function () {
$('.defectsSelect').val('');
}, 1000);
};
</script>
script.js
function submitDefectsRobots(button) {
$form = $('#formDefectsRobots');
if ($form.valid()) {
Swal.fire({
title: "Inserir Defeito?",
text: "Esta acção irá inserir um novo registo de defeito.",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancelar',
confirmButtonText: 'Confirmar',
animation: false,
focusCancel: true
}).then((willSubmit) => {
if (willSubmit.value) {
$form.submit();
hideOverlay();
setTimeout(function () {
toastr.success("Defeitos Inseridos");
}, 1000);
}
})
}
}
Before submission (two "defeito" options appear on 3.9.V and one on 3.9.Y)
After submission on 3.9.V (Values Cleared, Still two options on 3.9.V)
After submission (Changed to "Célula" 3.9.Y and when changing back to 3.9.V only one "defeito" option appears now)
I found it: since I was changing the val of the selected option on submit, it would not work on the next time.
//This changes the val of the select option to it's text.
function doSomething() {
$('#select2DefectsRobots option:selected').val($('#select2DefectsRobots option:selected').text());
};
Related
first I have a form that placed inside a modal, this is the form:
<form id="kt_modal_add_menu_form" class="form" action="{{route('administrator....')}}" method="POST">
#csrf
{{-- begin: scroll --}}
<div class="d-flex flex-column scroll-y me-n7 pe-7" id="kt_modal_add_menu_scroll" data-kt-scroll="true" data-kt-scroll-activate="{default: false, lg: true}" data-kt-scroll-max-height="auto" data-kt-scroll-dependencies="#kt_modal_add_menu_header" data-kt-scroll-wrappers="#kt_modal_add_menu_scroll" data-kt-scroll-offset="300px">
<div class="fv-row mb-7">
<label class="required fw-semibold fs-6 mb-2">Menu Name</label>
<input id="menu-name" type="text" name="menu_name" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Menu Name" />
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Module Name</label>
<select name="module_name" aria-label="Select the module" data-control="select2" data-placeholder="Select module" class="form-select form-select-solid"
data-dropdown-parent="#kt_modal_add_menu_scroll" id="select-module-name">
<option value="New Module" selected>New Module</option>
#foreach ($allModule as $module)
<option value="{{$module->module_name}}">
<b>{{$module->module_name}}</b>
</option>
#endforeach
</select>
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Parent</label>
<select name="parent_id" aria-label="Select the Parent" data-control="select2" data-placeholder="Select parent" class="form-select form-select-solid"
data-dropdown-parent="#kt_modal_add_menu_scroll" id="select-parent">
<option value=""></option>
</select>
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Routes Name</label>
<input id="route-name" type="text" name="routes_name" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Routes Name e.g. administrator.menu.menu-list-page" />
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Routes URL</label>
<input id="route-url" type="text" name="url_routes" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Routes URL e.g. modules/parent/url_name" />
</div>
</div>
{{-- end: scroll --}}
<div class="text-center pt-15">
<button type="reset" class="btn btn-light me-3" data-kt-users-modal-action="cancel">Discard</button>
<button type="submit" class="btn btn-primary" data-kt-users-modal-action="submit">
<span class="indicator-label">Submit</span>
<span class="indicator-progress">Please wait...
<span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
</button>
</div>
<div class="text-left pt-10">
<p>
note:<br>........
</p>
</div>
</form>
inside the form there is a field id="select-module-name", after this menu selected, it will get from ajax to fill the selection for the next field with:
// after selecting module, show menu with parent_id == module menuID
$("#select-module-name").change(function () {
var moduleName = $(this).val();
const selectParent = document.querySelector('#select-parent');
// empty the select-parent options, then add the default empty select
$('#select-parent').empty();
selectParent.add(new Option('',''));
if(moduleName != null && moduleName != "New Module"){
$.ajax({
type: "GET",
url: "/administrator.......,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
response.forEach(function (parentData) {
var option = new Option(parentData.menu_name, parentData.id);
selectParent.add(option, undefined);
});
}
});
}
});
it works fine when creating a new menu,
but when edit, I want to get the prefilled form.
The only one got problem is the select with id="select-parent", this below is the code event when I click edit on selected menu:
// edit menu button eventListener
$(".edit-menu").click(function () {
var menuID = $(this).data('id');
console.log(menuID);
$.ajax({
type: "GET",
url: "/administrator.......,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
console.log(response);
$("#menu-id").val(response.id);
$("#menu-name").val(response.menu_name);
$("#route-name").val(response.routes_name);
$("#route-url").val(response.url_routes);
$("#select-module-name").val(response.module_name).trigger("change");
if(response.parent_id != 0){
$("#select-parent").val(response.parent.menu_name).trigger("change");
// $('#select-parent').val(menuData.parent_id).trigger("change.select2");
// $("#select-parent").select2('data', {id: menuData.parent.module_name, text: menuData.parent.module_name});
}
n.show();
}
});
});
basically, there is 2 select2, but the second select2 is getting the value after the first got selected.
And the problem is the #select-parent (second select2) wont get selected within the value, data is valid but still the select option wont get selected, happen when edit (prefilled form)
thank you in advance if any solution from anyone
$("#select-parent").val(response.parent.menu_name).trigger("change");
$('#select-parent').val(menuData.parent_id).trigger("change.select2");
$("#select-parent").select2('data', {id: menuData.parent.module_name, text: menuData.parent.module_name});
I have tried this 3 option, and even try using setTimeout,
have been suffered this pain for over than 2 weeks XD
I've got three fields inline and one of them is a inpt field, this is how it look like when they are validated
https://ibb.co/X8c1jDZ
the problem is when I enter some values into the input fiedl then it moves all the other fields as you can see from the image
https://ibb.co/Fn666cw
I believe something is wrong with the way I unhighlight the field once has been filled but not sure, maybe someone can help me. Please let me know if you need more details. many thanks
This is my html code
<div class="row">
<div class="form-group fieldGroup">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Tipologia proprietario</label>
<select class="form-control bs-select" id="kmg_admin_new_building_owner_type-1" name="kmg_admin_new_building_owner_type[]" data-live-search="true" title="Seleziona tipologia proprietario">
<option value="1">Proprietario</option>
<option value="2">Co-Proprietario</option>
<option value="3">Nudo proprietario</option>
<option value="4">Usufruttuario</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Proprietario</label>
<select class="form-control bs-select" id="kmg_admin_new_building_owner-1" name="kmg_admin_new_building_owner[]" data-live-search="true" title="Seleziona tipologia proprietario">
<option value="1">Proprietario</option>
<option value="2">Co-Proprietario</option>
<option value="3">Nudo proprietario</option>
<option value="4">Usufruttuario</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Se
<span class="required"> * </span>
</label>
<div class="input-group">
<input type="text" class="form-control prova" id="kmg_admin_new_building_owner_quota-1" name="kmg_admin_new_building_owner_quota[]" placeholder="Quota titolare">
<span class="input-group-btn input-group-btn input-space">
<button class="btn btn-default addMore" type="button">Aggiungi proprietario</button>
</span>
<span class="input-group-btn input-group-btn input-space">
<button class="btn btn-default remove" type="button">Rimuovi proprietario</button>
</span>
</div>
</div>
</div>
</div>
</div>
This is my javascript code
form.validate({
// doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
kmg_admin_new_building_increment: {
required: true,
digits: true,
remote: {
type: 'POST',
data: {
ajax_action: 'kmg_new_building_check_increment',
kmg_new_building_increment: function() {
return $( "#kmg_admin_new_building_increment" ).val();
}
}
}
},
kmg_admin_new_building_type: { required: true },
kmg_admin_new_building_palazzina: { required: true },
kmg_admin_new_building_interno: { required: true },
"kmg_admin_new_building_owner_type[]": {required: true},
"kmg_admin_new_building_owner[]": { required: true },
"kmg_admin_new_building_owner_quota[]": {
required: true,
number: true,
min: 0,
max: 100
},
kmg_admin_new_building_metri: {
required: false,
digits: true
}
},
messages: {
kmg_admin_new_building_increment: {
required: "Specifica un ordine di stampa univoco",
digits: "L'ordine di stampa può solo essere un numero",
remote: "Ordine di stampa è già registrato!",
},
kmg_admin_new_building_type: "Specifica la tipologia dell'unità immobiliare",
kmg_admin_new_building_palazzina: "Specifica la palazzina dell'unità immobiliare",
kmg_admin_new_building_interno: "Inserisci il valore d'interno",
"kmg_admin_new_building_owner_type[]": "Seleziona tipologia di proprietario",
"kmg_admin_new_building_owner[]": "Seleziona proprietario",
"kmg_admin_new_building_owner_quota[]": {
required: "Specifica la quota",
number: "solo numeri",
min: "minimo 0",
max: "massimo 100"
},
kmg_admin_new_building_metri: {digits: "Inserisci valore numerico"}
},
errorPlacement: function(error, element) { // render error placement for each input type
if (element.parent(".input-group").length > 0) {
error.insertAfter(element.parent(".input-group"));
} else {
error.appendTo(element.closest('.form-group'));
}
},
invalidHandler: function(event, validator) { //display error alert on form submit
success.hide();
error.show();
App.scrollTo(error, -200);
},
highlight: function(element) { // hightlight error inputs
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) { // revert the change done by hightlight
$(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
},
success: function(label) {
label.addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
},
This is how i clone the fields
//add more fields group
var fieldGroup = $(".fieldGroup").clone();
// Hide remove button
$(".remove").parent('span').hide();
$(".addMore").click(function(e) {
var fgc = $('body').find('.fieldGroup').length;
var fieldHTML = '<div class="form-group fieldGroup">' + fieldGroup.html() + '</div>';
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner_type-1', 'kmg_admin_new_building_owner_type-' + (fgc + 1));
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner-1', 'kmg_admin_new_building_owner-' + (fgc + 1));
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner_quota-1', 'fkmg_admin_new_building_owner_quota-' + (fgc + 1));
$('body').find('.fieldGroup:last').after(fieldHTML);
var el = $('.fieldGroup').next();
// Hide add new button
el.find('.addMore').parent('span').hide();
// Show remove button
el.find('.remove').parent('span').show();
// Load selectpicker again after cloning the inputs
$('.bs-select').selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check',
dropupAuto: false
});
});
//remove fields group
$("body").on("click", ".remove", function() {
$(this).parents(".fieldGroup").remove();
});
This is not a serious problem, I think, you just have to think of the changes of the layout, and prepare for them in your CSS.
Here's an example of what's happening:
(You can find a short explanation at the bottom of the answer.)
jQuery(document).ready(function($) {
$(".modify").on('click', function(e) {
// $.fn.toggle() switches between display: none and
// display: block
$('#il3').find('label').toggle()
})
})
.inputandlabel {
float: left;
}
input[type="text"],
label {
display: block;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-primary modify">Just push it to see the problem</button>
</div>
</div>
<div class="row">
<div class="col-12">
<div id="il1" class="inputandlabel">
<label for="form1">Form1</label>
<input id="form1" type="text" />
</div>
<div id="il2" class="inputandlabel">
<label for="form2">Form2</label>
<input id="form2" type="text" />
</div>
<div id="il3" class="inputandlabel">
<label for="form3">Form3</label>
<input id="form3" type="text" />
</div>
<div id="il4" class="inputandlabel">
<label for="form4">Form4</label>
<input id="form4" type="text" />
</div>
<div id="il5" class="inputandlabel">
<label for="form5">Form5</label>
<input id="form5" type="text" />
</div>
<div id="il6" class="inputandlabel">
<label for="form6">Form6</label>
<input id="form6" type="text" />
</div>
</div>
</div>
</div>
And here's a solution:
jQuery(document).ready(function($) {
$(".modify").on('click', function(e) {
e.preventDefault()
if ($('#il3').find('label').css('visibility') !== 'hidden') {
$('#il3').find('label').css('visibility', 'hidden')
} else {
$('#il3').find('label').css('visibility', 'visible')
}
})
})
.inputandlabel {
float: left;
}
input[type="text"],
label {
display: block;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-primary modify">Just push it to see "nothing"</button>
</div>
</div>
<div class="row">
<div class="col-12">
<div id="il1" class="inputandlabel">
<label for="form1">Form1</label>
<input id="form1" type="text" />
</div>
<div id="il2" class="inputandlabel">
<label for="form2">Form2</label>
<input id="form2" type="text" />
</div>
<div id="il3" class="inputandlabel">
<label for="form3">Form3</label>
<input id="form3" type="text" />
</div>
<div id="il4" class="inputandlabel">
<label for="form4">Form4</label>
<input id="form4" type="text" />
</div>
<div id="il5" class="inputandlabel">
<label for="form5">Form5</label>
<input id="form5" type="text" />
</div>
<div id="il6" class="inputandlabel">
<label for="form6">Form6</label>
<input id="form6" type="text" />
</div>
</div>
</div>
</div>
You can see from the two snippets, that by setting display: none; on the label scrambles the layout. display: none; takes the element out of the flow (not the DOM itself, but from the object flow), while visibility: hidden; just makes the element invisible. Quite a difference, isn't it?
So, setting the display CSS property to none "removes the height" that kept your layout in order - try setting the elements visibility to hidden with JS.
If that's not working, then give the form-group a fixed height (the height with success / error message), and don't change that value on success / error.
Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.
This is my html code: this is my input filed where i have declare input type and id.
<div class="col-lg-4 col-sm-6">
<div class="form-group">
<div>
<input id="SkillsAndInterests" class="form-control" type="text"
name="SkillsAndInterests" style="width:286px;height:35px;" />
</div>
</div>
</div>
This is my js code :
vm.CommunityMembersAdditionalInfoData.SkillsAndInterests = vm.skillsandinterestarray;
$('#SkillsAndInterests').tagSuggest({
data: vm.CommunityMembersAdditionalInfoData.SkillsAndInterests,
sortOrder: 'name',
maxDropHeight: 200,
name: 'SkillsAndInterests'
});
And this is my reset function: where i am unable reset filed
vm.ResetSerachMembers = function () {
$("#SkillsAndInterests").val('');
}
And this is my button where i am calling reset function:
<button class="btn btn-danger" ng-disabled="data.isMembersLoading"
ng-click="data.ResetSerachMembers();" type="button">
Reset
</button>
I have a modal window used to update or add a new object Store.
This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.
Button that calls the modal:
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
Html of the modal:
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
GET Method:
public IActionResult Create(int? id)
{
List<Department> DepartmentList = new List<Department>();
DepartmentList = (from department in _context.Departments
select department).ToList();
DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
ViewBag.ListofDepartment = DepartmentList;
StoreIndexData edit = new StoreIndexData();
List<District> ListofDistrict = new List<District>();
ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
ViewBag.ListofDistrict = ListofDistrict;
return PartialView("~/Views/Shared/Stores/_Create.cshtml");
}
The problem:
I have the following jQuery which asigns a value to DistrictID once the modal opens:
<script type="text/javascript">
var wasclicked = 0;
var $this = this;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
};
$('#modal-action-store').on('hidden.bs.modal', function () {
//global.wasclicked = 0;
wasclicked = 0;
$(this).removeData('bs.modal');
});
$('#modal-action-store').on('shown.bs.modal', function (e) {
console.log($('#DistrictID').length);
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
};
});
});
</script>
The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :
ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
And this line is lost:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
What I suspect is that the information coming from the Controller overwrites any result from jQuery over the in the modal.
After debugging I have identified three diferent moments:
Moment 1: First time we open the modal
The modal hasn't opened yet and the jQuery executes
For this reason it does not identify DistrictID
The result from the GET Action fills the modal's inputs.
Moment 2 - Part 1: Second time we open the modal
This time the modal opens before the jQuery is executed
The DistrictID has the value from the GET Method before we assign the value from jQuery
Moment 2 - Part 2: When the value from jQuery is assigned
The value from jQuery is assigned to DistrictID
This value will be overwritten by the result of the GET Action
Question:
Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
}
});
</script>
PS: Default option can be also be used. refer the below code.
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
<option value='0'>-- Seleccione Distrito --</option>
</select>
</div>
</div>
modal() only accepts an options object or a string. To append elements to your modal, we can append them when the show.bs.modal is triggered:
$('#modal-action-store').on('show.bs.modal', function(e){
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
<div class="modal" id="modal-action-store">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<select class="form-control" id="DistrictID" name="DistrictID">
</select>
</div>
</div>
</div>
</div>
I would update your http://plataformafantasypark.azurewebsites.net/Stores/create to contain <option value='0'>-- Seleccione Distrito --</option> by default. This would limit the options to overwrite the element with zero entries.
This would make your js code easier too.
By the way, why do you use document.getElementById("modalbutton").onclick when you can use $("#modalbutton").on("click", function(){}); because you are using jQuery for everything else.