Variable Query by Checkbox - javascript

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();
});

Related

How do I prevent reset the select box after ajax post action?

I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.

Change a tooltip content on hover over session times button

My ASP.Net webpage generates buttons with below codes
<a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1" target="_self" href="https://localhost:6969/VenueTicketing/Start.aspx?sessionId=248506&cinemaId=cbcc0921bb8e233ab9626690" class="tooltip" title="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1">11:30am</a>
When I hover over session I see basic information about session like screen name and seats remaining. Please see screenshot attached
On hover over session I want to display real time seats remaining number, So i am making an ajax call to a function which send api request and get live seats remaining number.
I am trying to update seats remaining number on rendered page by using following java script code.
<script type="text/javascript">
$(document).ready(function () {
function handler(ev) {
var target = $(ev.target);
var sessionid = target.attr('id');
var sessionPOSid = target.attr('val');
var TooolTipText = target.attr('titletext');
target.attr('title', TooolTipText);
if (sessionPOSid == "done")
{
}
else
{
if (target.is(".tooltip")) {
$.ajax({
type: "POST",
url: '../WebService/Home_SessionTimes.asmx/GetSeatsRemaining',
data: "{sessionId: '" + sessionid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//alert(msg.d);
var n = TooolTipText.indexOf("Seats Available: ");
var t = TooolTipText.substr(n + 17, 3);
if (t.indexOf("<") >= 0) {
if (t.indexOf("<") == 2) {
t = t.replace("<", "");
}
else {
t = t.Substring(0, 1);
}
}
TooolTipText = TooolTipText.replace(t, msg.d);
$('#' + sessionid).attr('title', TooolTipText);
$('#' + sessionid).attr('titletext', TooolTipText);
//$('#' + sessionid).attr('val', "done");
target.attr('title', TooolTipText);
target.tooltiptext = TooolTipText;
},
});
}
}
}
$(".tooltip").mouseover(handler);
});
Above code updates the "titletext" field of tag but does't change anything on "title" field.
Any help would be appreciated.
I have solved this by using qtip. Every time user hovers over div with 'sessiontimes' class, I make ajax call to generate tooltip text (that comes from server based upon session time).
This is my output now:
This is the jQuery code. you need to import qtip css and script files from their website.
<script type="text/javascript">
$(document).ready(function () {
$('.sessiontimes').qtip({
style: { classes: 'qtip-bootstrap' },
content: {
text: function (event, api) {
$.ajax({
url: '../SessionToolTip.aspx',
data: 'sid=' + $(this).children("a").attr("id"),
dataType: "text",
})
.then(function (content) {
api.set('content.text', content);
}, function (xhr, status, error) {
api.set('content.text', status + ':' + error);
});
return 'Loading...';
}
}
});
});
</script>
If you may look at this post and see if the same answer could apply to your situation
JQUERY Change Title not working with tooltip

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

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.

Make a loop in jquery

Hello I want to know how to make a loop so that my js is through an id because I have an email id for 2 fields for 2 different forms
I would then be able to choose when I click on the id of my form right that displays the error only on the right form and vice versa
My code :
<script type="text/javascript">
$(document).ready(function(){
$("input#id_st-courriel").focusout(checkEmailField);
});
function checkEmailField() {
$fieldValue = $("input#id_st-courriel").val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
if ($data != '') {
$("input#id_st-courriel").parent().prev('errorlist').remove();
$("input#id_st-courriel").parent().before($data);
}
}
})
}
</script>
I have an id : id_st-courriel
and an other id for my second formulaire : id_em-courriel
For the moment I're the error display on my first form with the id: id_st-courriel
Edit :
I have a second problem
My views.py
def ajax_check_email_field(request):
form = LoginForm(request.POST)
HTML_to_return = ''
if 'value' in request.GET:
field = forms.EmailField()
try:
field.clean(request.GET['value'])
except exceptions.ValidationError as ve:
HTML_to_return = '<ul class="errorList">'
for message in ve.messages:
HTML_to_return += '<li>' + message + '</li>'
HTML_to_return += '</ul>'
return HttpResponse(HTML_to_return)
<ul>
<li>foo</li>
<li>bar</li>
</ul>
//You can select the list items and iterate across them:
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
You can make some minor changes to do it like
Update the selector to select both the fields - either use a class selector after add a common class to both the fields or use multiple selector syntax to select both the elements using their id
In the event handler dynamically select the current element by using this reference - in the event handler this will refer to the input element which triggered the event
So
$(document).ready(function() {
$("#id_st-courriel, #id_em-courriel").focusout(checkEmailField); //you can simplify the selector if you can add a common class to both these fields and then use the class selector to add the event handler
});
function checkEmailField() {
var $fileld = $(this);
var $fieldValue = $fileld.val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
$fileld.parent().prev('.errorlist').remove();//may be .errorlist if it is a class
if ($data != '') {
$fileld.parent().before($data);
}
}
})
}
You could pass $(this) to you function checkEmailField to refer to the current focused out field, try :
$(document).ready(function(){
$("input#id_st-courriel, input#id_em-courriel").focusout(function(){
checkEmailField($(this));
});
});
function checkEmailField(_this) {
$fieldValue = _this.val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
if ($data != '') {
$(_this).parent().prev('errorlist').remove();
$(_this).parent().before($data);
}
}
})
}
Hope this helps.

Categories