Select boxes, disabling values based on values in an array - javascript

I have a select menu, that gives the user some criteria options that can use to act as a filter on a search, the user can add as many filters as they wish, however at the moment the user can add the same filter more than once.
What I am wanting to do is, when a user selects a filter from the select box, the value gets added into a array, and then that option in the select box is disabled, is this possible with javascript & jquery?
Currently I have the following
Code that creates a new filter select menu
$('select.option').live({
change: function() {
if($(this).val() == 'distance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/distance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'height')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/height',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'appearance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/appearance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'education')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/education',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'children')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/children',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'smoking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/smoking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'drinking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/drinking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'politics')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/politics',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'religion')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/religion',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'ethnicity')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/ethnicity',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'work')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/work',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
}
});

as the name of url and selected option is the same you can try this:
$('select.option').on({
change: function() {
var element = $(this).val();
$(this).prop('disabled', true);
$.ajax({
url: site_url + 'ajax/row/' + element,
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
})

Don't know what your HTML looks like, but I would make it look roughly like this:
<select class="option">
<option value="distance" data-path="ajax/row/distance">Distance</option>
<option value="height" data-path="ajax/row/height">Height</option>
...
</select>
Then have the jQuery be (assuming there are multiple selects in one page and a filter can only be applied once per row):
$('select.option').live({
change: function() {
// get selected history or empty array
var selected = $(this).data('selected') || [];
// get selected option
var $element = $(this).find('option:selected');
// if selected option in history, return
if($.inArray($element.val(), selected) return;
// otherwise, add to history and save back into element
selected.push($element.val());
$(this).data('selected', selected);
// query AJAX by using the data- attribute of the option
$.ajax({
url: site_url + $element.data('path'),
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
});

Related

JQuery select 2 disables Jquery Ajax Call

Am trying to use select2 JQuery feature that enables searching by text through drop down menu options, and at the same time the retrieved drop-down elements are retrieved from the back-end using ajax call,
if i removed select2 it works probably, but it if i added select two the on-click function is not even triggered.
Here is my code
var area = 0;
$("#area").on("click", function () {
if (area == 0) {
$.ajax({
type: "Get",
url: "/Filters/Areas",
datatype: "json",
traditional: true,
success: function (data) {
area = area + 1;
console.log(area);
for (var i = 0; i < data.length; i++) {
$("#area").append('<option class = "form-control" value=' + data[i].Value + '>' + data[i].Text + '</option>');
}
}
});
}
});
$(document).ready(function () {
$("select").select2();
});
You can listen to the selected event, base on this documentation
$(document).ready(function() {
$('#area').select2();
$('#area').on('select2:select', function(e) {
const _val = $(e.target).val();
if (_val === "0") {
$.ajax({
type: "Get",
url: "/Filters/Areas",
datatype: "json",
traditional: true,
success: function(data) {
area = area + 1;
console.log(area);
for (var i = 0; i < data.length; i++) {
var newOption = new Option(data[i].text, data[i].value, false, false);
$('#area').append(newOption).trigger('change');
}
}
});
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select id="area" name="area">
<option value="">Test</option>
<option value="1">testus</option>
</select>

Calling ajax several times result a duplicated response

I created an ajax function that returns my items Price by fetching from my DB. I'm sure there isn't any problem with my php but sometimes I get the same result twice!
jQuery
$('.removemore___').click(function(e) {
var item_id = $(this).attr('data-item');
var col_id = $(this).attr('data-col');
var value = $(this).attr('data-value');
if ($(this).attr('data-trash') == 'trash') {
newPopuper('alert_sure__', 'flex', 'blackScreen');
$('.__aggtoyes').attr('data-item', item_id);
$('.__aggtoyes').attr('data-col', col_id);
$('.__aggtoyes').attr('data-value', value);
} else {
$.ajax({
type: "POST",
url: "includes/chekavailableitem.php?remove",
data: {
item_id: item_id,
col_id: col_id,
value: value
},
dataType: "text",
success: function(response) {
var iNum = parseInt(value);
iNum--;
if (response == 'done') {
$('.value__cart[data-item=' + item_id + '][data-col=' + col_id + ']').html(iNum);
$('.removemore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
$('.addmore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
if (iNum == 1) {
location.reload();
}
} else if (response == 'deleted') {
location.reload();
}
},
error: function() {
$('#wrong-signup').html(': 102');
},
timeout: 5000
});
}
$.ajax({
type: "POST",
url: "includes/get_finalize_cart.php",
data: {},
cache: false,
async: true,
dataType: "json",
success: function(response) {
// var final_price = $.parseJSON(response)
console.log(response);
if (response[0] == 'done') {
$('.final_price__').html(response[1] + ' <span style="font-size: .786rem;font-weight: 400">تومان</span>');
} else {
}
},
error: function() {
$('#wrong-signup').html(': 101');
},
timeout: 5000
});
e.stopImmediatePropagation();
return false;
});
Here is full function in jQuery
<?php
include 'db.php';
include 'function.php';
$user_id = extractUserId();
$chekcart = "SELECT * FROM `box` WHERE `user_id`='$user_id'";
$result_cox_cart_cheker = connectANDdie($chekcart);
$sum_price = 0;
while($row_items = mysqli_fetch_assoc($result_cox_cart_cheker)){
$price = $row_items['item_price'];
$value = $row_items['value'];
$sum_price = $sum_price + ( $price*$value );
$final_value = number_format($sum_price);
$result = ['done',$final_value];
$result1 = json_encode($result);
echo $result1;
}
and I'll also show a screenshot from console page so you can see what my result is:
You're not waiting for chekavailableitem.php?remove to complete before you call get_finalize_cart.php. Since AJAX is asynchronous, the latter might be processed first, so you'll get a duplicate of the old value.
You should put the second $.ajax() call in the sucess: function of the first $.ajax() call, or use a promise.

Ajax post formdata net::ERR_CONNECTION_RESET

I have 2 similar JS functions:
1)
$(area).on('click','#copy',function (e) {
//var images=[];
e.preventDefault();
var $this=$(this);
var $gal=$this.closest('.gal_insertion_new');
var id=$gal.attr('gal_id');
var $copy=$gal.find("#copy");
$copy.attr("disabled", true);
var copy_to=$gal.find('#copy_to').val();
var row_paste=$gal.find('#row_copy_to');
var formData=new FormData();
var row_p_l=row_paste.length;
var row_p_v=row_paste.val();
console.log(row_p_v);
if (copy_to=='') {
alert('Заполните id галереи');
return;
}
formData.append('gal_id',id);
if ($gal.find('input:checked').length<1){
alert('Выберите хотябы одну картинку');
return;
}
$.each($gal.find('input:checked'),function (i,item) {
formData.append(i,$(item).attr('image_id'));
});
formData.append('what','copy_images');
formData.append('where',copy_to);
if (row_p_l>0) {
if (row_p_v==''){
alert('Заполните номер ряда');
return;
}
formData.append('where_row',row_p_v);
}
$.ajax({
type:'post',
data:formData,
cache:false,
contentType: false,
processData: false
}).done(function (response) {
console.log(response);
//alert(response);
if (response[0]==0) {
alert(response[1]);
} else if (response[0]==1) {
alert(response[1]);
} else if (response[0]==2) {
alert(response[1]);
} else {
if ($('div[gal_id=' + copy_to + ']').length > 0) {
if (row_p_l > 0) {
response.forEach(function (item,i) {
$('.row_item_img_preview[image_id=' + item['id'] + ']').attr('src', item['path']);
});
} else {
$('.img_previews[gallery_id=' + copy_to + ']').append(response);
}
alert('Скопировано');
}
}
$copy.attr("disabled", false);
});
});
2)
$(area).on('click','#delete_selected_images',function (e) {
e.preventDefault();
console.log('delete');
var $this=$(this);
//$this.attr("disabled", true);
var $gal=$this.closest('.gal_insertion_new');
var id=$gal.attr('gal_id');
var formData=new FormData();
//console.log(row_p_v);
formData.append('gal_id',id);
if ($gal.find('input:checked').length<1){
alert('Выберите хотябы одну картинку');
return;
}
$.each($gal.find('input:checked'),function (i,item) {
formData.append(i,$(item).attr('image_id'));
console.log(item);
});
formData.append('what','delete_images');
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
type:'post',
data:formData,
cache:false,
contentType: false,
processData: false
}).done(function (response) {
console.log('delete2');
/*
console.log(response);
//alert(response);
$.each($gal.find('input:checked'),function (i,item) {
$(item).remove();
});
*/
$this.attr("disabled", false);
});
});
The first one works perfect, but the second one gives me net::ERR_CONNECTION_RESET error.
I'm using laravel, PHP 7.0.1, currently running on OpenServer.
The use of debugger gives nothing, but the understanding that the error is somewhere in the framework, or in my script.
Using json is not an option, cause of my PHP code...

Undefined Javascript variable - phcat

I have a function that returns an undefined variable. I tried all responses in some similar posts but no results.
identifier_id is defined but phcat is not defined. Any ideas?
$(function() {
$('body').on('click', '.save_random_profile', function() {
var identifier_id = $(this).attr("id");
$('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />');
var phcat = document.getElementById('#phcat'+identifier_id).value;
alert(phcat);
$.ajax({
type: "POST",
async: false,
url: "actions/save_random_profile.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
$('.created_profile' + identifier_id).html('Not Sent!');
} else {
$('.created_profile' + identifier_id).html(data);
}
}
});
return false;
});
});
Try jquery.attr().
Object.id is a native javascript method and will not be applicable on a jquery collection objects.
To get the id in a jquery object, use var phcat = $('.phcat#' + identifier_id).attr("id");
Or if you want to persist with javascript, use document.querySelector('.phcat#' + identifier_id).id;
$(function() {
$('body').on('click', '.save_random_profile', function() {
var identifier_id = $(this).attr("id");
$('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />');
var phcat = $('.phcat#' + identifier_id).attr("id");
alert(phcat);
$.ajax({
type: "POST",
async: false,
url: "actions/save_random_profile.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
$('.created_profile' + identifier_id).html('Not Sent!');
} else {
$('.created_profile' + identifier_id).html(data);
}
}
});
return false;
});
});
EDIT
If you are using document.getElementById, do not use the # along with the id.
var phcat = document.getElementById('phcat'+identifier_id).value;
Use var phcat = $('.phcat#'+identifier_id).attr('id');
use
var phcat = $('.phcat#' + identifier_id)[0].id;
it will give you native JS obj
OR
var phcat = $('.phcat#' + identifier_id).attr('id');
it will return id of element

Multiple form submission

function saveConfig(val)
{
if(val == 1){
document.f1.submit();
document.f4.submit();
}
else if(val == 2){
document.f2.submit();
}
else if(val == 3){
document.f3.submit();
}
document.f0.submit();
}
Hi The above code works well in IE6, IE7, IE8, FF3.0.19, FF3.5.19 and FF3.6.20. However it doesnot work on Firefox versions > 4. Please help me in understanding what was wrong with the above code.
Can try by using
var form1=document.getElementsByName('f1');
form1.submit();
function f0Submit() {
document.f0.submit();
}
function f4Submit() {
var dataString = $('f4').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
function saveConfig(val) {
if(val == 1) {
var dataString = $('f1').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f4Submit();
}
});
}
else if(val == 2){
var dataString = $('f2').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
else if(val == 3){
var dataString = $('f3').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
}

Categories