javascript if("" != "") not working - javascript

HTML & PHP
<?for($i=1;$i<=10;$i++){?>
<input type='textbox' style="width:100%" name='name[]' id = 'name<?echo $i;?>'>
<?}?>
Javascript
for(var i=1;i<="?";i++){
if(document.getElementById('name'+i).value != "") {
alert("text_if");
}else{
alert("text_else");
}
}
In the textbox don't have value (mean "") so "" != ""
return false alert text_if but it's not working don't alert all.
i try "" == "" it's working why != not working please help me
Okay it's working now
but i have loop but i don't know max of element
because i have function add&del textbox (create element)

It works:
http://jsfiddle.net/uyz6fozt/
I just needed to add a closing bracket }.
Change
<input type='textbox' style="width:100%" name='name[]' id = 'name' value="ENTERSOMETHINGHEREORREMOVEIT">
to
<input type='textbox' style="width:100%" name='name[]' id = 'name' value="">
and press RUN to see it working.

It's false because the empty strings are equal.
"" != "" translates to "an empty string is not equal to an empty string" which is false because they are indeed equal.
if(document.getElementById('name').value != "") {
alert("text_if");
}else{
alert("text_else");
}
<input type='textbox' style="width:100%" name='name[]' id = 'name'>
Notice how the else statement runs here. If it is not running for you, it means you may have placed your javascript in a location where it runs before the DOM is loaded.

Also make sure you are calling this after the element has loaded - so ensure you wrap it in a function that is only called after the page has fully loaded - or alternatively have the script after the closing body tag (page runs more efficiently this way)
JavaScript can only call elements with IDs that exist in the DOM :)

Related

Set Default Value for hidden field

I have a hidden field where i save a value when button is clicked. But on page load there is no value assigned to it. I need to know how to set default value of hidden field.
I am saving a string in hidden field when button is clicked and then access it in a JS function. But on page load the JS function return Undefined value error as the value of hidden field is not set on page load.
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom != "")
{
// logic here
}
}
You can simply try with this
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom) {
// logic here
}
}
So if(nom) will return true only when it has non-blank value. It'll return false if it is "" or undefined
Now the next thing, you need to make sure about the Id of the element. If you are using the asp.net hidden field with runat="server" then Id would be different than what are you expecting. So to make sure that Id remains same as you've given in asp.net markup, use ClientIdMode="Static"
you can also do this:
if (nom != "" || nom != undefined) {
//Your Logic
}
try to use this
if (nom !== "" && nom !== undefined)
so, your code should be rewritten as below
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom !== "" && nom !== undefined)
{
// logic here
}
}
Here for only text,password fields in html only you can give a default value attribute .But in the case of html
<input type="hidden" value="">
element the value would not be assigned by default.
If you want to use a hidden field with a default value use a text field with the property of display:none like
<input type="text" style="display:none" value="Default">
Or else if you are determined to use the hidden element only then you can go for a javascript based check solution like
var nom = document.getElementById('hdNomValue').Value;
if (nom != "" || nom != undefined)
{
}
what are you using jquery or javascript, if u are using jquery you may try to use
var nom = $('#hdNomValue').val();

What is the value of an empty text input box?

I am trying to implement a search box. The following is the code (both HTML and JS)
HTML
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
JS
var Search = function() {
/* code to implement the table content loading part */
//The following is what I have to filter out the table contents based on input in the text field
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i])
}
//Call function to load table
}
What is happening is that, if I enter some string into the input text field, the search algorithm works fine and only the relevant items are displayed. However, if I clear the contents of the search box and click on Search button, nothing is displayed in the table. That is, when the text field is cleared and clicked on the search button, it is as if ItemsToDisplay is empty and the if condition fails.
Can someone explain why this is the case? And how I can solve this?
Before your indexOf($searchVar) you should check that searchVar is != ''. Otherwise no item will be displayed afterward. A suggestion, javascript has a really great console.log functionality that will help you a lot when it comes to if branches
If you cleared input, the value of $scope.searchVar willbe undefined and your condition
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
will be false, so you didn't push into ItemsToDisplay and nothing append.
I suggest you to write an else statement :
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
else {
ItemsToDisplay.push(tableContent[i]);
}
U can try with,
if (($scope.searchVar) != undefined)
or
if (typeof ($scope.searchVar) != 'undefined')
when you do not enter anything in INPUT box then its value become UNDEFINED.
you will have to check in if() condition, if input is undefined then write your logic, if input has some value then write your logic.
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
var Search = function()
{
if ( $scope.searchVar == undefined){
//Do something, input box is undefined
}
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i]);
}
}

Include IF statement in Javascript

I have written the script below with some help. I am now trying to combine with an IF Statement. Here is what I am trying to accomplish, if %%GLOBAL_Availability%%is empty, then do not display the button. Else, display the button and run the script.
I did some research and came up with the below:
if (%%GLOBAL_Availability%% ==""){
<div><input id="ShopButton" style="display: none";></div>
}
else {
<!--Amazon Shopping button-->
<div><input id="ShopButton" </div>
<script>
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
</script>
}
It did not work at all. I am VB.net, and just learning this hard way.
Any suggestions?
Thanks.
I'm assuming that your variable %%GLOBAL_AVAILABILITY%% is a string since you're testing that it's empty via testing that it's equal to a blank string.
In javascript I'd offer 2 tips for testing if a string exists or is empty.
1 - use the .length property of the String object.
2 - to check that it exists check that the type of %%GLOBAL_AVAILABILITY%% is a string use the identity operator === to check that the variable is of type string.
Your if statement should look like the below:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
//execute code
}
Secondly, javascript is made to manipulate the DOM, so there's no need to insert new HTML based on a condition, you can just manipulate the properties of the existing HTML - in this case, setting the display property of '#ShopButton' to none.This can be achieved like this:
document.getElementById('ShopButton').style.display = "none";
So, your code should look like this:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
document.getElementById('ShopButton').style.display = "none";
} else{
document.getElementById('ShopButton').style.display = ""; //MAKE VISIBLE
document.getQuerySelector('#ShopButton').addEventListener('click', function(){
document.location.href = '%%GLOBAL_AVAILABILITY%%';
});
}
It seems you want the input to be "display: none;" if the variable is empty, in which case you can just change the style attribute based on the variable. Something like:
<div><input id="ShopButton" style="display: none";></div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
This will simply render the element as invisible and then the script will make it visible if the variable isn't empty.
<div>
<input id="ShopButton" style="display: none";>
</div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
Is this what you're trying to do maybe?

How to get value of textbox on page load, if it is null? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
Want to check first that, Is text box contains nothing on page load ?
Then assign some value to it.
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
But getting error
"JavaScript runtime error: Unable to set property 'value' of undefined or null reference"
How to do this?
It is because your DOM is not ready so wait until load complete:
window.onload=function(){
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
};
You're probably trying to access the element before you defined in page, so you should execute that code on window.load event or move that code just before </body>
as alternative you may use the placeholder attribute supported on many modern browsers
<input type="text" id="txtBoxId" placeholder="Some text here" />
If the input has no value, the placeholder value will be shown instead
(polyfills of this behaviour are available for older browser)
You are trying to access the property 'value' on a null (or undefined) object, wich cause an exception, assuming your ID may not be txtBoxID
It is not safe to test null for the textbox value. You should use empty string instead.
I created a jsFiddle which shows this:
<input type="text" id="txtBx" />
document.getElementById("txtBx").value = null;
alert("test 1 textbox is null \n" + (document.getElementById("txtBx").value == null));
alert("test 2 textbox is empty string \n" + (document.getElementById("txtBx").value == ""));
http://jsfiddle.net/kZhHa/3/
(I'm using Chrome)
Are you doing your code above after the page is loaded?
window.onload = function() {
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
}
Note that window.onload isn't best way to check whether page is loaded. It depends on the browser's spec. See window.addEventListener or window.attachEvent or IE.
Please try the below code, you need to set the value to the null first in the line
Name: <input type="text" id="myText" value=''>
Here is the demo :
function func() {
if (document.getElementById("myText").value == '') {
document.getElementById("myText").value = "Some text here";
} else {
alert("not null");
}
}
Name: <input type="text" id="myText" value="">
<p>Click the button to change the value of the text field.</p>
<input type="button" id="button" value="Click Me" onClick="func();" />
If you have JQuery available here is another way of accomplishing what you are asking for. In the document.ready function you can get the value of your text using the id of your textbox and wrapping it in JQuery. This will allow you to check and replace the value of your text box in the case that it is empty by using the .val() function
$(document).ready(function () {
if($('#id-of-your-textbox').val() == ' ')
{
$('#id-of-your-textbox').val('some text');
}
});

Correct syntax for IF statement

Can anyone tell me why this IF statement doesn't work, please? I'm using jQuery and Firebug but the latter is not giving me any useful information.
I'm simply attempting to reveal a "submit" button when all of the fields have been completed and the script runs every couple of seconds to check for input.
My code excerpt goes a little like this:
function checkForm(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
// The following line shows me that the values for the fields are all getting picked up properly
$('#report').html("userName: "+userName+"<br />userContent: "+userContent+"<br />userEmail: "+userEmail);
// But the following line is throwing some kind of error
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideDown();
} else {
$('#update').slideUp();
}
}
$(document).ready(function(){
$('#update').hide();
setInterval('checkForm()' , 2000);
});
And my HTML...
<div id="report"></div>
<form id="submitfact">
<div id="update">Update Database</div>
<label><input id="name" name="name" type="text" value="" /><span>Fact submitter's name</span></label>
<label><input id="email" name="email" type="text" value="" /><span>Fact submitter e-mail address</span></label>
<label class="content"><span>Fact text</span><br /><textarea id="content" name="content"></textarea></label>
</form>
Edit...
I apologise if people think I'm wasting their time by not providing the error message - but Firebug simply isn't giving me anything useful - if it was I'd be posting it here. I am a reasonably experienced php programmer but fairly new to jQuery so I admit I am still getting to grips with both writing the language and debugging it. I'd like to post a screen shot of Firebug's response but, as a new user, I am not allowed... all I am getting is a "red error circle/yellow play triangle" icon in the line numbers column ("script" tab) on the line I've shown above... there is nothing else unless you can tell me where else to look other than the "script" and "console" panels?
Another edit...
Well, I got it fixed by taking a look at Cristoph's suggestion. It's basically the same solution but instead of calling it as a function I put it "inline". I'm not entirely sure what the difference between the two techniques is or whether it's simply a local issue I was having but my new jQuery looks like this:
$(document).ready(function(){
$('#submitfact').keyup(function(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
$('#report').html(userName + "<br />" + userContent + "<br />" + userEmail);
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideUp();
} else {
$('#update').slideDown();
}
});
});
I will have a look through your other comments to see if I can streamline it at all but at least I have a working baseline now! Thanks for your time, everyone :)
First of all, is it really throwing an error, or is it simply not working?
From how i understand your code, your if condition should be:
if (!userName === "" && !userContent === "" && !userEmail === ""){
// show
$('#update').slideDown();
} else {
// hide
$('#update').slideUp();
}
Second: doing this with a timer is a bad idea.
Introducing an eventhandler to check once an inputvalue changed is far better:
$("input").change(function(){
// if all inputs are filled, show Button, else hide it
});
P.S.
advanced insight into Javascript: an empty string is considered "falsy", thus
username === "" could be written as !username. Note however, that undefined, null, false, 0 and NaNare also considered "falsy"! THis means, you can't distinguish them. For this reason i prefer username === "" ( note the === ! )
Try changing your evaluation to this:
if (!userName || !userContent || !userEmail){
$('#update').slideDown();
} else {
$('#update').slideUp();
}

Categories

Resources