2

When the input gets blurred, I want to get the value of the input and replace the word "action" in the script, with the value of the input. So for example, if I type "hide" in the input, the word "action" would be replaced with "hide". Or something to that effect.

I'll then be using this logic to define the trigger (#elementA) and target (#elementB) also.

HTML

<input type="text" id="define-action">

<script id="interactions">
  $('#elementA').click(function() {
    $('#elementB').action();
  )};
</script>

JS

$('#define-action').blur(function() {
  var action = $(this).val();

  // Replace "action" with action
)};

2 Answers 2

2

Use object [] notation

$(selector).hide(); can be written as $(selector)['hide']()

So you could pass in variable instead of hard code string

$(selector)[action]()

Beware you will get errors thrown if method represnted by variable doesn't exist, so you should probably create an array of valid methods you will accept and make sure value is in the array before calling the method

Example of testing values in array:

var allowedMethods=['hide','show','slideUp'];
if( $.inArray( action, allowedMethods) >-1){
  $(selector)[action]()
}else{
    alert( action +' is not a valid method')
}
Sign up to request clarification or add additional context in comments.

10 Comments

I'm getting "Property 'undefined' of object [object Object] is not a function". Is that what you meant by the errors? If so, could you elaborate a little please?
yes, that's sort of error. What methods do you want to support?
things like hide, show, fadeIn, fadeOut etc. I'll be editing this code a lot in future. Just trying to get something working for now.
you had typo in id="#define-action" ...should be ..id="define-action" WOrks here jsfiddle.net/4JMF2/2
$('#'+ target)...can even see in syntax highlighter that target wasn't a variable
|
1

Instead of dot notation use bracket notation

Also I don't think you need to use the blur handler, in the click handler you can read the value of the input filed

$('#elementA').click(function () {
    var action = $('#define-action').val();
    $('#elementB')[action]();
});

or if you want to use the blur method then you need to define the variable action is a shared scope of both the click and blur handlers

$('#elementA').click(function () {
    $('#elementB')[action]();
});
var action;
$('#define-action').blur(function () {
    action = $(this).val();
});

Comments

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.