Dropdown value not being retained - javascript

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/>'))
});
}
});
});

Related

jQuery AJAX get value from .each function and send it to AJAX

How to set jQuery AJAX outside .each on my script below?
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
var moduleID = $(this).val();
var chk = new Array();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: moduleID,
chk: chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
});
If I put the AJAX function inside .each function it will submit more than 1.
But I need to put it outside, and found problem moduleID and chk not found.
Scope problem. Define uid and moduleID outside the click.
var uid="";
var moduleID="";
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
uid = $(this).attr('id'); // Assign value for uid
moduleID = $(this).val();
Define the variables in the global scope:
make a function called sendAjax and call it on button click.
In the mean time all your data will be stored in the data global variable (object).
var data={};
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
data.moduleID = $(this).val();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
data.chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
sendAjax();
});
function sendAjax()
{
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: data.moduleID,
chk: data.chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
}

Variable Query by Checkbox

I have created this code to filter the search by checkbox but I haven't find a final solution..!
This doesn't work when for example I click on 'All Colors' or 'All Brand'..
And not work when I recheck the checkbox because I haven't idea..!
This is a search to filter the results in eBay style, with combobox and much checkbox.. I want this to filter without the reload of the page..
This is the partial code..
function create_query(add){
var query = "SELECT * FROM computers WHERE 1 = 1 "+add+" ORDER BY " + ($("#ordine option:selected").val()) + " LIMIT " + ($("#risultati option:selected").val());
$.ajax({
type: "POST",
url: "static/cerca_prodotti.php",
data: "query="+query,
dataType: "html",
success: function(risposta){
$("div#risultati").html(risposta);
},
error: function(){
alert("Chiamata fallita!!!");
}
})
}
$( "[type=checkbox]" ).change(function() {
text = $(this).parent().text();
gruppo = this.getAttribute("name");
if(this.checked) {
}
else {
create_query('AND '+gruppo+' NOT LIKE "'+text+'"')
}
});
$("#ordine").change(function() {
create_query();
});
$("#risultati").change(function() {
create_query();
});

Updating rows that are added dynamically using ajax

I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.

How to set the default selection on the currently added item using jquery

I have this code using this code I am inserting an item from one list box to other list box. I need to set the default selection for tagrget list box item when it is added.
please can any body help me out how to set the deafult selection to the list box.
How to set the default selection to the currently added item to the list box
function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val(); /// Selected Item to add
var targetIndex = $("#lstCodelist").val(); /// added item to the list box(target list box)
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
FinishAjaxLoading();
}
});
could you use
.focus()
Example:
$("#lstCodelist").focus();
you can use .focus in the success callback to set the focus
$("element").focus()

jquery autocomplete not populating unless entered text is in the first result

Im having an issue with jquery autocomplete plugin. the textbox im using wont populate the results of autocomplete until i enter a value that is in the first entry of my data. After it populates that, then the autocomplete works how its supposed to.
$(document).ready(function () {
});
function textChange() {
var callback = function (request, response) {
var searchText = request.item;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
})
}
after playing around with it i got the following code to work, before i was using an onkeyup event in the text box but i guess i didnt need it. i dont know if this is efficient but it is working correctly now.
$(document).ready(function () {
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
});
});
var callback = function (request, response) {
var searchText = request.term;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}
You have to use a callback as the source option when you initialize the autocomplete (in your example you initialize the autocomplete every time a key is being pressed):
var callback = function(request, response) {
var searchText = request.item;
// Set searchField somehow here
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data)
{
var splitData = data.split(",");
response(splitData);
});
});
};
$( ".searchTextBox" ).autocomplete({
source: callback,
autoFill: true
});
There are some more examples and a more detailed description in the documentation.

Categories