JQuery select 2 disables Jquery Ajax Call - javascript

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>

Related

JavaScript running on page load

This JS is running on my page load and I don't want it to. I thought it should wait for change of ddlEquipment but it isn't. On top of that selectedID4 should be null at page load so it shouldn't run the if. Does anyone know how I can stop this?
$("#ddlEquipment").change(function() {
var selectedid = $('#ddlSubDepartments option:selected').val();
var selectedid2 = $('#ddlDepartments option:selected').val();
var selectedid3 = $('#ddlMachines option:selected').val();
var selectedid4 = $('#ddlEquipment option:selected').val();
alert("test");
if (selectedid4 != null) {
$.ajax({
url: "/Problem/PopulateProblemsddl",
data: {
id: selectedid,
id2: selectedid2,
id3: selectedid3,
id4: selectedid4
},
type: "Post",
dataType: "Json",
success: function(result) {
console.log(result);
var s = '<th></th>';
for (var i = 0; i < result.length; i++) {
s += '<th>'
result[i].value '</th>';
}
console.log(s);
$('#NameOfProblem').html(s);
});
}
else {
alert("this is else");
}
});
Wrap you function into
window.addEventListener('load', () => {
$("#ddlEquipment").change(function () {
// rest of your 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

Working on dynamically added input elements with Typeahead

This is my code in adding rows which also have the class='form-control mybur':
$("body").on("click", "#add_row_bur", function() {
$("#bur" + o).html("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>;
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});
I tried implementing typeahead on it but it doesn't work. I tried using this answers ( answer 1, answer 2), but still fails.
Here's my code:
var objects = [];
var map = {};
$('input.mybur').typeahead({
source: function(query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function(data) {
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function(item) {
$('input.mybur').blur(function() {
$(this).val(map[item].code);
});
return item;
}
});
I deleted all the code that I tried. Again, this will work on a pre-created elements:
<input type="text" name='bur_account_code[]' placeholder='Account Code' class="form-control mybur" data-provide="typeahead" required/>
The problem is for the dynamically added input elements, you need to initialize the plugin after they are created.
So one solution is first create a method which can be reused to initialize the plugin for a passed set of elements like
var objects = [];
var map = {};
function createTypeahead($els) {
$els.typeahead({
source: function (query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function (data) {
objects = [];
map = {};
$.each(data, function (i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function (item) {
$('input.mybur').blur(function () {
$(this).val(map[item].code);
});
return item;
}
});
}
//for the already present elements
createTypeahead($('input.mybur'));
then in the add new element code
$("body").on("click", "#add_row_bur", function() {
var $td = $("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>")
$("#bur" + o).html($td);
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
createTypeahead($td.find('input.mybur'));
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});

Bypass Input FIle; Uploading Image directly using javascript

I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Sizeļ¼šUnder 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!

Select boxes, disabling values based on values in an array

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

Categories