2

i want to build my own PROP function just like what Jquery does, but in pure Java script.

this is my code :

<input id="submitButton" type="submit" value="LOGIN">

function prop(el, dom, boolean) {

    var convert = eval(dom);
    el.convert = boolean;
    console.log(convert);
}

var x = document.getElementById("submitButton");

prop(x, "disabled", true);

How to convert string into object property? I heard that eval will be useful? But why did i got the below error?

ReferenceError: disabled is not defined

what's wrong with my code?

5
  • 2
    use - el[dom], or el.setAttribute(dom,value) to manipulate properties of an el. Commented Dec 22, 2015 at 6:26
  • ^ You should use this. Commented Dec 22, 2015 at 6:28
  • wow BatScream, your method works perfect! thank you so much!!!! you are A W E S O M E, anyway, i wonder what kind person that give me down votes for this questions lol Commented Dec 22, 2015 at 6:34
  • @BatScream - Why are the things you say in this comment (which holds the best answer) nowhere to be found in your actual answer? Commented Dec 22, 2015 at 6:49
  • @JimboJonny - have included it now. I thought the link and the comments would have sufficed. Thanks for pointing it out. Commented Dec 22, 2015 at 6:53

2 Answers 2

3

You should not use eval() to convert property names into properties. Use Property accessors.

e.g., el[dom] or el.dom.

If the Object is an HTML element, you could use the setAttribute and getAttribute methods that are available.

when you pass in a string as argument to eval, it tries to represent the string as java script code.

Here, you have passed in a string disabled.

It gets represented as:

disabled;

The interpreter now tries to locate a variable named disabled. Since disabled is not a variable we have defined in the context, it throws the error: ReferenceError: disabled is not defined.

To validate this, try defining a variable and then invoking the eval() function on it.

var disabled = 10;
console.log(eval("disabled"));

prints: #10

Sign up to request clarification or add additional context in comments.

Comments

0

It's because you're trying to evaluate what "disabled" alone is to. eval("document.getElementById('submitButton').disabled") would work.

1 Comment

This one also working! thanks Aiman Al-Eryani. you're the best!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.