I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.
Related
I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.
I am working on a BIRT Report and one of the fields contains the following expression:
dataSetRow["user_id"] != dataSetRow["creatorId"] ? dataSetRow["orderCreator"] : ''
What is the logic of this statement?
That statement is the equivalent of the code below, and is called the 'ternary' operator:
var value;
if(dataSetRow["creatorId"]){
value = dataSetRow["orderCreator"];
}
else{
value = '';
}
//To be clear, this isn't assigning to anything - this is the same expression you have in your question.
dataSetRow["user_id"] != value
You could use that expression, which returns a boolean, in an if block, for example:
if(dataSetRow["user_id"] != value){
//Do something
}
Im making a little form where you can pick your value.
If the value is not filled in correctly(I have given some example answers)
I want an alertbox to pop-up which indicates the incorrectly filled in textfields.
Cant seem to make it work...
This is what I tried
if(document.getElementById("BS").value.match ("thin","thick","medium")
{
alert("Fill in the correct values");
}
Here is the fiddle.
http://jsfiddle.net/vuc8Z/
Here is my suggestion:
var val = document.getElementById("BD").value;
if (!(val == "thin" || val =="thick" || val =="medium")) {
alert("Vul een geldige waarde in bij de aangegeven velden");
}
Demo here
Notice that you were using getElementById("BS"), but you wanted BD i think. I changed your match function to a triple || (or) if statement.
I moved your if statement to inside the "go" button click handler so it is fired when the button is clicked.
The match() function expects a regex, you can read more here (MDN: .match()).
EDIT:
To check if the color text input is in the right format you can use this:
var filter = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
if (!color.match(filter)) {
alert('Color code Error!');
}
Updated demo here
If you want to use match method then you can use like :
var str = document.getElementById("BD").value;
if(str.match('thin') || str.match('thick') || str.match('medium'))
{
alert("Fill in the correct values");
}
As per my knowledge match takes regular expression as parameter and don't take multiple values.
I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}
I have a problem using quotation marks in js...
I have an input field using this js-function
function validate(xyz) {
"+umum+" == "yeah_it_is_ok";
if(xyz == ""+umum+"") {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
What do I have to insert in the input-field to get the Hoera message?$
In other words, what is the function of a " or a + in js?
You don't have a syntax error in the function declaration,
but it will fail at execution time, because umum is not defined;
and surely you have a semantic error, because the only way to get "Hoera"
is to declare the umum var first and call the validate function later:
var umum;
validate("test value");
Of course, it always give a "too bad!" message unless you pass ""+undefined+""
as parameter. I think the right function should be:
function validate(xyz) {
var umum = "yeah_it_is_ok"; // or whatever you want to validate with..
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
In this case, when calling validate("yeah_it_is_ok") you'll get an "Hoera!".
You would want to declare a variable like this:
var umum = "yeah_it_is_ok";
Note the var keyword and the use of a single equals for assignment.
Also, a pair of " characters is used to enclose a string variable, and the + will concatenate two strings. However, if you wish to have a double-quotation within a string you need to escape it with a backspace \. For example:
if(xyz == "\"+umum+\"") {
Single- and double-quote characters are used to delimit string constants. The + character is an operator that serves several purposes, including string concatenation, numeric addition, and asserting numeric "positiveness" (used often for its implicit side effects).
I think you mean to write your function like this.
function validate(xyz) {
umum = "yeah_it_is_ok";
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
So then to answer your question, you can put the string that your looking for into the input-field. Which, since you don't have an input field in your example, we can just call the function with the correct string.
validate("yeah_it_is_ok");
Also it seems like you were thinking that you can use " or + in a variable. You can't do that. As others have suggested, you should learn the basics of JavaScript. w3schools.com and the Mozilla Developer Network are good places to do that.
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/learn/javascript
I believe you put a \ infront of it
so like
if(xyz == "\"+umum+\"") {