Syntax Error in Basic Javascript Function - javascript

I keep getting errors when debugging in IE.
This is a basic hide function.
idHide is the id of the field to be hidden
idCondition is the id of the reference field the condition is compared upon
value is the value that would satisfy the condition
function hideOnCondition(idHide, idCondition, value)
{
if (document.getElementById[idCondition] = value)
{
document.getElementById(idHide).style.display = "none";
}
else
{
document.getElementById(idHide).style.display = "";
}
}
I always encounter the error in:
if (document.getElementById[idCondition] = value)
"the value of the property is null or undefined not a function object"
Then I tried changing "getElementById" with "all". then changed the brackets to parentheses, still nothing, only for the line to be highlighted in yellow.
Im sorry, I'm just stumped. Again, thank you all for understanding.

You were using square brackets instead of parentheses
=== should be used for comparing not =
.
function hideOnCondition(idHide, idCondition, value)
{
if (document.getElementById(idCondition) === value) // <- fix here
{
document.getElementById(idHide).style.display = "none";
}
else
{
document.getElementById(idHide).style.display = "";
}
}

function myFunction(option, value, div) {
//get the element you want to hide by it's ID
var x = document.getElementById(div);
//if the option you selected is coresponding to the given value
//hide the earlier selected element
if (option === value) {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
This should do it.

Instead of an assignment you should use the comparison operator Identity / strict equality (===):
function hideOnCondition(idHide, idCondition, value) {
const result = document.getElementById[idCondition] === value ? 'none' : '';
document.getElementById(idHide).style.display = result;
}

Two issues I could see
using = instead of === and not comparing value instead only comparing the the output of document.getElementById[idCondition] with value.
using [] instead of invoking the function using ()
Although, none of these would cause the syntax error as you have claimed in your post.
You can simplify it as
var getEl = (id) => document.getElementById(id);
function hideOnCondition(idHide, idCondition, value)
{
getEl(idHide).style.display = getEl(idCondition).value == value ? "none" : "";
}

Related

If statement not executing correct code?

So I am trying to develop a Tic Tac Toe game for practice with javascript but I've hit a roadblock. I have an if statement that should be returning true but it isn't. Here is a sample.
var game = true;
var x = 'X';
var o = 'O';
var blank = '';
var turn = x;
var board = [blank, blank, blank,
blank, blank, blank,
blank, blank, blank];
function write() {
$('td').click(function() {
//Making sure that the block that was clicked can only be clicked once
var id = $(event.target).attr('id');
var digit = parseInt(id.slice(-1));
//check to see of the block has been clicked on
if (board[digit] = blank) {
board[digit] = turn;
$(board[digit]).html(turn.toUpperCase());
if (turn = x) {
turn = o;
} else if (turn = o) {
turn = x;
}
} else {
alert("That box has already been clicked on!")
}
});
}
You have two issues at first glance.
First, event is undefined. Define it as a function parameter in your .click call.
$('td').click(function(event) { /* rest of the code */ }
Second, as Pointy commented, = is for assignment, == and === are meant for comparisons.
Thus
if (board[digit] = blank) { /**/ }
needs to be
if (board[digit] === blank) { /**/ }
Regarding the difference between == and === you can get more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Short version, prefer === unless you're absolutely sure you know what you're doing and want to explicitly use ==.
if (board[digit] === blank) {
^^

If statement returns false when it should be true

I have a javascript function to get a property from a style attribute.
I am then checking if the attribute is equal to a specific point.
However, when I console.log() the value of the attribute, it is as expected but when I test the attribute value, it returns as false?
here is my code and screenshots:
var $paywhirlWidget = $(".payment-signup-section .container .row .col-xs-12:first-child iframe#paywhirl_frame"),
$widgetRow = $(".payment-signup-section .container .row .col-xs-12:first-child");
$.fn.inlineStyle = function (prop) {
var styles = this.attr("style"),
value;
styles && styles.split(";").forEach(function (e) {
var style = e.split(":");
if ($.trim(style[0]) === prop) {
value = style[1];
}
});
return value;
};
function checkForChanges() {
if ($(window).width() < 998) {
console.log(Boolean($paywhirlWidget.inlineStyle("height").toLowerCase() == "620px"));
console.log($paywhirlWidget.inlineStyle("height").toLowerCase());
if ($paywhirlWidget.inlineStyle("height").toLowerCase() == "620px") {
console.log("im here!!");
$widgetRow.css("display", "none");
}
} else {
if ($paywhirlWidget.inlineStyle("height") == "300px") {
console.warn("im here too!!");
$widgetRow.css("display", "none");
}
}
}
setInterval(checkForChanges, 500);
As an example, here is the "620px" test, as you can see, the first console.log() returns false, even though the second one shows the value as being exactly what I am testing for!
This is really confusing as I cannot understand why a value that is clearly true is returned as false when Boolean tested.
It looks like your style attribute has a space at the start of the value. Try using trim:
$.trim( $paywhirlWidget.inlineStyle("height").toLowerCase() ) === "620px"
Or update your inlineStyle plugin so that it does the trimming:
value = $.trim( style[1] );
Simpler to just use jQuery height() which returns number representing pixels
if ($paywhirlWidget.height() == 620)

AngularJS setting up a function to prevent duplication

At the moment I have duplicate code where I have the following examples:
if ($scope.user.window.title == 'true'){
if (this.title){
title = '<h2>'+this.title+'<h2>';
} else {
title = '';
}
} else {
title = '';
}
if ($scope.user.window.football == 'true'){
if (this.football){
football = '<p>'+this.football+'<p>';
} else {
football = '';
}
} else {
football = '';
}
I have tried the following but it doesn't work, it says that the $scope.user.window.football and $scope.user.window.title don't exist. I think it is down to the below function sending the value through as a string for my $scope.
function CheckWindow(element,tag) {
console.log(element);
if ($scope.user.window.element == 'true'){
if (this.element){
element = '<'+tag+'>'+this.element+'</'+tag+'>';
} else {
element = '';
}
} else {
element = '';
}
}
Usage
CheckWindow('title','h2')
CheckWindow('football','p')
$scope.user.window.element tries to access the property named element of $scope.user.window. You need $scope.user.window[element] instead.
this refers to the created function's scope. You could pass a new argument that for example.
that.element will have to be rewritten to that[element], for the same reason as in #1.
You can't assign a new value to a function's parameter (well, you can, but it won't be accessible outside the function's scope). Better return the value.
So:
function CheckWindow(that, element, tag) {
if ($scope.user.window[element] && that[element]){
return '<'+tag+'>'+that[element]+'</'+tag+'>';
}
return '';
}
title = CheckWindow(this, 'title', 'h2');
football = CheckWindow(this, 'football', 'p');
try
$scope.user.window[element]
When you need to reference a property as a sttring, you must use bracket notation.
Also, I doubt that 'this' will reference what you want. You may need to angular.bind this to the method.

searching inputs for duplicated values except this

I'm in a medium project and a issue occurs.
I have extracted the essence of the problem to this fiddle
What this code is
$(".6").focusout(function(){
if( $(".6").filter(function(){ return this.value;}).not(this).length>0)
{ $(this).val("duplicated");}
What this code should do is get this.value and search it in other inputs, if it productive, alert the user and prevents the blur. The setback is in searching by value (if()), it does'nt working.
UPDATE
I have made a change in fiddle above: now the event sets a new value to input instead alert() and focus()
I have noticed that filters by "have a value" and not "have the value".
The main issue is regarding the filter.
.filter(function(){ return this.value;})
The jQuery filter method will return all jQuery objects where the return value is true. In the above code, every input that has a value will result to true.
To fix this, first save the value of the current input being modified, and then compare it with each value of the elements:
$(".6").focusout(function (e) {
var val = this.value;
if( $(".6").filter(function(){ return this.value === val;}).not(this).length>0){
$(this).val("duplicated");
}
})
A few additional tips. If you use the not() method first, then you will reduce the number of filter queries by 1.
$(".6").focusout(function (e) {
var val = this.value;
if( $(".6").not(this).filter(function(){ return this.value === val;}).length>0){
$(this).val("duplicated");
}
})
Even better, you can use the siblings() selector instead to only select other elements.
$(".6").focusout(function (e) {
var val = this.value;
if ($(this).siblings(".6").filter(function () { return this.value == val; }).length > 0) {
$(this).val("duplicated");
}
})
In this particular case, you can omit >0 in the if statement
$(".6").focusout(function (e) {
var val = this.value;
if ($(this).siblings(".6").filter(function () { return this.value == val; }).length) {
$(this).val("duplicated");
}
})
see: http://jsfiddle.net/tleish/VM2fy/4/

Jquery Evolution from simple plain javascript

i have been using jquery for a while now but only thing i know about jquery is probably a dozen of functions that get my job done. but i want to understand how jquery evolved from simpl plain javascript i.e how
$("#xyz").val();
is converted to
document.getElementById('xyz').value;
i have searched for my answer on the web but most of the writers are happy to show how you can hook on to different DOM elements with jquery, selector details etc. but nothing can be found about how actually the transition was made. can anyone refer me to some tutorial where i can get my required material?
thanks
jQuery is not a compiler. jQuery does not get compiled into javascript.
.val is a method of an object. The jQuery object.
Specifically it is
function (value) {
if (!arguments.length) {
var elem = this[0];
if (elem) {
if (jQuery.nodeName(elem, "option")) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
// We need to handle select boxes special
if (jQuery.nodeName(elem, "select")) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if (index < 0) {
return null;
}
// Loop through all the selected options
for (var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++) {
var option = options[i];
// Don't return options that are disabled or in a disabled optgroup
if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if (one) {
return value;
}
// Multi-Selects return an array
values.push(value);
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if (rradiocheck.test(elem.type) && !jQuery.support.checkOn) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function (i) {
var self = jQuery(this),
val = value;
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, self.val());
}
// Treat null/undefined as ""; convert numbers to string
if (val == null) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (jQuery.isArray(val)) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
if (jQuery.isArray(val) && rradiocheck.test(this.type)) {
this.checked = jQuery.inArray(self.val(), val) >= 0;
} else if (jQuery.nodeName(this, "select")) {
var values = jQuery.makeArray(val);
jQuery("option", this).each(function () {
this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
});
if (!values.length) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
If we break the above wall down we can get
function (value) {
if (arguments.length === 0) {
return (this[0].value || "")
}
this.value = val;
return this;
}
Of course jQuery has a lot more code to deal with various edge cases and special things.
In essence jQuery takes a selector. finds the elements. Stores them internally then returns you an object.
This object has all kinds of methods that allow you to mutate the underlying dom objects stored internally. .val is one of them.
There are plenty of articles on how jQuery works (there are screencasts too).
jQuery, as you've noticed, is basically a bunch of methods operating on an array of elements. It is also intended to normalize browser differences under the hood.
Take the basic usage $("#xyz").val();
I can even tell you what jQuery is doing behind the scenes, but I don't think you really want to know. :)
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// ...
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// ...
},
// ...
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
So basically $(selector) means newjQuery.fn.init(selector), it's just a shortcut for easier typing (and also to prevent the "bug" where fogetting new binds this to the global object, instead of the current instance).
Also, the so-called plug-ins added as jQuery.fn.ext are mapped to jQuery.fn.init.prototype as you can see in the last line, it's another shortcut. So when you call $(selector) everything that is added to jQuery.fn will also be on jQuery.fn.init.prototype and so the new instance will have those methods as $(selector).ext(...).
// as you use it today
jQuery.fn.plugin = function ( ... ) { ... }
$(selector).plugin( ... )
// as it would be without shortcuts
jQuery.fn.init.prototype.plugin = function ( ... ) { ... }
(new jQuery.fn.init(selector)).plugin( ... )

Categories

Resources