Programmatically select2 to select 2 select option sequentially - javascript

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

Related

Select Options disappearing

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());
};

Already sucess to add select form dyamically , but the data from success ajax cannot be send to the new select form

I'm trying to make a dependent dropdown, and it already works.
The problem is, the user want the second dropdown (in a different div) to be added dynamically but when we try to add a new dropdown, the new dropdown doesn't show any data when I choose value from first dropdown.
How to make the new dropdown contain data from ajax?
P.S: the option value is in another html where the ajax call the html if it succeeds.
This is the html:
$(document).ready(function() {
$("#dataselect").change(function() {
var urls = "{% url 'polls:load-column' %}";
var column = $(this).val();
$.ajax({
url: urls,
data: {
'column': column
},
success: function(data) {
$("#columnselect").html(data);
},
error: function(data) {
alert("error occured");
}
});
});
});
function appendBox() {
$('#test').append('<select id ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id="test">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>

How to Submit a Form by using a button at the same time click event on anchor link?

I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>

Link in keyup function is not working

Here is screen shot of my problemI am using codeigniter and ajax.When keyup function is call on search bar then data is shown in suggestion box but when i click on link which is shown on suggestion box then this click is not working.No error of any script file.
Here is code of my view file:
<div class="container-fluid my_searchbar">
<div class="container my_searchbar_container">
<div class="nav nav-justified navbar-search navbar-nav">
<form class="search navbar-search" method="post" action="index.html" >
<div class="input-group">
<input type="text" name="search_area" id="search_area" placeholder="Search Area" class="form-control input-lg">
<div class="input-group-btn">
</div>
<input type="text" name="search_pro" id="search_pro" placeholder="Search Professional Category" class="form-control input-lg">
<ul id="show_search_pro" class="results" >
</ul>
<div class="input-group-btn">
Search
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Here is my ajax code in view file.
$('#search_pro').keyup(function(){
// alert($(this).val());
var location_field = $('#search_area');
var search_cal_field = $(this);
$.ajax({
type: 'POST',
url: 'http://localhost/JustClick/User/search_professional',
cache : false,
dataType : 'html',
data :{location_id:location_field.val(), category_id:search_cal_field.val()},
success:function(data)
{
$('#show_search_pro').html(data);
}
});
});
Here is code of my controller through using ajax i get data on view page:
public function search_professional()
{
if($this->input->is_ajax_request())
{
$professional = $this->UserModel->search_professional($this->input->post('location_id',true),$this->input->post('category_id',true));
foreach ($professional as $row)
{
echo '
<li>
<a class="s_pro" href="'.base_url('Professional/show_professional_detail/'.$row->pro_id).'">'.$row->firstname.' '.$row->lastname.'<br /><span>Description...</span></a></li>';
}
}
else
{
show_404();
}
}
Help me how i solve this problem.

Need to restrict clone max10 in mobile device using jquery

Working on Jquery clone where in large device like desktop and tablet user can clone more but in mobile I have to restrict user to clone 10. Is this possible to restrict user to clone
Here is the jquery code
var i = 1;
$(document).on("click", ".btn_more", function () {
$(".cloned-row:first").clone().insertAfter(".cloned-row:last").attr({
'id': function(_, id) {
return id + i
},
'name': function(_, name) {
return name + i
},
'class': "add_pn_grp"
//'value': ''
}).end().find('[id]').attr({
'id': function(_, id) {
return id + i
}
});
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
});
$(document).on('click', ".btn_less", function () {
$(this).closest(".cloned-row").remove();
});
Here is the html code
<div id ="phone_div" class="col-xs-12 col-sm-9 col-md-9 col-lg-9 ">
<!--Phone information Help pop up-->
<div class="modal-dialog" role="document" id="phonehint" align="center">
<div class="modal-content">
<div class="modal-header text-center" >
<h4 id="myModalLabel" class="modal-title" style="color:black;">Help - Phone</h4>
</div>
<div class="modal-body" >
<h5 style="color:black;" align="left"> Provide number <br/>Provide your phone number along with the country code.</h5>
</div>
</div>
</div>
<!--Contact information Help pop up Ends-->
<label>Phone</label> <i class="fa fa-question-circle help_icon" onclick="showphonehint()" onmouseout="hidephonehint()"></i>
<div class="em_pho cloned-row">
<select id="sel_phntype" name="sel_phntype" class="sslt_Field">
<option selected='selected' value="">Phone Type</option>
<option value="BUSN">Business</option>
<option value="CAMP">Campus</option>
<option value="CELL" >Cellphone</option>
<option value="CEL2">Cellphone2</option>
<option value="FAX">FAX</option>
<option value="HOME">Home</option>
<option value="OTR">Other</option>
</select>
<span class = "ph-inline">
<input type="text" class="cc_field" placeholder="Country Code" id="txt_CC" maxlength="3" name="txt_CC" />
<input type="text" class="pn_field" placeholder="Phone Number" id="txt_Pno" name="txt_Pno" />
<input type="radio" name="preferred" id="rad_Prf" value="preferred">
<label class="radio-label">Preferred</label>
<!--<button class="btn_more" id="buttonvalue"></button>-->
<input type="button" class="btn_more" id="buttonvalue"/>
</span>
</div>
</div>
I have created variable count I have assigned the count as 10 but how to restrict in mobile I am confused like anything.
Kindly help me
Thanks in advance
Mahadevan
you could prevent execution in those cases, isMobile and size > 9, using a relatively effective one-liner.
edit
as suggested in another post on the topic, you could check for mobile with matchMedia.
$(document).ready(function() {
$(".btn_add").click(function() {
if ( $('.cloned_row').size() > 9 && isMobile() ) return;
// cloning logic
});
});
function isMobile() { return window.matchMedia("only screen and (max-width: 760px)").matches; }

Categories