Get jQuery dropdown value onchange event - javascript

I load partialview on load page .
$(window).bind("load",
function() {
$.get("/agent/GetInfo",
function(data) {
$("#home-tab-right").empty();
$("#home-tab-right").append(data);
});
});
I have a dropdown on partialview. I want to run a function on change it. I use this code but don't run it.
$(document).ready(function(){
$('#StateId').change(function() {
var item = $(this).val();
$.ajax({
url: '#Url.Action("FindCity", "Agent")',
type: 'POST',
data: { value: item },
success: function(result) {
$("#CityId").find('option').remove();
$.each(result,
function(i) {
var optionhtml = '<option value="' +
result[i].Id +
'">' +
result[i].Name +
'</option>';
$("#CityId").append(optionhtml);
});
$(".popup-loading").hide();
}
});
});
});

In order to avoid attaching the same event multiple times. Use Off() first
$(document).off("change.findCity").on("change.findCity","#StateId",function(){ //process })

<script type="text/javascript">
$(document).ready(function (event) {
$('#StateId').on('change', function (event) {
//do something
});
});
</script>

Related

jQuery click event is not working in first click

I using a code on my page. Like this:
$('#language_id').change(function () {
var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
$.each(response.archs, function() {
options += '<option value="' + this.arch_id + '">' + this.name + '</option>';
});
$('#arch_id').html('<option value="0">- ' + selachitecture + ' -</option>'+options);
$('#arch_id').attr('disabled', false);
}
});
});
$('#arch_id').change(function(){
var version_id = $('#version_id :selected').val();
$('#selectBoxInfo').load('https://example.com/dl.php?fileName=' + arch_id + "&lang=" + lang);
return(false);
});
$('body').on('click', '.buttond a', function() {
alert("new link clicked!");
$("a").removeAttr("onclick");
});
I explain my code: when selecting an optional, it will create a button "Download". This button load by Ajax. I don't want feature pop-up of this button.
So, I tried to prevent this button turn on the pop-up.
The problem is: at first click in button, my Javascript is not working. It only works from the second click.
I don't know problem at here. I using 'on' to listen to all event.
replace your code with this code ..
$('#selectBoxInfo')
.load('https://example.com/dl.php?fileName=' + arch_id+"&lang="+lang
,function(){
$("a").removeAttr("onclick");
}
);

Dropdown value not being retained

I have a dropdown which gets its value from a model and is first populated. On click of that dropdown, I populate other values using AJAX. I am able to populate the dropdown but once I select an option from the dropdown, it gets reset to first value in the dropdown. What I want is the dropdown to populate once on click and then function like a normal dropdown. How do I put a condition for it?
This is the code for initially setting the dropdown value with the defined value 'field.Value'
ddlValue = "<option value="+field.Value+ " selected='selected'>" + field.Value+"</option>";
<td><select id='#String.Format("selValue{0}", field.Field)' class='ddlValue'>#Html.Raw(ddlValue)</select></td>
And this is the AJAX function which populates it.
$('body').on('click', '.ddlValue', function () {
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
If you want the ajax population to happen only once, you need to remove the event listener after it has occurred. Something like so:
$('.ddlValue').on('click', function () {
$(this).off('click'); //This removes the event after it has happened once.
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
Please note, the follow will not work:
$('body').on('click', '.ddlValue', function () {
$(this).off('click');
...
This seems like a silly way of doing this. You could do the same operation on loan without having any interaction with the user to populate the dropdown.
That being said to fix your solution simply add a global variable
$first = true
$('body').on('click', '.ddlValue', function () {
if($first) {
$first = false
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
}
});
});

Select option does not show data

This is my first attempt to databind an html control via ajax. I check/debug my ajax call and the data are retrieved OK, but the do not appear in the select option. My javascript is located at the bottom of my aspx page. What's the problem
$(function () {
$.ajax({
type: "POST",
url: "psHlp.asmx/getDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#District").empty();
$.each(msg.d, function () {
$("#District").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load districts");
}
});
});
This is my select option which is located at the beginning of my page
<div class="col-sm-3 col-xs-12 ffield">
<select id="District" style="display: none;">
</select>
</div>
Try using like this on your each loop.
var options;
$.each(msg.d, function () {
options += '<option value="' + this["Value"] + '">' + this["Text"] + '</option>';
});
console.log(options);
$("#District").append(options);
You need to specify (index,value) params in your $.each callback function and use value to access the iterated elements. Something like this.
$.each(msg.d, function (index,value) {
$("#District").append("<option value='" + value.Value + "'>" + value.Text + "</option>");
});
Finally I found the solution. All the above suggestions were correct. The problem occurred because I'm using bootstarp js/css (customer's designer provided the layout), so I need to rebuild the multiselect option after the append.
var options = "";
$.each(response.d, function () {
options += '<option value="' + this['Value'] + '">' + this['Text'] + '</option>';
});
$("#Town").append().html(options);
$("#Town").multiselect('rebuild');
Hope this will help at least one person :)

how to dynamically create a dropdown menu?

I have no problem creating the menu dynamically.
My problem : the class submenu is not working. I assume it's because the alert doesn't appear.
When I hard code the li´s and do not create them dynamically, the submenu works.
I'm using .NET
<script type="text/javascript">
jQuery(document).ready(function () {
mostrarGrupo01();
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
});
function mostrarGrupo01()
{
var k = 0;
var grupo01;
$.ajax({
type: "POST",
url: "Mesa.aspx/getGrupo01",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
grupo01 = response.d;
$('#grupos').empty();
$.each(grupo01, function (index, BEGrupo) {
//var r = $('<input type="button" value="' + BEAreaCC.DSAREACC + '" id="' + BEAreaCC.CDAREACC + '" name="' + BEAreaCC.CDAREACC + '" style="font-size:xx-large" onclick="botonClick(this.id, this.name, this.title);"/> ');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '" onclick="mostrarGrupo02(this.name, this.id);">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
var t = $('<li class="submenu">' + BEGrupo.DSGRUPO01 + '</li>');
$('#grupos').append(t);
k++;
});
},
failure: function (msg) {
$('#grupos').text(msg);
}
});
}
</script>
HTML :
<div class="contenedorMenu">
<nav class="menu">
<ul id="grupos">
</ul>
</nav>
</div>
The HTML element with class submenu is added to your page dynamically. You therefore need to bind your event in the following way:
$(".submenu").on('click',function () {
alert("hola");
$(this).children("ul").slideToggle();
});
You are binding the click event before .submenu is added to the DOM due to the asynchronous nature of $.ajax.
You have two options:
1 . Bind you click event within the .ajax success callback after you add the .submenu elements to the DOM
success: function (response) {
...
$.each(grupo01, function (index, BEGrupo) {
...
});
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
},
2. Or change your click binding to target the parent ul
$("#grupos").on('click', '.submenu', function () {
alert("hola");
$(this).children("ul").slideToggle();
})

Javascript Scope Issue Possibly

Having trouble with my variable 'html'. I think i have the scope correct but something weird happens when I run this code. the first alert of the 'html' variable produces a blank result and then I populate my select list with the same 'html' variable and it works, then i alert the 'html' variable again and the options show up.
If I remove the two alerts the list is not pop
function populateMakes(years)
{
var makes = new Array();
var html = "";
$.each(years, function () {
var uri = "/api/make?year=" + this;
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
});
});
alert(html);
$("#Make").html(html);
alert(html);
$("#MakeSection").removeClass("hidden");
};
Document Ready Script
$(document).ready(function () {
populateYears();
$("#Year").change(function () {
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateMakes($("#Year").val());
});
$("#Make").change(function () {
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateModels($("#Year").val(), $("#Make").val());
});
$("#Model").change(function () {
$("#SubModelSection").addClass('hidden');
//
});
$("#Clear").click(function () {
$("#YearSection").addClass('hidden');
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateYears();
})
});
.getJSON is async and i overlooked the timing. i needed to add the .done callback and set the output there. the script simply wasn't finished yet.
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
}).done(function () {
$("#Make").html(html);
$("#MakeSection").removeClass("hidden");
});
I also didn't send an array in the event handler on the code I posted in the question. I fixed that first.

Categories