AJAX - After success clean input value and set dropdown to selected - javascript

I have a page with a dropdown list and a input with type="text".
I'm trying to filter the results of my table via AJAX when I select an option in my dropdown list.
It should clean the value of the input when the option is selected (after the success).
It's working fine.
The problem is that I need it to for my input. It should send the value of the input to AJAX and then filter the results when I submit the form.
I can't put it to work after the suceess. It sets the dropdown list to "selected". I don't know why.
HTML code:
<form action="#Url.Action("a","b")" id="filter-date" onsubmit="javascript:return false">
<label for="from" class="label-datepicker">from:</label>
<input type="text" id="from" name="from" class="dateinput">
<label for="to" class="label-datepicker">to:</label>
<input type="text" id="to" name="to" class="dateinput">
<button type="submit" name="submit" id="submit-date">
OK
</button>
</form>
<select name="Assunto" id="select-a">
<option value="" selected="selected">--Select--</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
JavaScript code:
$("#select-a").change(function () {
var selected = $("#select-a").val();
var Keyword = { data: $("#select-a").val() };
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("bo", "b"))',
data: { Keyword: selected },
dataType: 'html',
success: function (data) {
$(".dateinput").val('');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
$("#select-a").val(selected);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});

Try this
As #Anto rightly said
var selected = $("#select-a").val();
scope of this above statement should be in form-submit also
$("#select-a option[selected]").removeAttr("selected");
$("#select-a option[value=" + selected+ "]").attr('selected', 'selected');

Try:
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
// $("#select-a").val(selected); //should remove this line because we use ajax, the page is not refreshed, not need to restore the state.
//or $("#select-a").val(""); if you need to reset
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
return false; //return false at the end to prevent form submitting
});
And remove onsubmit="javascript:return false". And should not use - in id attribute.

i have found a solution.. and its solved now.
its more easier if i thought.
the ajax call on .submit doesn´t allow me to do something after success like what i need..
this i don´t know it.
what i have done is to set the value of the option from my dropdownlist to selected before the ajax section.
and the magic is done..
its working now.
this is my new code:
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$('#select-a').val('selected');
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
$("#select-a").val(selected);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});

Try use jQuery function .data(name, value) to store selected value like this:
$('#select-a').data('selectedValue', $('#select-a').val());
Then in submit handler get it:
var selected = $('#select-a').data('selectedValue');
And use #Nitin's code to set selected option:
$("#select-a option[selected]").removeAttr("selected");
$("#select-a option[value=" + selected+ "]").attr('selected', 'selected');

Just make selected global:
(function(){
var selected;
$("#select-a").change(function () {
selected = $("#select-a").val();
// rest of your script
})(); // close the wrapper
EDIT: Wrapping it up in a self-executing anonymous function will keep the global namespace clean (thanks to #jameslafferty).

Related

Getting an error when i loop through to get input name value

Can't figure out why this loop won't give me the info i'm wanting
I have a page with a few hundred inputs on it , i want to get the the input "name" value for each input that is checked
<input type="checkbox" name="TAXI_SQUAD0001" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0021" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0011">
$.ajax({
url: urlHPM,
xhrFields: {
withCredentials: true
},
cache: false,
type: "GET",
success: function (data) {
checkedInputs = $(data).find('input[checked="checked"]');
for (var i = 0; i < checkedInputs.length; i++) {
console.log(checkedInputs.attr('name')[i]); // loops character of first name of first input over and over
console.log(checkedInputs[i].attr('name')); // error attr not a function
// i want to log input names TAXI_SQUAD0001 and TAXISQUAD0021
}
},
error: function (xhr) {
}
});
You can loop all checked checkboxes in the ajax success response using the .each() jQuery function.
$.ajax({
url: urlHPM,
xhrFields: {
withCredentials: true
},
cache: false,
type: "GET",
success: function (data) {
checkedInputs = $(data).find('input[checked="checked"]');
$(checkedInputs).each(function(){
//Log the input name attribute
console.log($(this).attr('name'));
});
},
error: function (xhr) {
}
});
You are accessing the DOM when you do checkedInputs[i]. It is not the jQuery wrapped code. You can do checkedInputs.eq(i).attr('name') or just checkedInputs[i].name
Your code also does not need the for loop. You can just use each.
checkedInputs.each(function () {
var cb = $(this);
console.log(cb.attr('name'));
});

select2 set option attributes manually for each option

i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?
Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

Is there a way to use the same jQuery Ajax for multiple items on a single page?

I have a page where people can add things to their "favorites" list with this:
$(function(){
$('.doit-01234').click(function (e) {
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$(".result-01234").html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$(".result-01234").html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
});
The items get added with page.php?add=01234. The same page may however have 20 or 30 items that people can add to their favorites. Is there an easy way to use just one instance of this script for multiple IDs instead of the same jQuery code over and over after each item?
Meaning page.php?add=9999 would then update .result-9999 when .doit-9999 is called and page.php?add=5151 would update .result-5151 and so on...
Give your elements a common class and a custom data attribute:
<div class="ajax doit-01234" data-id="01234"></div>
And then use 1 handler:
$('.ajax').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Create this function like this:
function Name (e) {
var code = 01234;//extract your code like 1234 here by splitting or..
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$('.result-'+code).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$('.result-'+code).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Now where you want to call this function , you can call like this:
HTML:
<button onclick="Name(this);">Hello</button>

How to set Select2 value using initSelection?

I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.
Here is my script:
$("#sub_lessons").select2({
maximumSelectionSize: 1,
placeholder: "Select Sublessons",
allowClear: true,
multiple:true,
ajax: {
url: "getData.action?lid="+lessonid,
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
My html snippet:
<input type="hidden" id="sub_lessons" style="width:300px"/>
When we clicking on the select2 box the data is loading perfectly,
but I have the function like setValue() when button is clicked.
<input type="button" onclick="setValue(1)"/>
And my function is:
function setValue(no)
{
$('#sub_lessons').select2('val',no);
}
But the value is not being set. I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.
any help would be appreciated.
try something like this
$('#sub_lessons').select2('val','no');
I try this; work for me. You should add this to initSelection select2:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#sub_lessons').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},

Categories