Can't trigger a function in Vue js - javascript

This is my JS code
getItemData:function(e){
var id = e.target.getAttribute('data-id');
var uom = e.target.options[e.target.options.selectedIndex].dataset.uom;
var uomId = e.target.options[e.target.options.selectedIndex].dataset.uomid;
if(uomId == null || uom == null){
$('#uom_item'+id).html('<option value="" selected></option>');
}
this.GetItemTotalAmount(id);
this.getItemGroupUOM(id);
this.getVatStructure(id);
},
getVatStructure:function (id)
{
var trans_sub_type = $('#trans_sub_type').val();
var prod_type = $('#product_type').val();
var hsCode = $('#hs_code'+id).val()
var defaultVatRate = $('#default_vat_rate_id'+id).val()
$.ajax({
url:'get-vat-structure-by/item',
method:'get',
data:{'tranSubType':trans_sub_type,'prod_type':prod_type,'hs_code':hsCode,'defaultVatRate':defaultVatRate},
success:function(res){
// console.log(res);
$('#vat_structure_rate'+id).html(res.result);
if (!res.isTrue)
{
$('#vat_item'+id).val(null);
$('#vat_amount_item'+id).val(null);
}
$('#vat_structure_rate'+id).trigger("change");
console.log('trg');
},
error:function(err){
console.log(err);
}
});
},
getVatData:function (e)
{
console.log('inside');
var id = e.target.getAttribute('data-id');
var vat = e.target.options[e.target.options.selectedIndex].dataset.vat;
$('#vat_item'+id).val(vat);
this.GetItemTotalAmount(id);
}
I want to trigger getVatData() which is an on change function declared in HTML as #change="getVatData" function from getVatStructure function.
How can I do that. I have tried the following but now working.

Related

How to fix onload function with Conditional If and else

My problem here is the fact that I don't know how to do the if statement. for onload page I want when the id is #lang_link\[fr\] directly run function ParseJSON1 and when my id #lang_link\[en\] run function ParseJSON2
I want to fix this:
window.onload = function runAtLoadTime() {
if(document.getElementsById('#lang_link\\[fr\\]').value = 'fr' ){
ParseJSON1();
}
else
{
ParseJSON2();
}
}
to call:
$(document).ready(function (){
$('#lang_link\\[fr\\]').click(function (){
ParseJSON1('fr');
});
$('#lang_link\\[en\\]').click(function (){
ParseJSON2('en');
});
});
code to run:
function ParseJSON1() {
var JSONObject = {
"footerboutiques": "Sourav french",
"boutiquelink": "https://www.w3schools.com/js/js_loop_for.asp",
"footerrestaurants": "Kayal",
"Restaurantslink": "https://www.w3schools.com/js/js_loop_for.asp",
"footeracces": 24,
"acceslink": "https://www.w3schools.com/js/js_loop_for.asp",
"footeraerogare": "123456" ,
"aerogarelink": "https://www.w3schools.com/js/js_loop_for.asp",
};
var Value = eval(JSONObject);
document.getElementById("footerboutiques").innerHTML = Value.footerboutiques;
document.getElementById("boutiquelink").href = Value.boutiquelink;
document.getElementById("footerrestaurants").innerHTML = Value.footerrestaurants;
document.getElementById("Restaurantslink").href = Value.Restaurantslink;
document.getElementById("footeracces").innerHTML = Value.footeracces;
document.getElementById("acceslink").href = Value.acceslink;
document.getElementById("footeraerogare").innerHTML = Value.footeraerogare;
document.getElementById("aerogarelink").href = Value.aerogarelink;
}
function ParseJSON2() {
var JSONObject = {
"footerboutiques": "Sourav2 english",
"boutiquelink": "https://developer.mozilla.org/fr/docs/Web/API/Document/getElementById",
"footerrestaurants": "Kayal2",
"Restaurantslink": "https://developer.mozilla.org/fr/docs/Web/API/Document/getElementById",
"footeracces": 242,
"acceslink": "https://developer.mozilla.org/fr/docs/Web/API/Document/getElementById",
"footeraerogare": "1234562" ,
"aerogarelink": "https://developer.mozilla.org/fr/docs/Web/API/Document/getElementById",
};
var Value = eval(JSONObject);
document.getElementById("footerboutiques").innerHTML = Value.footerboutiques;
document.getElementById("boutiquelink").href = Value.boutiquelink;
document.getElementById("footerrestaurants").innerHTML = Value.footerrestaurants;
document.getElementById("Restaurantslink").href = Value.Restaurantslink;
document.getElementById("footeracces").innerHTML = Value.footeracces;
document.getElementById("acceslink").href = Value.acceslink;
document.getElementById("footeraerogare").innerHTML = Value.footeraerogare ;
document.getElementById("aerogarelink").href = Value.aerogarelink;
}

Angular js: Everything works fine but the buttons created in html inside compile does not work

Everything is working fine in my code except the line of HTML below
> $compile('<button class="btn btn-link ng-scope" data-ng-click="Flow.GetFarePriceRule('+ start_point +','+ end_point +')">'+ $scope.fare_base_code_array[i-1].FareBasis["#attributes"].Code +'</button>');
$timeout(() => {
console.log($el.prop('outerHTML'))
});
The button links are showing correctly but when I click on them they do not work. I guess the HTML is not binding with angular because the function in that HTML does not call after clicking.
$scope.ptc_break = function(variable , index , key)
{
$scope.fbc=[];
if (Array.isArray(variable) == false) {
$scope.fbc.push(variable);
}else{
$scope.fbc = variable;
}
$scope.fare_base_code_array = $scope.fbc;
$scope.temp_array = [];
var fare_base_var = '';
var count = 0 ;
var comma = '';
var start_point = 1;
var end_point = 0;
var fare_base_include = "";
for (var i = 0; i <= $scope.fare_base_code_array.length; i++) {
if (i == $scope.fare_base_code_array.length) {
fare_base_include = "";
}else{
fare_base_include = $scope.fare_base_code_array[i].FareBasis["#attributes"].Code;
}
if ($scope.temp_array.includes(fare_base_include) == false) {
count++;
if (count>0) {
comma = ",";
}else{
comma = '';
}
if (i > 0) {
var $el = $compile('<button class="btn btn-link ng-scope" data-ng-click="Flow.GetFarePriceRule('+ start_point +','+ end_point +')">'+ $scope.fare_base_code_array[i-1].FareBasis["#attributes"].Code +'</button>')($scope);
$timeout(() => {
console.log($el.prop('outerHTML'))
});
fare_base_var = fare_base_var + $el.prop('outerHTML') + comma;
}
start_point = end_point + 1;
setTimeout(function() {
delayFunction1();
}, 1000);
function delayFunction1(){
// if (key == 0) {//$('#fare_base_'+index).html(fare_base_var);
// el = document.getElementById('#fare_base_'+index);
// angular.element(el).append( $compile(fare_base_var)($scope) )
// }
if (key == 0) {$('#fare_base_'+index).html(fare_base_var);}
if (key == 1) {$('#private_fare_base_'+index).html(fare_base_var);}
if (key == 2) {$('#fare_base_best_buy_'+index).html(fare_base_var);}
if (key == 3) {$('#private_fare_base_best_buy_'+index).html(fare_base_var);}
if (key == 4) {$('#fare_base_alternative_'+index).html(fare_base_var);}
}
}
if (i != $scope.fare_base_code_array.length) {
$scope.temp_array.push($scope.fare_base_code_array[i].FareBasis["#attributes"].Code);
}
end_point++;
}
}
and this is the function that i am calling..
$scope.GetFarePriceRule = function(start , end_number){
alert("hello");
$scope.price_rule_para = "";
$('#private_fare_base_'+index)
alert(start);
alert(end_number);
$('#myModal2').modal('show');
$scope.select_traveler_type = $scope.send_passenger_type;
$( ".rule_modal_loader" ).addClass( "loader" );
var url = base_url+"/start_soap_fare_price_rule_workflow.php";
$scope.getfarerules = {
'ItneraryNo': $scope.pnr_number,
'FlightSegment': $scope.send_pasenger_segment,
'PassengerType': $scope.send_passenger_typee,
'rule_passenger_type': $scope.rule_passenger_type ,
'FareType': "Public",
'carrier_code': null,
'kind_of_fare' : "retain",
'start_point':start,
'end_point':end_number
};
$http({
method: 'POST',
url: url,
data: $.param($scope.getfarerules),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
console.log(response);
var myar = response.RulesFromPriceRS.FareRuleInfo.Rules.Paragraph.Text.replace(/-/g, "");
var myarr = myar.split(".");
$scope.price_rule_para = myarr;
$('#Price_head').show();
$('#Price_itinerary_table').show();
$('#price_itinerary_btn').hide();
$('#Issue_air_ticket_btn').show()
$( ".rule_modal_loader" ).removeClass( "loader" );
}).error(function(response) {
console.log(response);
alert(response);
alert("error");
alert('This is embarassing. An error has occured. Please check the log for details');
});
};
please help me out to get out of the situation
outerHtml return string, simple string. So you discard all bindings.
This wont work:
var $el = $compile...
vat html = $el.prop('outerHTML')
someElement.html(html);
This will:
var $el = $compile...
someElement.append($el);
P.S. I see you are fan of Jquery, but better stop using it in Angular projects at all.

Function is not returning data back to my array

im having a problem with my function Mrequest,the problem is that data like id and year are not add to de array. I know is a problem with the function but i just cant solve it.
any idea of what could i change so my array result get the ID and the YEAR
function getContent() {
var result = [];
async.series([
getDb,
getInfos
]);
function getDb(done) {
//posta
var query = "SELECT title , launch_year FROM content WHERE content_genre_id=1 && content_type_id!=2 LIMIT 2;"
mysqlConnection.query(query, function(err, data) {
result = data;
async.each(result, getPelicula, done);
});
}
function Mrequest(pagina, callback){
request({
url: pagina,
method: "GET",
json: true,
}, callback);
}
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
var pagina = "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false"
setTimeout(function() {
Mrequest(pagina, function(error, res, body) {
if (error) {
console.log("error", error);
} else {
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
console.log(pelicula);
console.log("id",id);
console.log("year",year);
console.log("year",year_solo);
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
} else {
pelicula.id = -1;
pelicula.year_pagina = null;
}
}
}
});
}, result.indexOf(pelicula) * 3000);
donePelicula();
}
getContent();
}
it doesn't look like you are making the request because getContent is being called from within itself

How to access data from ajax call after the ajax call ends

I am making a ajax calls that returns me some data from the server. I work on string function on the data that come from ajax call. From my knowledge i can see the string operation begins before the ajax call gets over. Often giving me undefined error. Here is my ajax call
$.ajax({
type: "POST",
url: "/add_director",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
$('#addDirModal').modal('hide');
insertDirector(data);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
Here is my insertDirector function
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
});
}
}
Here when i work on substr() it throws the error Cannot read property 'val' of undefined. I can see this is because the substr() is executed before the ajax request is completed. how do i fix this ?
EDITED
Here is the response
{"msg":"1","director":{"dir_name":"Naveen","dir_pan":"AAAAA1111B","dir_din":"123456","dir_addr":"dsadasdasdasdsadasdas","dir_img":"1490852438.jpg","user_id":3,"updated_at":"2017-03-30 05:40:38","created_at":"2017-03-30 05:40:38","id":15}}
Its not clear why you use the $.each here (you can omit it and use data.director instead of value), but if it is possible that your data contain several 'director' objects and you want to iterate through all of them, then you should change the insertDirector code to skip the 'msg' key as it doesn't have dir_name, dir_plan, ... properties:
function insertDirector(data) {
console.log(data);
if (data.msg == "1") {
$.each(data, function (key, value) {
if (key == "director") { //or if (key != "msg")
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
var dir_r_name = (dir_name.length > 15 ? dir_name.substr(0, 15) : dir_name);
//if (dir_name.length > 15) {
// var dir_r_name = dir_name.substr(0, 15);
//}
//else {
// var dir_r_name = dir_name;
//}
}
});
}
}
also, note that dir_name.val().length is wrong as dir_name is a string (.val() is not required)
change
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
to
if (dir_name.length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
try this way :
function insertDirector(data) {
console.log(data);
if (data.msg == "1") {
var dir_name = data.director.dir_name;
var dir_pan = data.director.dir_pan;
var dir_din = data.director.dir_din;
var dir_addr = data.director.dir_addr;
var dir_id = data.director.id;
var dir_img = data.director.dir_img;
if (dir_name.length > 15) {
var dir_r_name = dir_name.substr(0, 15);
}
else {
var dir_r_name = dir_name;
}
}
}
After seeing the data you posted, it is easy to find issue.
Here, the issue is:
Your function:
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
});
}
}
Here, when you do $.each, every object inside data will be traversed. Now, your first value inside data is msg:1. This is not a object. As a result, on first iteration, key is 'msg' but value is '1'. Now this value can't have dir_name so undefined is returned. As a result dir_name.val() generates error.
Try it like this:
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
if(key==="director"){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
}
});
}
}

Javascript Code User Login Without Email Extension

I'm having a problem and don't know how the form will accept the username without email extension for example i can enter "pro" only in "pro#domain.com"
Here's my code:
function loginHI(menu){
$(".hopplerTextboxLogin").focusin(function(){
hopplerTextboxFocused($(this));
}).focusout(function(){
$(this).removeClass("hopplerTextboxBorderBlue").addClass("hopplerTextbox");
});
$("#loginForm input").keyup(function(e){
if(e.keyCode == 13){
$("#btnLogin").click();
}
});
$("#btnLogin, #btnLogin2").click(function(){
//variable for email
var get_email = $("#j_username").val();
var get_pass = $("#j_password").val();
//validation
if(get_email=="" && get_pass==""){
somethingIsWrongHere("divUsername_login","Required fields");
somethingIsWrongHere("divPassword_login","Required fields");
return false;
}
if(get_email=="" || !isValidEmailAddress(get_email)){
somethingIsWrongHere("divUsername_login","Invalid email address");
return false;
}
if(get_pass == ""){
somethingIsWrongHere("divPassword_login","Password is required");
return false;
}
var result_page = setProjectName + "/j_spring_security_check";
$("#loginForm_message").html("<div class=\"loading_message_login\">logging in...</div>").fadeIn();
$("#cboxContent").removeClass("cboxContentHeight").addClass("cboxContentHeightMessage");
$.ajax({
type: 'POST',
url: result_page,
data: $("#loginForm").serialize(),
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Ajax-call", "true");
},
success: function(data) {
if(data.result==1){
localStorage.shortlists = "";
var sl_array = [];
localStorage.userFullName = data.firstName+" "+data.lastName;
var user_url = "HICollection3/select?q=id%3A"+data.userId+"&wt=json&indent=true";
var sl_url = "ShortList_Collection/select?q=removed%3Afalse+AND+user_id%3A"+data.userId+"&rows=1000&wt=json&indent=true&json.wrf=?";
$.get("properties/querySolr",{url : sl_url},function(result) {
solr_results = result;
var obj = $.parseJSON(solr_results);
console.log("obj.numFound" + obj.numFound);
var sl = obj.docs;
$.each(sl,function(index){
sl_array.push(sl[index].property_id);
});
localStorage.shortlists = sl_array;
/*EMBEDDED HIDDENLIST FXN*/
var hl_array = [];
var hl_url = "HiddenList_Collection/select?q=user_id%3A"+data.userId+"&rows=1000&wt=json&indent=true&json.wrf=?";
$.get("properties/querySolr",{url : hl_url},function(result2) {
solr_results2 = result2;
var obj2 = $.parseJSON(solr_results2);
console.log("obj2.numFound" + obj2.numFound);
var hl = obj2.docs;
$.each(hl,function(index){
hl_array.push(hl[index].property_id);
});
localStorage.hiddenlists = hl_array;
$.get("properties/querySolr",{url : user_url},function(result3) {
var solr_results3 = result3;
var obj3 = $.parseJSON(solr_results3);
console.log("obj3.numFound" + obj3.numFound);
var user_res = obj3.docs;
localStorage.userContact="";
localStorage.userFullName="";
localStorage.userEmail="";
$.each(user_res,function(index){
localStorage.userFullName = user_res[index].firstName+" "+user_res[index].lastName;
localStorage.userEmail = user_res[index].email;
if(user_res[index].mobile!=undefined || user_res[index].mobile!="")
localStorage.userContact = user_res[index].mobile;
else if(user_res[index].telephone!=undefined || user_res[index].telephone!="")
localStorage.userContact = user_res[index].telephone;
else
localStorage.userContact = "";
});
setTimeout(function(){
location.reload();
},1000);
});
});
});
}
else{
somethingIsWrongHere("",data.result);
}
}
});
return false;
});
$("#keepMeLoggedIn").click(function(){
$("#rememberMe").trigger("click");
});
}
the user log-in should accept also the the whole email address.
This is the code for isValidEmailAddress function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
Once again... the function test you will use will depend on what characters you would like to allow. If you want to only allow letters and numbers you could use...
function isValidUsername(username) {
var pattern = new RegExp(/^[a-zA-Z0-9]+$/);
return pattern.test(username);
}
and if you wanted to allow periods and # symbols so that you could have emails used as the username as optional...
function isValidUserName(username) {
var pattern = new RegExp(/^[a-zA-Z0-9\.\#]+$/);
return pattern.test(username);
}
Note that the user could use any combination of letters numbers and # symbols and periods if you use the second function. So, they could enter ###... or ddd#example.com or adfsadf8347

Categories