how to filup the textbox value after popup the bootstrap modal - javascript

I am trying to fillup textbox value when user select the value from the dropdownlist
but issue is my dropdownlist is coming when click on apply link
see below image when I click the apply button then open bootstrap model
I write the code for change the value of dropdownlist an fillup that value in another textbox
.cshtml
<div class="row">
<div class="col-md-2">
<label>Vacancy:</label>
</div>
<div class="col-md-8">
<select id="hm" class="form-control">
#foreach (var item in #ViewBag.vacancy)
{
<option value="item.vacancytitle">
#item.vacancytitle
</option>
}
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-md-2">
<label>vacancyid:</label>
</div>
<div class="col-md-8">
<input class="form-control" type="text" id="vacancyid" value="" />
</div>
</div>
<br />
<div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('#applylink').click(function () {
debugger
//var h = document.getElementById(hm).value;
//var strUser = h.options[e.selectedIndex].value;
//$('#vacancyid').val(strUser);
$("#myModal").modal(); //here open bootstrap modal
$('#hm').on('change', function () {
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal); //here I am trying to fetch value from dropdownlist when user select the particular value from the dropdownlist
});
});
</script>
currently I have two value in dropdownlist
html/css developer
angular,js developer
when user select html/css developer from the dropdownlist then here I am filling
$('#vacancyid').val(selectVal);
html/css developer
first click the apply link button and then open bootstrap modal
I want to fillup textbox value when user select the value from the dropdownlist
when open the popup then I want to call this method
$('#hm').on('change', function () {
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal); //here I am trying to fetch value from dropdownlist when user select the particular value from the dropdownlist
});
Edit:
//load javascript after modal is loaded
//load option value chage after modal is loaded
$(document).ready(function () {
debugger
$('#myModal').on('load', function () {
debugger
$('#hm').on('change', function () { //debugger here not come when select the value from the dropdownlist
debugger
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal);
});
});
});

You can simply use the native BS function like shown.bs.modal. Your load function is not doing anything when the modal shows so your change function is not working at all.
Also, since you want load the vacancyId value from dropdown- You can simply assign the option the value of #item.vacancyId
<select id="hm" class="form-control">
#foreach (var item in #ViewBag.vacancy)
{
<option value="#item.vacancyid">
#item.vacancytitle
</option>
}
</select>
Load the boostrap modal like this:
$(document).ready(function() {
$('#myModal').on('shown.bs.modal', function() {
$('#hm').on('change', function() {
var selectVal = $(this).val();
$('#vacancyid').val(selectVal);
}); //this method work now :)
})
});

You can use show event for bootstrap modal. See this.
Like as in the following code:
$('#myModal').on('shown.bs.modal', function() {
// your code goes here
})

Related

jQuery: Result of script gets deleted after execution - removeData() running on the background?

I have a modal window used to update or add a new object Store.
This modal has a cascading dropdownlist for two properties: Department and District.
How should it work:
We first identify if we are in the situation of creating or updating a Store.
In case is a new Store the modal opens and using jQuery we present a default value for the District dropdownlists (since no Department has been chosen yet).
<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>
However, at this moment, after the default value is added, after a fraction of a second, the value gets deleted.
What I've tried
I've noticed that when I remove this line of code:
$(this).removeData('bs.modal');
From the previous script, it works ok, but I need that code in order to clear the data from the modal if I need to use the modal to edit another Store.
Plus, when I debug the project the debugger did not stop at the breakpoint of that line, so I'm not sure why it's somehow executing in the background? Is it because it's wrapped inside the function document.ready()?
I've been struggling with this for days. I thank for any helpful comment.
Aditional info:
Online version of the project:
There is an online version for this for debugging:
http://plataformafantasypark.azurewebsites.net/
user: adelgado password: $Adelgado33
Under the menu 'Tiendas' -> 'Registro'
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>
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>
Why not do something like(?):
$("#modalbutton").on('click', function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
});
The idea is to take manual control of the loading and inserting of the remote content received from /Stores/Create. I'm not set up to test this but give it a try.
You will need to get rid of/comment out the existing .on('showN.bs.modal') handler, and you might have to get rid of the href on the <a> tag that invokes the modal, not sure.
$('#modal-action-store').on('show.bs.modal', function (e) {
if (wasclicked == 1) {
// load the form, once it's done loading modify it as needed
$('#modal-action-store').find('.modal-content').load('/Stores/Create', function () {
$('#DistrictID').html('<option value='0'>-- Seleccione Distrito --</option>');
});
}
});

How to reset dropdown box in jquery (select2)?

I have the following code:
https://jsfiddle.net/rmxpq2z0/
<div class="swiper-pagination"></div>
<div id="quote-form" class="quote-form">
<div class="container">
<div class="range range-xs-center range-lg-right">
<div class="cell-xs-10 cell-sm-8 cell-lg-5 text-left offset-top-0">
<div class="inset-lg-left-70">
<div class="quote-form-body">
<div>
<h3 class="text-bold">Get a FREE Quote!</h3>
</div>
<div class="offset-top-25">
<p>Please select your repair from the drop down boxes for an instant quote.</p>
</div>
<div class="offset-top-20">
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="console">
<option value="selectconsole">Select My Console</option>
<option value="ps4">PS4</option>
<option value="xboxone">Xbox One</option>
</select>
</div>
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="model">
</select>
</div>
Get My Quote
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
ps4models = new Array("Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro");
xboxonemodels = new Array("Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio");
populateSelect();
$(function() {
$('#console').change(function() {
populateSelect();
});
});
function populateSelect() {
console = $('#console').val();
$('#model').empty();
$('#model').html('');
if (console == 'ps4') {
ps4models.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
if (console == 'xboxone') {
xboxonemodels.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
</script>
It works perfectly in the jsfiddle, but when I post the code to the website, it doesn't work.
It DOES populate the dropdown box, but it won't auto select the first option in the second box, and it won't remove any previous option that was selected.
For example, if I select an option in the first box, the second box stays empty until I select something. The first option should be auto selected. Also if I select something in the second box, and then change the selection in the first box, the second box option stays there, instead of being reset.
It is the EXACT same code, no changes at all. Is it possible the CSS is interfering with it?
Any help would be greatly appreciated.
UPDATE
Thanks to DanielH! It turns out the template was using Select2 jquery plugin. His code worked perfectly.
Solution 1:
Since you are using select2, add $('#model').change(); at the end of your console dropdown's select2 config should trigger the update every time you update the model dropdown list.
Solution 2:
If you have no control over the select2 or not sure where to find it, the following also gonna work, add a onchange event to the parent dropdown console:
$( document ).ready(function() {
$('#console').on('change', function(){
$('#model').val('selectmodel');
$('#model').change();
})
});

Trying to pass a variable to Jquery from Razor

So I'm working on a project in ASP.net and have a situation where I've created a form that provides users a drop down menu to select from. On top of this the Jquery below allows the user to add additional drop down fields. This works.
Now my problem stems from the first drop down has a list of institutes which works fine as its being populated from the C# in the html form.
When the user selects to add another drop down that box is just empty. I've tried adding the C# directly to the Jquery but this doesn't work.
I'm not overly experienced with ASP.net or MVC both of which I'm using for the project, what is the best way to go around passing the values into Jquery so I can add list to the drop down?
Here is the code below
<script>
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" /></select>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Here is the HTML
<div class="col-md-3 BasicInfoFormLabelColumn">
<label for="restrictedInstitute" class="formLabel">Restricted Institutes: (Can't Apply)</label>
</div>
<div class="col-md-3 input_fields_wrap">
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
#foreach (var item in Model.institute)
{
if (#item.TradingName != null && #item.TradingName != " " && #item.TradingName != "")
{
<option value="#item.TradingName">#item.TradingName</option>
}
}
</select>
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>
</div>
</div>
</div>
I've added a couple images to help clarify what I'm trying to do.
Its happening because U only append select without its option inside you Jquery. I recommend using AJAX and partial view to achieve ur goal.
First, separate the rendering of dropdownlist into another cshtml, for example the name is Institute.cshtml
Institute.cshtml
#model xxxx.Model.Institute //model would be your institute
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
#foreach (var item in Model)
{
if (#item.TradingName != null && #item.TradingName != " " && #item.TradingName != "")
{
<option value="#item.TradingName">#item.TradingName</option>
}
}
</select>
Then you call it as partialview in your HTML
<div class="col-md-3 input_fields_wrap">
#Html.Partial("Institute", Model.Institute)
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>
</div>
</div>
</div>
And add the partialview in your Controller
xxController
PartialViewResult Institute()
{
return PartialView();
}
This is the first step to separate your dropdownlist into another partialView
The second step is calling an ajax in your add click button, and fetch the result using this partialView
javascript
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function{ //on add input button click
if (x < max_fields) { //max input box allowed
x++; //text box increment
$.ajax({
url: '#Url.Action("AddDropdown", "YourController")',
type: "GET",
success: function (result) {
$(wrapper).append(result);
}
});
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
this Javascript means, when u click Add button, you will request to your controller using Ajax. Then the controller will help you to render the dropdownlist and send the result back to your Client.
So, you need to add another function in your controller to receive this Ajax request
xxController
public ActionResult AddDropdown()
{
Model.Institute Result = new Model.Institute()
//you can generate your Model.Institue in here
Return PartialView("Institute", Result); //this will render Result with Institute.cshtml
}
after this, you can add dropdownlist into your html with the click add button

How to associate an event with the option id of a select box

I have to add a div element to a page after a particular option in the select box is selected. How can I do it using jQuery? I am trying to use the onClick event but it doesn't works.
<div class="col-xs-7">
<label for="sel1">Filter Type:</label>
<select class="form-control" id="sel1">
<option>Text</option>
<option onclick="Adddivision();">List</option>
</select>
</div>
<script>
function Adddivision(){
<div class="col-xs-6">
<label for="Filter Options">Filter Options:</label>
</div>
}
</script>
You can use:
$('#sel1').on('change', function() {
if($(this).find('option:selected').text()=="List" ){
$('body').append('<div class="col-xs-6"><label for="Filter Options">Filter Options:</label></div>')//append div
$('#sel1').off('change');
}
});
Use onchange jQuery event.
$(document).on("change", "#sel1", function(){
if($(this).val() == 2) // 2 is the value of the <option> tag
{
var divElement = "<div>The Div Element that you want to be appended to your page</div>";
$("body").append(divElement);
}
});
You can use below jQuery to bind change event to select box and check if selected option is List, then append label to the div
$('#sel1').on('change', function() {
var text = $(this).find('option:selected').text();
if(text =="List" );
{
$(".col-xs-6").append('<label for="Filter Options">Filter Options:</label>');
}
});

Listbox from a dropdownlist

Can anyone tell me how can i load a listbox from a selected item of a dropdownlist?
Let's say i have a dropdownlist that contain "option1=male" & "option2=female"
I want that when male is selected, a list of male employees is shown in a listbox.
Added note:
i want to know how can i do this if employees names are saved in a file / data base?
Is this what you're after?
Selecting from a dropdown box a specific option will trigger an ajax call for a specific json file. On success, we display file's content into a listbox. This is just a demo.
Code sample:
$(document).ready(function() {
var listbox = $('#listbox'),
populateListbox = function(data) {
for (var i = 0, item; i < data.length; i++) {
item = data[i];
var option = $('<option>').val(item.age).text(item.name);
listbox.append(option);
}
showListbox();
},
emptyListBox = function() {
listbox.empty();
},
showListbox = function() {
listbox.removeClass('hide');
},
hideListbox = function() {
listbox.addClass('hide');
};
$('#dropdown').on('change', function (e) {
emptyListBox();
hideListbox();
var selectedOption = $("option:selected", this),
selectedValue = this.value;
switch (selectedValue) {
case 'male':
$.getJSON( "male.json", populateListbox);
break;
case 'female':
$.getJSON( "female.json", populateListbox);
break;
}
});
});
I gather that you want it to populate another listbox asynchronously? What you would need to do to achieve this is to use JavaScript and to call a function when the document loads. For example
$(document).ready(function(){
exampleFucntion();
});
This will call the function "exampleFunction" when the document loads. Inside this function the following code can be put where #dropdownbox would be the ID of your HTML drop down box.
$("#dropdownbox").change(exampleOnDropDownChanged);
This again will call a function that performs an action everytime the index of the drop down box changes. Inside the called function is where you would put the code to create another dropdown box dynamically with the details of male or female employees (or just populate an existing dropdown). Within the function you could put 'if' statements to get the male or female employees and then carry out the corresponding code to populate the dropdown. This function could also call a PHP page which could retrieve data and then populate the drop down.
The way I have described doesn't require the HTML page to be refreshed. I also suggest that you read around JavaScript and AJAX and also basic techniques, such as populating dropdown boxes.
I think this is what you are looking for. DEMO HERE
Select your gender and shows relative listbox.
<form id="survey" action="#" method="post">
<div id="section1">
<label for="Gender">Select employee gender.</label>
<select id="Gender" onchange="selection(this);">
<option value="Gender">---Select---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div id="section2" style="display:none;">Please select employee gender from above.</div>
<div id="section3" style="display:none;">Male Employees
<br />
<label for="Jim">Jim</label>
<input type="radio" id="Jim" />
<label for="Tom">Tom</label>
<input type="radio" id="Tom" />
<label for="Sam">Sam</label>
<input type="radio" id="Sam" />
</div>
<div id="section4" style="display:none;">Female Employees<br />
<label for="Kate">Kate</label>
<input type="radio" id="Kate" />
<label for="Claire">Claire</label>
<input type="radio" id="Claire" />
<label for="Sue">Sue</label>
<input type="radio" id="Sue" />
</div>
</form>
<script>
var sections = {
'Gender': 'section2',
'Male': 'section3',
'Female': 'section4'
};
var selection = function (select) {
for (var i in sections)
document.getElementById(sections[i]).style.display = "none";
document.getElementById(sections[select.value]).style.display = "block";
};
</script>

Categories