JavaScript isset() equivalent
I generally use the typeof
operator:
if (typeof obj.foo !== 'undefined') {
// your code here
}
It will return "undefined"
either if the property doesn't exist or its value is undefined
.
(See also: Difference between undefined
and not being defined.)
There are other ways to figure out if a property exists on an object, like the hasOwnProperty
method:
if (obj.hasOwnProperty('foo')) {
// your code here
}
And the in
operator:
if ('foo' in obj) {
// your code here
}
The difference between the last two is that the hasOwnProperty
method will check if the property exist physically on the object (the property is not inherited).
The in
operator will check on all the properties reachable up in the prototype chain, e.g.:
var obj = { foo: 'bar'};
obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true
As you can see, hasOwnProperty
returns false
and the in
operator returns true
when checking the toString
method, this method is defined up in the prototype chain, because obj
inherits form Object.prototype
.
php isset() equivalent in javascript
ECMAScript defines the hasOwnProperty
method for checking if an object has a property of a given name:
var foo = {'bar':'bar'}
alert( foo.hasOwnProperty( 'bar' ) ); //true
alert( foo.hasOwnProperty( 'baz' ) ); //false
EDIT: This doesn't fully answer your question
It's possible for a property to be set as undefined
foo.bar = undefined;
alert( foo.hasOwnProperty( 'bar' ) ); //still true
The important question is: What do you need your truth table to be?
In php:
type | isset() | == true
------+---------+----------
null | false | false
false | true | false
true | true | true
"" | true | false
"a" | true | true
0 | true | false
1 | true | true
In JS:
type | isset() | truthy
----------+---------+--------
NaN | ? | false
undefined | ? | false
null | false | false
true | true | true
false | true | false
"" | true | false
"a" | true | true
0 | true | false
1 | true | true
JavaScript isset() function
When javascript variables are not declared and you try to call them, they return undefined
, so you can do:
if (typeof sessionvalue == "undefined" || sessionvalue == null)
PHP if (isset) JavaScript equivalent
Just remove the empty()
function, as that is invalid JS. With that said, here is you adjusted code:
$.ajax({
type: 'get',
url: url,
success: function (data) {
if (data[0] != null) {
console.log('has data');
} else {
console.log('does not have data');
}
}
});
is there something like isset of php in javascript/jQuery?
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
What is the equivalent of isset($_POST['name']) in javascript?
First don't forget that you need name attributes on your checkboxes for PHP. Second, although your ids are valid in HTML5, I'd change them to start with a letter to make them HTML4 compatible.
I print the POST variable using php and assign it to post
in javascript. Then I check if the checkbox exists in the post variable.
page1.php:
<form method="POST" action="page2.php">
<input type="checkbox" id="1" name="box1">
<input type="checkbox" id="2" name="box2">
<input type="checkbox" id="3" name="box3">
<input type="checkbox" id="4" name="box4">
<input type="checkbox" id="5" name="box5">
<input type="checkbox" id="6" name="box6">
<input type="submit">
</form>
page2.php:
<form method="POST" action="action.php">
<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
<input type="checkbox" id="4">
<input type="checkbox" id="5">
<input type="checkbox" id="6">
<input type="submit">
</form>
<script>
var post = <?php echo json_encode($_POST) ?>;
if (!post.box2) document.getElementById("4").disabled = true;
</script>
isset equivalent in javascript to find palindrome
First, thank you for all the comments.
Second, I ran a var_dump on the count array in the PHP file and this was the result:
array (size=2)
'm' => int 2
'o' => int 1
Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.
One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:
var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";
var mForN = function(obj, strArr) {
for (var y = 0; y < strArr.length; y++) {
// console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
if (isset(obj[strArr[y]])) {
obj[strArr[y]]++;
} else {
obj[strArr[y]] = 1;
}
}
return obj;
};
var mForN_2 = function(obj, objKeys) {
for (var z = 0; z < objKeys.length; z++) {
/* console.log(
"obj[objKeys[z]]: " +
obj[objKeys[z]] +
" obj[objKeys[z]] % 2: " +
eval(obj[objKeys[z]] % 2)
); */
if (eval(obj[objKeys[z]] % 2) == 1) {
oddCounter++;
}
// console.log("oddCounter: " + oddCounter);
}
return oddCounter <= 1;
};
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
var isPalindrom = function(str) {
// reverse original string
splitString = str.split("");
reverseArray = splitString.reverse();
joinArray = reverseArray.join("");
var checking = checkSpellingOfStr(str);
if (str == joinArray) {
strArr = str.split("");
// console.log("strArr: " + strArr);
objKeys = makeObjKeys(count, strArr);
// console.log("filled count before mForN: " + JSON.stringify(count));
// create array of keys in the count object
objKeys = Object.keys(count);
// console.log("objKeys: " + objKeys);
count = mForN(count, strArr);
// console.log("count after mForN: " + JSON.stringify(count));
return mForN_2(count, objKeys);
} else {
return 0;
}
};
var makeObjKeys = function(obj, arr) {
for (var x = 0; x < arr.length; x++) {
obj[arr[x]] = null;
}
return obj;
};
var checkSpellingOfStr = function(someStr) {
var formData = {
someWord: someStr
};
$.ajax({
type: "GET",
url: url,
data: formData,
success: function(result) {
if (!$.trim(result)) {
} else {
console.log(result);
$("#checkSpelling").html(result);
}
}
});
};
Start everything with the following call:
isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
In my example, I have a form and I listen for a button click as follows:
var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});
The following is the php for spell check:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!empty($_REQUEST['someWord']))
{
$someWord = $_REQUEST['someWord'];
}
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, $someWord)) {
echo trim($someWord) . " is a recognized word in the English language";
} else {
echo "Your word is either misspelled or that is not a recognized word";
}
You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini
This is what I did, to get it running locally on my mac:
cd /Users/username/Downloads/php-5.6.2/ext/pspell
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
make
cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
sudo apachectl restart
check your phpinfo file and you should see the following:
pspell
PSpell Support enabled
Live example
How to check if isset is not set?
It'd fine to use !isset
, no issue, but else ifif
is completly wrong in your code
Approach will be:-
if(isset($_REQUEST['search'])){ // check that variable is set and have some value or not
// variable is set and have value
}else {
// variable is either not set or not have value
}
if isset statement with javascript?
document.getElementById("element")
will return null
if the element doesn't exist -- and something not-null
if it exists.
Which means you should be able to do something like this :
var areaOption = document.getElementById("element");
if (areaOption) {
// element exists
} else {
// element doesn't exist
}
(You could also compare areaOption
with null
, instead of just checking if it's non-falsy)
Related Topics
Proper Use of Const for Defining Functions
How to Remove the Decimal Part from JavaScript Number
Semicolon Before Self-Invoking Function
Detect iPad Users Using Jquery
How to Add Predefined Length to Audio Recorded from Mediarecorder in Chrome
Handle Url Fragment Identifier (Anchor) Change Event in JavaScript
What Is "Callback Hell" and How and Why Does Rx Solve It
Scriptmanager.Registerstartupscript Code Not Working - Why
Node.Js Shell Command Execution
How to Clone a JavaScript Object Except for One Key
Select All Contents of Textbox When It Receives Focus (Vanilla Js or Jquery)
What Is Difference Between Axios and Fetch
What Does $.When.Apply($, Somearray) Do
Arrow Function in Object Literal
Setting Multiple Attributes for an Element at Once with JavaScript