I'm facing a problem with a jquery script. Can't enter on an if statement.
Can someone explain me why I cant enter on if (partner_type_id === 1) even if the value is 1?
$(document).ready(function(){
$('#holder_0_partner_nr').change(function(){
var partner_type_id = $("#holder_0_partner_type_id").val();
var partner_nr = $("#holder_0_partner_nr").val();
console.log(partner_type_id);
console.log(partner_nr);
if (partner_type_id === 1)
{
$.ajax({
url: '{{ route('sgc.contracts.create.get.occ.person.data') }}',
type: 'get',
data: { partner_nr: partner_nr },
success: function(response) {
if (response !== false)
{
let data = JSON.parse(response);
$("#holder_0_name").val(function() {
return data.name;
});
}
}
});
}
});
});
are you sure it is a number? try parseInt(partner_type_id) === 1 OR partner_type_id === '1'?
.val() can return a number, string or array
In this case:
if (partner_type_id === 1) with triple ===(strict check), will only be true if both the value and type is equal.
Since you're comparing to a number you must make sure partner_type_id is also a number and not a string containing "1".
Either parse your variable correctly or use double ==
Related
$(document).ready(function() {
$("form").submit(function(e) {
if (!checkStockOfProduct())
{
e.preventDefault();
return false;
}
return true
});
});
<script src="~/Scripts/storeinputoutput.js"></script>
storeinputoutput.js file:
function checkStockOfProduct() {
var allowSubmitForm = true;
$("table#StoreItemdatatable > tbody > tr").each(function () {
.
.
.
var storeId = $('#StoreID').val();
var stock = null;
var URL = '/aaa/bbb'
$.ajax({
async: false,
url: URL,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: {
productNServiceID: productNServiceID,
storeID: storeId
},
type: 'POST',
success: function (data) {
stock = data.Stock;
}
, error: function (jqXHR, exception) {
}
});
if (...) {
allowSubmitForm = false;
}
return allowSubmitForm;
});
}
In form submit , I called the function and I wouldn't do the submit operation if function return false.
But the value of the xx variable is always undefined.
Please advise
Checked using Alert. variable "allowSubmitForm" in function "checkStockOfProduct" in the last line has value and not "undefined"
But in Submit it is undefined
I understand you want to return boolean, so use true and false rather than 'true' and 'false'
Why? The ones without quotes are boolean while the ones with quotes are string. A non-empty string in javascript would always return true while an empty string would return false (youare returnimg non-empty strings there and the result is obviously not what you would want in this case).
var is a little tricky and I would suggest we use let next time. Since it doesnt seem as though you are doing a lot in the checkStockOfProduct function I would refactor it to ==>
const checkSumOfProduct = (whatever...) ? false : true
I noticed the update on your question, I really don't get what you are trying to do there but to me it looks as though the result of the checkStockOfProduct decides whether you would prevent default form submission on submit and return false or not.
I would also be assuming that the CheckSumOfProduct function is synchronous
Let's refactor that code to do the same thing you were trying to do but look something like this ==>
$(document).ready(function() {
$("form").submit(function(e) {
if(!CheckStockOfProduct()){
e.preventDefault()
return false
}
return true
});
});
Let me know if this works out...I am in transit and on mobile atm
Try
function checkStockOfProduct() {
var allowSubmitForm = true;
if (...) {
allowSubmitForm = false;
}
return allowSubmitForm;
};
And adjust your submit() event handler based on the function return value:
$(document).ready(function () {
$("form").submit(function (e) {
if (checkStockOfProduct()) {
//valid
return;
}
//invalid
e.preventDefault();
});
});
I have javascript, including an ajax call, that takes an empty form input and uses what the user types to query for a json object. It successfully returns matching objects and displays them in a datalist.
This all works fine, but now I'm trying to make sure that when they click a list option, I get certain fields from ONLY that selected option so I can eventually post them to a form.
When an option is clicked I'm getting the value I want in my console (console.log(searchResult[i]._source.frm.grp.Name)) but it gives me every one from the previous objects, where I just want the data from the one clicked.
I think this could have to do with the fact that I'm doing that function in the for loop or it my have something to do with my indexing using [i] but I can't pinpoint it.
How can I get this to only affect the values of the indexed object that is clicked?
<script type="text/javascript">
//input event handler
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function(response){
$('#returnedProducts').empty();
let searchResult = response.hits.hits;
for(let i = 0; i < searchResult.length; i++) {
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
//Issue starts here//
$("#productInput").on('input', function(){
var val = this.val = this.value;
if($('#returnedProducts option').filter(function(){
return this.value === val;
}).length){
document.getElementById("grpName").value = searchResult[i]._source.frm.grp.grp_name;
document.getElementById("grpNum").value = searchResult[i]._source.frm.grp.grp_code;
}
})
}
}
});
}
});
</script>
<form>
<input id="grpName">
<input id="grpNum">
</form>
I'm not sure about this but here is what I understand:
all your code here is already wrapped in a listener on 'input' event, there shouldn't be any need to add another listener, especially to work on the same property (.val() or .value seem to refer to the same thing, right?)
you have 3 cases: one when #productInput is empty, one when it's a partial match (suggestions), and you're adding one when it's a perfect match
to "export" this code to that upper level, you're going to need a higher access to what you currently have as searchResult (not the const one, the let one)
for the same purpose you're going to have a way of linking an <option> with an element in your searchResult (like adding an arbitrary param srindex containing the index of the element in searchResult)
Eventually, your top if block should look like:
let _this = $(this);
let foundOption;
if (_this.val() === '') {
return;
} else if (foundOption = $('#returnedProducts option').find((option) => {
return option.srindex === _this.val();
})) {
console.log(searchResult[foundOption.srindex].blahblah);
} else {
$.ajax(...);
}
A note:
using .find() is generally faster and can't be slower than .filter(), since the former stops on the first matching element, whereas the latter walks the whole array anyway (since it returns all matching elements, and here you have zero or one to be found) spoiler post-update: we're not talking about Array.prototype.find, we're about jQuery.find, but shhh, I don't know it yet!
I'm not sure option.srindex works as-is, maybe it's something like option.getAttribute('srindex') spoiler post-update: it doesn't work as-is
UPDATE (solution after a long chat and many tries)
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let searchResult = [];
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
$("#grpName").val(searchResult[$(foundOption).attr('srindex')]._source.frm.grp.grp_name);
$("#grpNum").val(searchResult[$(foundOption).attr('srindex')]._source.frm.grp.grp_code);
} else {
$.ajax({ url: '/account/autocomplete',
data: {
search_result: _this.val()
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
$("#returnedProducts").empty();
for(let i = 0; i < response.hits.hits.length; i++) {
$("#returnedProducts").append(
`<option srindex="${i}" value="${searchResult[i].cat}" />"`
);
}
});
});
}
});
I want to create this function:
If ID is 10 digits it should make ajax call to file number 1
If ID is 18 digits it should make ajax call to another file
Here is the code:
function get_invoice_info(expressid,expressno,div_id)
{
document.getElementById("retData")
.innerHTML="<center>Please wait fetching tracking details for you...</center>";
var expressno = '{$order.invoice_no}';
var matches = expressno.match(/^\d{12}$/);
Ajax.call('plugins/track/tracking.php?CN='+ expressno,
'showtest=showtest',
function(data){
document.getElementById("retData").innerHTML=data;
},
'GET',
'TEXT'
);
} else {
Ajax.call('plugins/track/tracking.php?CN='+ expressno,
'showtest=showtest',
function(data) {
document.getElementById("retData").innerHTML=data;
},
'GET',
'TEXT'
);
}
This code is working exactly as i wanted it to be
function get_invoice_info(expressid,expressno,div_id)
{
var waitMsg = "Please wait fetching tracking details for you...";
document.getElementById("retData").innerHTML= waitMsg;
var expressno = '{$order.invoice_no}';
if(expressno.length === 12) {
filePath='tracking';
} else if(expressno.length === 18) {
filePath='track';
} else {
//Not in range, so exit
return;
}
Ajax.call('plugins/track/'+filePath+'.php?CN='+ expressno, 'showtest=showtest', function(data){document.getElementById("retData").innerHTML=data;}, 'GET', 'TEXT');
}
Am I missing something, seems like you can just check length (or does it need to only be numeric, in which case you can add another if statement to the beginning that checks for non numeric characters).
function get_invoice_info(expressid,expressno,div_id) {
var waitMsg = "Please wait fetching tracking details for you...";
var expressno = '{$order.invoice_no}';
var filePath = null;
document.getElementById("retData").innerHTML= waitMsg;
if(expressno.length === 10) {
filePath='file1';
} else if(expressno.length === 16) {
filePath='file2';
} else {
//Not in range, so exit
return;
}
var onSuccess = function(data){
document.getElementById("retData").innerHTML=data;
};
Ajax.call('plugins/track/'+filePath+'.php?CN='+ expressno,
'showtest=showtest',
onSuccess,
'GET',
'TEXT'
);
I have problem with recognizing variable and defining if statement dont know why. So...
$.ajax({
type: "POST",
url: "check.php",
success: function(response){
alarmvar = response;
if(alarmvar !== 0){
alert(alarmvar+"aaaaag");
}
}
});
and in check.php file:
$rowsw = mysql_num_rows($query);
echo "".$rowsw."";
variable is always defined not like 0 even if mysql_num_rows returns 0
alert is always shown and alarmvar variable causes next line in alert box.
Where is the problem?
The problem is you check if alarmvar is 0 value and number type. The operator !== check value and type. When mysql_num_rows is 0, you are checking "0" !== 0, and return true because the type is different. Alternatives:
if(alarmvar !== "0"){
alert(alarmvar+"aaaaag");
}
Or (Not recomended)
if(alarmvar != 0){
alert(alarmvar+"aaaaag");
}
And I recomended you use var to declare alarmvar, if not, alarmvar is in global scope.
var alarmvar = response;
I'm doing an ajax call that returns JSON, which includes 3 location zip codes.
These zip codes are:
value2.loc1_zip
value2.loc2_zip
value2.loc3_zip
Then, a "search" form returns a list of zip codes within a search radius. These are:
zipback.zip_codes
and each zipcode is here:
zipback.zip_codes.zip_code
I cannot figure out how to check if value2.loc1_zip, value2.loc2_zip, or value2.loc3_zip are in the list of zipback.zip_codes
I've tried this, but it has not worked:
var grabbed_zips = zipback.zip_codes;
if (grabbed_zips.hasOwnProperty(value2.loc2_zip)) {
...stuff...
}
Here's the raw JSON:
{"counselor_posts":[{"id":"1","firstName":"John","lastName":"Doe","loc1_zip":"30309"},{"id":"3","firstName":"Jeff","lastName":"Kim","loc1_zip":"30315"}]}
{"zip_codes":[{"zip_code":"30324","distance":4.484},{"zip_code":"30376","distance":4.298}]}
Here's the actual jquery I'm using:
$.ajax({
type: "GET",
url: '...url..here...',
dataType: "json",
success: function(zipback) {
var grabbed_zips = zipback.zip_codes;
$.getJSON('/scripts/get_counselor.php', function(data2) {
$.each(data2.counselor_posts, function(name2,value2) {
if (grabbed_zips.hasOwnProperty(value2.loc3_zip)) {
$(".counselor-search-results").append(cat_html2);
}
});
});
}
});
Are you using $.parseJSON to instantiate a JSON Object?
$.parseJSON
This will help yo manage the object. And if the object is a list, then:
var JSONZips = $.parseJSON('{"zips" : {"user1zip":94140, "user2zip": 94107}}');
JSONZips.zips.hasOwnProperty('user1zip');
This would return true.
If you need to find a specific value, then:
function checkForValue(json, value) {
for (key in json) {
if (typeof (json[key]) === "object") {
return checkForValue(json[key], value);
} else if (json[key] === value) {
return true;
}
}
return false;
}
Hope this helps!
I would extract the zip codes contained in the result of the form with a map function, then test if some of the zip codes you have is contained in it.
For example:
var zip1 = "30321", zip2 = "00000", zip3 = "01010"; //zip codes you want to test
var grabbed_zips = {"zip_codes":[{"zip_code":"30324","distance":4.484},{"zip_code":"30376","distance":4.298}]}; //search result
//flattened array containing the zip codes in the search result
var zipCodes = grabbed_zips.zip_codes.map(function(zip){ return zip.zip_code; });
//The test you are looking for, either true or false
var someMatch = [zip1, zip2, zip3].some(function(curZip){ return zipCodes.indexOf(curZip) != -1; });
Two arrays are used: one containing the zip codes you have, the other derived from the zip codes in the result of the form.
The some method tests if one of the zip codes in the first array is equal (index!= -1) in the second one.