ajax not working for multiple select box - javascript

I have multiple select box by click to add button and all select box have ajax call on change event, but it is not working. Only work s for first.
code is given below.
Following code call ajax for default select box, but not working for next dynamically inserted select box..
$(document).ready(function () {
$(".one").change(function () {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'https://champbaba.tk/demo/two.php',
data: {'one': one},
type: 'POST',
success: function (data) {
$(company).html(data);
}
});
});
});
$(document).ready(function () {
var companyhtml = $(".one").html();
$(".add").click(function (e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select>').insertAfter($('.wrap'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<select class="one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select class="two">
</select>
</div>
<button class="add">Add</button>

It's working but I thought it's not a good way to work like that you need to search about that how to reinitialize event.
$(document).ready(function () {
var companyhtml = $(".one").html();
$(".add").click(function (e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select> <br>').insertAfter($('.wrap'));
$("select").change(function () {
var one = $(this).html();
var company = $(this).next('select').html(one)
$(this).next('select').val(1);
});
});
$("select").change(function () {
var one = $(this).html();
var company = $(this).next('select').html(one)
$(this).next('select').val(1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<select class="one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select class="two">
</select>
</div>
<button class="add">Add</button>
try it now.

The problem you have is one of event delegation.
You're attempting to affix an event handler to an element that doesn't actually exist in the DOM at the time the handler is attached. Adding $(document).ready() won't resolve this, because the element is generated dynamically, after page load.
To work around this, you have to hoist the scope and attach the event handler to an element that will exist on page load, such as document. You're looking for $(document).on("change", ".one", function() {} ) instead of $(".one").change(function() {} ):
$(document).ready(function() {
/* Ajax Call... */
$(document).on("change", ".one", function() {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'two.php',
data: {
'one': one
},
type: 'POST',
success: function(data) {
$(company).html(data);
}
});
});
/* To add more select boxes.. */
var companyhtml = $(".one").html();
$(".add").click(function(e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select>').insertAfter($('.wrap'));
});
});
Hope this helps! :)

$(".wrap").live('change','.one'function () {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'two.php',
data: {'one': one},
type: 'POST',
success: function (data) {
$(company).html(data);
}
});
});

Related

Bind API returned data to dropdownlist

I am trying to bind a dropdown list via javascript/jquery (anyone will work). Here is my code I tried -
$(document).ready(function () {
$.ajax({
type:"POST",
url: "function.php",
//dataType: "json"
success: function(result){
alert(result);
for (var i in result) {
$("#dropdownlist").append('<option value="'+result[i]+'">'+result[i]+'</option>');
};
}
});
});
On alert, it is showing data like this -
{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}
How to bind those values to Dropdown List (Only Value). It will be better if I can add Default Value something like "Select Country".
If response is a string, you can use a regex
const data = `{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}`
// success: function(data) {
var options = data.match(/:"(\w+)/g)
.map(cc => {
cc = cc.replace(/\W+/g,""); // remove non-letters
return `<option value="${cc}">${cc}</option>`;
});
$("#dropdownlist").append(options);
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>
Even more elegant using lookbehind, pointed out to me by Jonathan Lam
const data = `{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}`
// success: function(data) {
$("#dropdownlist").append(
data.match(/(?<=:")(\w+)/g)
.map(cc => `<option value="${cc}">${cc}</option>`)
)
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>
Note: Browser support for JS RegExp lookbehind (ES2018 draft) is still low. See the compatibility table on MDN for more details.
Original answer for simpler format ({"DK"}{"PL"}{"SA"}....) :
var options = data.match(/[A-Z]{2,}/g).map(cc => `<option value="${cc}">${cc}</option>`)
const data = `{"DK"}{"PL"}{"SA"}{"SP"}{"RS"}{"IS"}{"SE"}{"LT"}{"GR"}{"AT"}{"DE"}{"TR"}{"CZ"}{"US"}{"TW"}{"TH"}{"EG"}{"SI"}{"HU"}{"JP"}{"IN"}{"CA"}{"UNK"}{"MA"}{"NL"}{"RU"}{"HK"}{"ID"}{"FR"}{"IT"}{"ES"}{"NO"}{"BE"}{"KR"}{"MY"}{"FI"}{"DO"}{"KW"}{"SK"}{"GB"}{"AE"}{"IL"}{"BG"}{"AUW"}{"SG"}{"BH"}{"QA"}{"LV"}{"AU"}{"HR"}{"CY"}{"IE"}{"UA"}{"CE"}{"CN"}{"CH"}{"RO"}{"PT"}{"PH"}{"JO"}`
// success: function(data) {
var options = data.match(/[A-Z]{2,}/g).map(cc => `<option value="${cc}">${cc}</option>`)
$("#dropdownlist").append(options);
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>

Select box options not getting selected by jquery with ajax response data

I have an update form in which the data is pre-populated by an ajax call. All the data is getting populated well except the select box. Im using jquery to populate data.
My select code:
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<!-- <option value="" selected></option> -->
<option value="F">Female</option>
<option value="M">Male</option>
</select>
</div>
Ajax call:
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName);
$("#middleName").val(cust.middleName);
$("#gender2").val(cust.gender);
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
I have tried these but none worked:
$('gender2 option[value='+cust.gender+']').attr('selected', 'selected');
$('#gender2 option[value='+cust.gender+']').prop('selected', true);
$("div.test select").val(cust.gender);
Note: im getting data from backed as cust.gender=M for male and cust.gender=F for female.
Try
$('#gender2').change(function() {var selectvalue =$('#aioConceptName').find(":selected").val(cust.gender);});
$("#gender2").change(function() {
//your ajax
});
Try this
When it comes to select box it requires change() event,
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName).trigger('change');
$("#middleName").val(cust.middleName).trigger('change');
$("#gender2").val(cust.gender).trigger('change');
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
See This Demo is working , now u can put your ajax function inside document ready function , and please check in ajax Response console.log() value is same as your select option value.
$(document).ready(function(){
$('#gender2').val("O");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<option value="F">Female</option>
<option value="M">Male</option>
<option value="O">Other</option>
</select>
</div>

HTML Input field value set by AJAX and catch that event

I have field in my html, and some third-party service will set it's value.
How could I catch that event when the field value is changing?
<input data-val="true" data-val-length="City cannot be longer than 30 characters." data-val-length-max="30" data-val-required="City is required." id="Address_City" maxlength="30" name="Address.City" type="text" value="">
How could I catch the value change of this field,
I've tried .change event also,
$('#Address_City').on('change', function() {
console.log("Changed");
});
Use change event.
$("#myTextBox").on("change", function() {
//alert($(this).val());
});
<select name="user_id" id="user_id" class="form-control" onchange=get_contact(this.value)>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
function get_contact(user_id) {
$.ajax({
type: "POST",
url: "search.php",
data: {
"user_id": user_id
},
dataType:'json',
success: function(data) {
// console.log(data.user_mobile);
$("#contact_mob").val(data.user_mobile);
// $("#replaceThis").append(responseData);
}
});
}
Please specify which control your using in your code.
You Can use change or keydown Event.
FOr Client Control
$("#TextBOXID").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
For Server Control
$("#<%=TextBOXID.ClientID%>").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
We are going to retrieve a value and set that value in an HTML form. First, let's create the form.
Form
<form method="POST" action="">
<select name="user_id" id="user_id" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
</form>
Now that we have a form, we will do the technical part using javascript and jQuery
Javascript/jQuery
// Wait for the dom to load before we start doing stuff
$(document).ready(function ($) {
// append value to input on change of the dropdown
$(document).on('change', '#user_id' , function () {
// Get selected value
var user_id = $(this).val();
$.ajax({
type: "POST", // Set ajax call type
url: "search.php", // Set url
data: {"user_id": user_id}, // Set an array of data
dataType:'json', // Set the data type
success: function(data) {
// Log response to console
console.log(data);
// Append data to input
$("#contact_mob").val(data.user_mobile);
}
});
});
});
That's all
I think I found some solution, I'm going to use a timer here, there will be some permanence issues.. but I couldn't find anything be
$('#Address_Address').on('change keyup paste click', function () {
$('.pcaautocomplete .pcaselected').click(function () {
var refreshInterval = setInterval(function () {
if ($('#State').val() != "") {
var statusVal = $('#State').val();
clearInterval(refreshInterval);
}
}, 100);
});
});

Handle event for specific div among multiple div

I'm looking for guidance on the following scenario:
Context: A page displays a dynamically generated list with X (changes based on the user) number of items, each formatted as follows:
<div class="dashboard_section_item">
<label for="add_listname_label">Assign to list</label>
<br/>
<select name="mod_list" class="mod_list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
I need to handle the user selection in the dropdown list in JQuery. The problem is the list is repeated x times on the page, so it will only work for the first item displayed.
$(document).ready(function () {
$(".mod_list").change(function () {
$.ajax({
type: 'POST',
url: 'mod.php',
data: 'prod_uid=' + $('.prod_uid').val() + '&mod_list=' + $(this).find(':selected').val(),
dataType: 'json',
success: function (response) {...
},
error: function () {...
}
});
return false;
});
});
I'm thinking about concatenating a UID to the list name tag like:
<select name="mod_list_34745727" class="mod_list">
but I'm unsure whether there is a better way to do this.
How can I uniquely identify each item list to select its dropdown value?
Supposing that there are a lot of selects with class mod_list you can use on() delegation:
$(document).ready(function () {
$(document).on("change", ".mod_list", function () {
// this is the select you changed the value
var $changedValueSelect = $(this);
// do stuff, ajax and so on
// print in console the selected value
console.log($changedValueSelect.val());
});
});
Why delegation? Because you have dynamically appended elements in your page.
JSFIDDLE

Issues getting values from multiple <select>/<option>

Im having issues with the following code. Im simply trying to get the values from whatever is selected from my layout_select2 options.
Currently when selection multi_select and then a option from layout_select2 i end up with the first value from layout_select1 due to the way i load the url. I need a suggestion on how to fix this or reference either of my <select> object's
See Demo
Html
<select id='multi_select' name='multi_select'>
<option value='bing.com'>Bing.com</option>
<option value='Google.com'>Google.com</option>
</select>
<select name='layout_select' id='layout_select1'>
<option value='/images/search?q=windowsphone'>Windows Phone - Images</option>
<option value='/search?q=android'>Android - Search</option>
</select>
<select name='layout_select2' id='layout_select2'>
<option value='/search?q=Windows'>Windows - Images</option>
<option value='/images/search?q=Robots'>Robots - Search</option>
</select>
<input type='button' id='button' value='Click Me' />
JavaScript
$(document).ready(function () {
$('#button').click(function () {
var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1').val();
window.location = url;
});
$('#layout_select1').show();
$('#layout_select2').hide();
$('#multi_select').change(function () {
if ($('#multi_select option:selected').text() == "Bing.com") {
$('#layout_select1').fadeIn('slow');
}
if ($('#multi_select option:selected').text() == "Google.com") {
$('#layout_select1').hide();
$('#layout_select2').fadeIn('slow');
} else {
$('#layout_select1').fadeOut('slow');
}
});
});
You can filter the layout_select elements to use the value of the visible select like this:
$('#layout_select1, #layout_select2').filter(':visible').val();
When you combine this with a couple tweaks to your fiddle, it works pretty well:
$(document).ready(function () {
$('#button').click(function () {
var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1, #layout_select2').filter(':visible').val();
window.location = url;
});
$('#layout_select1').show();
$('#layout_select2').hide();
$('#multi_select').change(function () {
if ($('#multi_select option:selected').text() == "Bing.com") {
$('#layout_select1').fadeIn('slow');
$('#layout_select2').hide();
} else {
$('#layout_select2').fadeIn('slow');
$('#layout_select1').hide();
}
});
});

Categories