How to set multiple properties in Javascript - javascript

I want to disable an element and also set its placeholder in Javascript.
I'm able to do this with the below code (I'm referring to the writecontent element).
function toggleType() {
var type = document.querySelector('select[name="type"]').value;
if(type == 'Review') {
aboutreview.style.visibility = ('visible');
document.querySelector('.writecontent').disabled = true;
document.querySelector('.writecontent').placeholder = "Not available in Review";
} else if (type == 'Discussion' || '') {
aboutreview.style.visibility = ('hidden');
document.querySelector('.writecontent').disabled = false;
Instead of calling the element twice, how would I set the disabled and placeholder at the same time when calling the element the first time?

May be by storing the element reference in a variable.
const writeElem = document.querySelector('.writecontent');
if (writeElem) {
writeElem.disabled = true;
writeElem.placeholder = "Not available in Review";
}

Related

Syntax Error in Basic Javascript Function

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" : "";
}

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) {
^^

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.

Retrieve the "Placeholder" value with Javascript in IE without JQuery

I have some Javascript code that checks if a browser supports Placeholders and if it doesn't it creates them itself. Now this works on some older browsers but not all, especially IE.
All I need to do it get the "Placeholder" value, at the moment the placeholder in IE9 is "undefined".
Here is my code:
//Test if Placeholders are supported
var test = document.createElement("input");
if ("placeholder" in test) {
var testholder = true;
}
else {
var testholder = false;
}
//Fix unsupported placeholders
function placeHolder(id)
{
var demo = document.getElementById(id);
demo.className = "fix-hint";
demo.value = demo.placeholder;
demo.onfocus = function()
{
if (this.className == "fix-hint")
{
this.value = ""; this.className = "fix-nohint";
}
};
demo.onblur = function()
{
if (this.value === "")
{
this.className = "fix-hint"; this.value = demo.placeholder;
}
};
return false;
}
I am using 0% Jquery, I feel it's too bulky to solve small problems, plus I want to learn pure Javascript. Modernizr is a no too although I may come round to using it at some point.
UPDATE
This is the working code. Tested in IE 8 and 9. (The function call is within an if/else for "placeSupport".)
//Check if placeholders are supported
placeholderSupport = ("placeholder" in document.createElement("input"));
if(!placeholderSupport){
var placeSupport = false;
}else{
var placeSupport = true;}
//Support placeholders in older browsers
function placeHolder (id)
{
var el = document.getElementById(id);
var placeholder = el.getAttribute("placeholder");
el.onfocus = function ()
{
if(this.value == placeholder)
{
this.value = '';
this.className = "fix-nohint";
}
};
el.onblur = function ()
{
if(this.value.length == 0)
{
this.value = placeholder;
this.className = "fix-hint";
}
};
el.onblur();
}
If you're not sure if you're able to use certain functionality/attributes, try caniuse.com - you'll notice that placeholder is not available in IE9.
Try using getAttribute("placeholder")
getAttribute() returns the value of the named attribute on the
specified element. If the named attribute does not exist, the value
returned will either be null or "" (the empty string); see Notes for
details.
EXAMPLE
HTML
<input id="demo" placeholder="Rawr" />
JavaScript
var placeholder = document.getElementById("demo").getAttribute("placeholder");
console.log(placeholder);

Javascript - Passing function as string, then execute if it exists

I have a javascript library which does returns a list of results to a div triggered on keyup events. I want to use Jquery to apply a standard keyup event to all fields on all pages which have a certain class.
That part I can do and it works OK.
My issue is that the parameters which I use are dynamic and the last 2 of these are optional functions.
<input type="text"
class="font8_input" name="wsFromPart"
value="<%=wsFromPart%>" id="wsFromPart"
size="20" maxlength="20"
onfocus="javascript:fncAjaxClear()"
onkeyup="javascript:fncAjaxSearch('wsDatabase','..\\AjaxBrowses\\PartBrowse.asp','wsFromPart','wsFromPartList','fncPrePartAjax',null);"/>
At present, to control this I pass null if I don't have a function.
I'm trying to get the to a position where I can define all of the fields like this.
<input type="text" class="PartClass" name="wsFromPart" value="<%=wsFromPart%>" id="wsFromPart" />
Everything else will be added by setting classes/events by Jquery.
I'm trying to work out how I can test if a function exists on my page, and only execute if it does. I've tried passing the function name as a string but can't seem to make that work. My last attempt is to have a generic function, and pass the name of the function which may exist to this function to evaluate and, if a function, execute it.
<input type="text" class="font8_input" name="wsFrPt" id="wsFrPt" size="20" maxlength="20" value="<%=wsFrPt%>" onfocus="javascript:fncAjaxClear()" onkeyup="javascript:fncAjaxSearch('wsDatabase','..\\AjaxBrowses\\PartBrowse.asp','wsFrPt','wsFrPtList',fncCheckFunction('fncPreAjaxPart1'),'fncPostAjaxPart');"/>
function fncAjaxSearch(wsDb,wsAsp,wsId,wsTarget,wsPreFunction,wsReturnFunction) {
var myDate = new Date();
var myDate1 = myDate.getTime();
if (objXHR.readyState == 4 || objXHR.readyState == 0) {
var wsDatabase = escape(document.getElementById(wsDb).value);
var wsStr = escape(document.getElementById(wsId).value);
var wsParam = "";
if (wsPreFunction !== null) {
wsParam = wsPreFunction();
}
//Only do ajax call if the 'source' field is not empty, otherwise empty target and clear border.
if (document.getElementById(wsId).value > '') {
objXHR.open("GET", wsAsp + '?qryDatabase=' + wsDatabase + '&qryDummy=' + myDate1 + '&qrySearch=' + wsStr + wsParam, true);
objXHR.onreadystatechange = function(){if(objXHR.readyState==4){fncAjaxSearchReturn(objXHR,wsId,wsTarget,wsReturnFunction)}};
objXHR.send(null);
}
else {
document.getElementById(wsTarget).innerHTML = '';
document.getElementById(wsTarget).style.borderWidth = '0px';
}
}
}
If it is a global, you can do this
var fnc = window["yourFunctionName"]; //Use bracket notation to get a reference
if( fnc && typeof fnc === "function" ) { //make sure it exists and it is a function
fnc(); //execute it
}
If it is namespaced, you can do the same type of thing, just involves some looping.
var myFnc = "foo.bar.fun";
var nameParts = myFnc.split("."); //split up the string into the different levels
var fnc = window; //set it to window
for(var i=0;i<nameParts.length;i++){ //loop through each level of the namespace
fnc = fnc[nameParts[i]];
if(!fnc){ //make sure it exists, if not exit loop
fnc = null;
break;
}
}
if( fnc && typeof fnc === "function" ) { //make sure it exists and it is a function
fnc(); //execute it
}
You can check if function exists by:
if(typeof(yourFunctionName) == "function")
//...do your code
else
//...function not exists
if you passing the function name as a string, then change typeof(yourFunctionName) to typeof(eval(yourFunctionName))

Categories

Resources