autocomplete doesn't working on dynamic created input fields jQuery - javascript

i am facing issue in autocomplete on dynamically created fields.
as in attached picture i created dynamic fields by clicking on plus sign, and on first row autocomplete is working but on the rest that are generated dynamically autocomplete is not working.
code is for autocomplete is
$(".account_code").dropdown({
onChange: function (val) {
var id=val;
var dataString = 'id='+ id +'&type=account_code';
alert(dataString);
$.ajax
({
type: "POST",
url: "include/ajax_data.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(data)
{
console.log(data);
$("#account_description").val(data.value);
}
});
}
});
dynamic row insertion code is
function add_row()
{
$rowno=$("#bank_payment_voucher tr").length;
$rowno=$rowno+1;
$("#bank_payment_voucher tr:last").after('<tr id="row'+$rowno+'"><td><div class="field"><select class="ui search dropdown account_code" id="account_code'+$rowno+'" name="account_code[]"><option value="">Select Code</option><?php foreach (get_lookups($data_code) as $key => $value){ ?><option value="<?php echo $value['code']; ?>"><?php echo $value['code']." | ".$value['description']; ?></option><?php } ?></select></div></td><td><div class="field"><input type="text" name="account_description[]" id="account_description'+$rowno+'" placeholder="Account Description" autocomplete="" value="" required=""></div></td><td><div class="required field"><input type="text" name="remarks[]" id="remarks'+$rowno+'" placeholder="Remarks" autocomplete="off" value="" required=""></div></td><td><div class="required field"><input type="text" name="cheque_number[]" id="cheque_number'+$rowno+'" placeholder="Cheque Number" autocomplete="off" value="" required=""></div></td><td><div class="field"><div class="ui fluid action input"><input type="number" name="amount[]" id="amount'+$rowno+'" placeholder="Amount" autocomplete="off" value=""><div class="ui green icon button"><i class="pk flag"></i> PKR</div></div></div></td><td><div class="field"><div class="ui fluid action input"><i class="minus circle icon red" onclick=delete_row("row'+$rowno+'") style="font-size: 2.5em; cursor: pointer;"></i></div></div></td></tr>');
}
console is also not showing any error.
requirements are: on every dynamic row, there is a fixed drop down and on the basis of that values selected from drop down, rest of the form fields filled automatically
please help me out in this

When you run this:
$(".account_code").dropdown({
...
});
You're finding all the elements with class account_code in the DOM and assigning a behavior to them, an event, that will be triggered when the dropdown functionality is used.
That code probably runs first.
So, when you add MORE elements with that same class, they never got the assignment of that behavior.
So what you need to do, in the add_row function, is not only creating the element and appending it, but also attaching the event you want to run on dropdown.
You could use this method to reassign the behavior: https://api.jquery.com/on/#on-events-selector-data-handler
Or you could also encapsulate the first snippet (assigning behavior) in a function, so you can trigger it again every time a new dynamic element is added.
Hope this helps.

See if this helpful.
$(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
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(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><input type="text" name="mytext[]"/>Remove</div>');
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
});
//add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
$("input[name^='mytext']").autocomplete({
source: availableAttributes
});
});
// autocomplete enablement
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>

i just achieved it by following code
$(document).ready(function(){
$(document).on('keydown', '.account_code', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "include/ajax_data.php",
type: 'POST',
dataType: "json",
cache: false,
data: {search: request.term,request:1},
success: function( data ) {
//console.log(data);
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.code); // display the selected text
var bank_code_id = ui.item.id; // selected value
//console.log(bank_code_id);
// AJAX
$.ajax({
url: 'include/ajax_data.php',
type: 'post',
cache: false,
data: {bank_code_id:bank_code_id,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var description = response[0]['description'];
// Set value to textboxes
document.getElementById('lookupcodeid_'+index).value = id;
document.getElementById('accountdescription_'+index).value = description;
}
}
});
return false;
}
});
});
});

Related

How to perform textbox search with matching dropdown options using only JavaScript/Ajax

I am working on a Web development project. I need to take some input like bank name in a textbox. After user starts typing 3 letters, I need to show all the matching options below (Not clear how to show). In the below options user can click any one options and the clicked text should be pasted in the same text box. All should be in html, css, js or ajax.
So far I created a text box and an ul list with no li in it and this ordered list is hidden by default. I created onkeyup event for the textbox. As the user starts typing bank names, if the text length is >=3 (Since banks keyword is minimum 3), I am filling that ul with the matching data using ajax and unhide it.
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for a Bank" title="Type in a name">
<ul id="myUL" hidden onclick="selectBank()">
And the script is:
<script>
function myFunction(){
var inp = document.getElementById('myInput');
var len = inp.value.length;
if(len>=3){
LoadBanks();
$("#myUL").show();
}else{
$('#myUL').empty();
$("#myUL").hide();
}
}
function LoadBanks(){
// for now the key is static. i will be updating it with the user input
var payload = {"key":"SBI"}
$.ajax({
url:"url",
type: "POST",
data: JSON.stringify(payload),
dataType: 'json',
success: function (data){
jsonObj = data.bankList;
var list = document.getElementById("myUL");
for (var i = 0; i < jsonObj.length; i++) {
var bank = jsonObj[i].banka;
var bankl = jsonObj[i].bankl;
var t = document.createElement('li');
t.innerHTML= bank+"-"+bankl;
list.appendChild(t);
}
},
error: function(data){
console.log(data);
}
});
}
The data is loaded sucessfully. But I don't know how to take text of which item is selected from that li's in onclick event.
You can write click event on li then inside that use $(this).text() this will give you text from li which is clicked then add that in your input-box.
Demo Code :
//just demo datas ..
var data = {
"bankList": [{
"banka": "cdc",
"bankl": "cdcde"
}, {
"banka": "cdc1",
"bankl": "cdcde1"
}, {
"banka": "cdc2",
"bankl": "cdcde2"
}]
}
function myFunction() {
var inp = document.getElementById('myInput');
var len = inp.value.length;
if (len >= 3) {
LoadBanks();
$("#myUL").show();
} else {
$('#myUL').empty();
$("#myUL").hide();
}
}
function LoadBanks() {
/*$.ajax({
url: "url",
type: "POST",
data: JSON.stringify(payload),
dataType: 'json',
success: function(data) {*/
jsonObj = data.bankList;
var list = document.getElementById("myUL");
document.getElementById("myUL").innerHTML = ""
for (var i = 0; i < jsonObj.length; i++) {
var bank = jsonObj[i].banka;
var bankl = jsonObj[i].bankl;
var t = document.createElement('li');
t.innerHTML = bank + "-" + bankl;
list.appendChild(t);
}
/*},
error: function(data) {
console.log(data);
}
});*/
}
//on click of li..
$("#myUL").on("click", "li", function() {
//get text add inside inputs
$("#selected").val($(this).text().split("-")[0])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for a Bank" title="Type in a name">
<ul id="myUL" hidden></ul>
<input type="text" id="selected">

jQuery validate , how to make validation rules for dynamically generated fields?

I have an HTML form with dynamically add more fields. For example company name. I am trying to use the jQuery validate method to validate. It is working fine with the existing company name field. Here is the code.
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
When I click on add more button another company name field will create on the form. The below code is failed to validate the dynamically generated field. Here I am getting the field count globally in this variable company_count
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
},
I tried like below, but this is giving me error
if(company_count> 0){
var new_field = jQuery("#company_name"+company_count);
new_field : {
required: true,
minlength: 3
},
}
The above block code is showing error in the text editor it self
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
Can anyone help me with how to make validation for these dynamically generated fields? Any help would be greatly appreciated. I am using form submission by using Ajax.
Code to add company fields dynamically
var company_room = 0;
var company_room1 = 0;
function add_another_company() {
company_room++;
company_room1++;
var objTo = document.getElementById('company_field')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass2" + company_room);
//var rdiv = 'removeclass2' + company_room;
divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';
objTo.appendChild(divtest);
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
function remove_another_company(rid2) {
company_room1--;
$('.removeclass2' + rid2).remove();
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
OK, so I didn't have your HTML so I had to mock some up. You will obviously have to tweak this a little to work with your ID's. I tried to keep it as close as possible to the ID's/classes you were already using.
I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it. Hopefully this kind of simplifies things a bit and makes it more manageable.
NOTE: I added a hidden input field to keep track of company count. This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now). I included code to preserve the company_count variable also, so basically you will have 2 company counts. I did this just to show you an easier way to keep track of this without having to micro manage it. :)
Try out this code and let me know what your getting in console if it is not working. Thanks
MOCK HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
<p>Dynamic Form</p>
<button id="addField">Add Dynamic Field</button>
<form id="dynForm">
Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
<br>
<input type="hidden" id="companyCount" name="companyCount" value="1">
<div id="company_field">
</div>
</form>
</div>
JQUERY/JS
$(function() { // <---- Document Ready!
$("#addField").on("click", () => {
var count = parseInt($("#companyCount").val(), 10);
count += 1;
$("#companyCount").val(count.toString());
var thisId = "company_name" + count.toString();
var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
var ele = $.parseHTML(html);
$("#company_field").append(ele);
});
$("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());
$("#company_creation_form").validate({
submitHandler: function(form) {
var company_count = parseInt($("#companyCount").val(), 10);
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize() + "&company_count=" + company_count,
success: function() {
alert("thanks");
}
});
return false;
}
});
});

Should I change "click" to "bind" ?, it does not work together

Good morning, I have these two javascript codes but I can not get both of them working. When both are embedded in my page the code that is responsible for uploading documents to a folder stops working. I do not see the error anywhere, where am I failing? Thanks in advance.
$(function() {
// grab the file input and bind a change event onto it
$('#file').bind("change", function() {
// new html5 formdata object.
$('#botondecarga').hide();
$('#cargando').show();
var formData = new FormData();
formData.append('carpeta', $('#carpeta[name="carpeta"]').val());
//for each entry, add to formdata to later access via $_FILES["file" + i]
for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
formData.append("file" + i, document.getElementById('file').files[i]);
}
//send formdata to server-side
$.ajax({
url: "file-upload.php", // our php file
type: 'post',
data: formData,
dataType: 'html', // we return html from our php file
async: true,
processData: false, // tell jQuery not to process the data
contentType: false,
// tell jQuery not to set contentType
success : function(data) {
confirm("Documentos subidos satisfactoriamente.");
location.reload();
},
error : function(request) {
console.log(request.responseText);
}
});
});
});
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div id="cantidadstock" class="cantidadstock"></div><div class="form-group"><label>Producto</label><select class="form-control select2" name="producto[]" id="producto" required><?php
$clase_newstock->lista_productos_almacen_principal_formulario();
?></select><label>Cantidad</label><input type="number" name="cantidad[]" class="form-control" value=""/><div class="form-group"><label>Fecha recepcion</label><div class="input-group"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" id="fecha_recepcion" name="fecha_recepcion[]" class="form-control"></div><div class="form-group"><label for="nombre">N albaran proveedor</label><input type="text" class="form-control" id="albaran_proveedor" name="albaran_proveedor[]" placeholder="El numero de albaran del proveedor..."></div><div class="form-group"><label for="precio">Precio</label><input type="number" class="form-control" id="precio" name="precio[]" placeholder="Precio...(Solo nĂºmeros y punto para decimales) "></div><br>Quitar producto</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
$('.select2').select2();
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});

How to clone a row of inputs with the parent element's function together? [duplicate]

This question already has an answer here:
Cloned elements' events corresponding to all elements in the form
(1 answer)
Closed 7 years ago.
I have a small table with two rows. In the first row I have 5 columns. First is select box displaying group names. WHen any of it selected, the second select box with list of item matching the value of selected group would appear in the next column. In third column, I have textbox for price. Followed by textbox for quantity in another.When price and quantity added the total of this will appear in the last column. In the second row I have a submit button with submits the form upon click.ALl these work perfectly fine.
Now I intend to allow users to dynamically add more of the first row so that they can submit multiple items! For that I'll need to add one more button type of input beside the submit.WHen clicked, it should clone the first row of 5 columns and also the function.
I tried:
$("#more_items").on("click",function
{
$("#clone_this").clone(true,true).appendTo("#submit_item");
});
This does clone the row. The first select box when selected from cloned item, the changes happen not to the current cloned row but to the parent row.Also, I couldn't clone more than once!ALso I tried replacing ID with class as I read clone would duplicate the ID yet no avail.
Now, how do I clone with the jquery also working correctly? DO I need to change my script in a way?
Below is my script for reference.
FORM
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr><th>Group Item</th><th>Nama Item</th><th>Harga</th><th>Kuantiti</th><th>Amount</th></tr>
<tr id="clone_this">
<td>
<select name='group' style="width:80px;" id="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach($group as $k=>$v){
?>
<option value="<?php echo $v['group_id']?>"><?php echo $v['group_name']?></option>
<?php
}
?>
</select>
</td>
<td id="sub_item">
<select name='item' style="width:100px;" id="it_id">
</select>
</td>
<td><input type="text" name="harga" value="" id="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty' id='qty'/>
</td>
<td><input type="text" name="amount" id="amount" value=""/></td>
</tr>
<tr><td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
SCRIPT
<script>
var harga;
var qty;
$("#harga").on("keyup",function()
{
console.log($(this).val());
harga = $(this).val();
});
$("#qty").on("keyup",function()
{
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$("#amount").val(amount);
});
$(document).ready( function ()
{
$("#sub_item").hide();
$('#gr').change(function()
{
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function(data) {
$("#sub_item").show();
$("#it_id").empty();
for (i = 0; i < data.length; i++)
{
$("#it_id").append("<option value='"+data[i].item_id+"'>"+data[i].item_name+"</option>");
}
if(data.length == "")
{
$("#it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$(function()
{
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function()
{
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide1").show();
}else
{
$("#hide1").hide();
}
});
$('#insurance').change(function()
{
$("#hide2").show();
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide2").show();
}else
{
$("#hide2").hide();
}
});
$('#bon').change(function()
{
$("#hide3").show();
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide3").show();
}else
{
$("#hide3").hide();
}
});
});
</script>
You should bind your event to your parent element by using the function with delegation property. e.g. ".on()" function.
For example:
$("table.test").on("click","tr",function(){
//do something
});
For all newly created tr element inside the table element with class name ="test" could trigger "click" event due to event delegation. It means after you have clone a new row, your new row could trigger the same event without handling explicitly by yourself
The problem is since you have ids in the elements, when you are cloning you are creating elements with duplicate ids, which is invalid as ID of an element must be unique.
Instead of ID, use class in such cases like
<select name='group' style="width:80px;" class="gr">
....
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
$(document).ready(function () {
$('#submit_item .gr').change(function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id '];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});

Not getting onchange event of dynamicly added dropdown in mvc3

I have three dropdownlists.
$(document).ready(function () {
$("#DropDownList1").change(function () {
$("#Id1").val($(this).val());
$("#Name1").val($("#DropDownList1 option:selected").text());
$('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());
});
$("#DropDownList2").change(function () {
$("#routeId").val($(this).val());
$("#routeName").val($("#RouteDropDownList option:selected").text());
$('#Div2').load('/Account/Dropdown3/?Id2=' + $("#routeId").val());
});
$("#DropDownList3").change(function () {
$("#Id3").val($(this).val());
$("#Name3").val($("#DropDownList3 option:selected").text());
});
});
In this DropDownList2 and DropDownList3 are added dynamicly.The problem is the dynamicly added dropdowns are not got registered in the page .So I am not getting its selected value from the onchange event.I added these controls as partial view.
Controller.
public ActionResult DropDownList2 (string Id1)
{
List<Emp> empList = new List<Emp>();
Emp em= new Emp ()
{
Id = "1",
Name = "Doac"
};
empList .Add(em);
ViewBag.DropDownList2= new SelectList(empList , "Id", "Name");
return PartialView();
}
Generated Html
<script type="text/javascript">
$('#CreateSubscriber').removeClass('menuHolderli').addClass('selectedMenu');
$(document).ready(function () {
$("#DropDownList").change(function () {
$("#Organization_Id").val($(this).val());
$("#Organization_Name").val($("#DropDownList option:selected").text());
$('#routeDiv').load('/Account/RouteDropdown/?organizationId=' + $("#Organization_Id").val());
});
$(document).on('change', "#RouteDropDownList", function () {
alert("hi");
$("#routeId").val($(this).val());
$("#routeName").val($("#RouteDropDownList option:selected").text());
$('#locationDiv').load('/Account/LocationDropdown/?routeId=' + $("#routeId").val());
});
$("#LocationDropDownList").change(function () {
$("#locationId").val($(this).val());
$("#locationName").val($("#LocationDropDownList option:selected").text());
});
});
</script>
<p class="message-info">
Passwords are required to be a minimum of 6 characters in length.
</p>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form action="/Account/Register" method="post"> <fieldset>
<legend>Registration Form</legend>
<ol>
<li>
<label for="Organization_Name">Name</label>
<input id="Organization_Id" name="Organization.Id" type="hidden" value="" />
<input id="Organization_Name" name="Organization.Name" type="hidden" value="" />
<select id="DropDownList" name="DropDownList"><option value="">---Select---</option>
<option value="516c0a18c891870f107aa74a">Choice School</option>
<option value="516d277bc8918701a44c131e">New Org</option>
<option value="516d1f492e6bba07dc245cc7">Olive</option>
</select>
<span class="field-validation-valid" data-valmsg-for="Organization.Name" data-valmsg-replace="true"></span>
</li>
</ol>
<div id="routeDiv"></div>
<div id="locationDiv"></div>
Use jQuery .on()
$(document).on('change', "#DropDownList2", function(){your code})
Repeat for your dropdown 3
Since, DropDownList2 and DropDownList3 are added dynamicly, you need to do this:
$(document).on('change', '#DropDownList1', (function () {
$("#Id1").val($(this).val());
$("#Name1").val($("#DropDownList1 option:selected").text());
$('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());
});
Similarly call other dyanmically added dropdowns also.
If you are adding the select options dynamically, why not use AJAX within AJAX?
$(function() {
$('#DropDownList').each(function () {
var dropdown = $(this);
dropdown.change(function() {
$.ajax({
url: 'Account/GetDropDownOptions',
type: 'GET',
data: {dropdownID: dropdown.attr('id'), value: dropdown.val()},
dataType: 'html',
cache: false,
success: function (data) {
var dropdown2 = $('#DropDownList2');
dropdown2.html(data);
dropdown2.change(function() {
$.ajax({
url: 'Account/GetDropDownOptions',
type: 'GET',
data: {dropdownID: dropdown2.attr('id'), value: dropdown2.val()},
dataType: 'html',
cache: false,
success: function (data) {
var dropdown3 = $('#DropDownList3');
dropdown3.html(data);
dropdown3.change(function() {
//....same thing as above pretty much
});
}
});
});
}
});
});
});
});
Then your controller action, GetDropDownOptions, would examine the DDL ID and selected value, understand what options it needed, then return the options as HTML. Or as a more elegant solution, you could have it return an object as json ( return Json(object) ) and then programatically create the elements in your javascript. You'd have to switch the dataType in the $.ajax to 'json'.
This way you have the dropdown change event after it has loaded the options. This change event loads DropDownList2's options and change event, which will load DDL3's options.
Haven't tested the code, but this idea will work. This sample assumes you already have the first DDL options loaded, but it seems you'll have to have add another layer of ajax to load those in as well. It also assumes the and DDL3 are already on the DOM at page load. You could add them to the DOM in your html to get this example to work, or change the IDs in the javascript to some container.

Categories