Reputation: 4491
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
)};
Upvotes: 2
Views: 48
Reputation: 171679
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')
}
Upvotes: 2
Reputation: 388316
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();
});
Upvotes: 1