How to call a function in javascript through a text box?

Asked

Viewed 1,421 times

2

I wanted to know how to call a function through a text box. example:

<input type="text" value="load()"/>

But it’s not exactly the load function, I wish the typist could call any function even.

  • Your question is unclear. Do you want the user to type code in the input to be run? or a function that runs when the user writes text to the input?

  • input code to be run :)

  • Do you generate the code through some language? if yes post here, because perhaps it is more practical to insert the value through her...

3 answers

3


You can use the val(). Try it like this:

var input = document.querySelector('input[type=text]');
input.addEventListener('blur', function(){
    eval(this.value);
});

But I strongly recommend read this about Eval();

Example

  • 1

    +1 Your idea is much better than mine... nor came to mind =)

  • 1

    Wow, it worked/(would never think of using the Eval function). But is it guaranteed to work even with any function even? Like $('#content'). html('dddddddd')

  • 1

    @Iagobruno, yes. Test this: http://jsfiddle.net/326EU/2/

  • If I don’t engage, "seTimeout" can also do the same thing as Eval =p

  • If it’s not too much to ask, there would be some way to detect if the text written inside an input is something javascript?

  • 1

    @Iagobruno, this seems difficult :/ I think it would give a good new question! One idea (with many exceptions) is test if you have parentheses like this (link): input.value.match(/\(?(.*)\)/);

  • In my tests worked your method, but do you think it can give error in some case? Because I saw that it checks if it has parentheses in value..

  • 1

    @Iagobruno, a case where it fails is for example: "I am Sergio (John’s brother)"

Show 3 more comments

2

All objects defined via direct code at the root of the scope will stop at the object window, and so you can do so:

window["nome do método"]();

So will call the function you want by name.

0

Just use type attributes onevent tag input.

For example:

<input type="text" onkeydown="alert('keydown')" />

http://jsfiddle.net/MdX76/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.