0

So I have a control (textbox) being created for each row in my grid view. (c#.net)

So for each of the text boxes, I want to find the current active element and return its id.

it kind of works, but I am having some issues.

I know item.addEventListener does not return a value.

Any ideas on how i can return the value after calling the addListener() function?

var controls = {
    txt: null,
};
var selectedTextArea;
var items = document.getElementsByClassName("textboxnew");

for (var i = 0; i < items.length; i++) {
    controls = addListener(items[i], controls);
    alert(controls.txt);  ///GET ERROR HERE
}

function addListener(item, ctrls) {
    selectedTextArea = document.activeElement;
    ctrls.txt = selectedTextArea.name.toString();
    item.addEventListener("click", function () {
        selectedTextArea = document.activeElement;
        ctrls.txt = selectedTextArea.name.toString();
        alert(ctrls);
    });   
    return ctrls;   //VALUE NOT RETURNED ???
}
1
  • 3
    It doesn't look like a jQuery to me anywhere! Can you post your HTML for reference here? Commented Jan 15, 2018 at 6:04

1 Answer 1

1

You can use jQuery.Callbacks() to define a callback function that can be fired with parameters passed.

var callbacks = jQuery.Callbacks();

function active(id) {
  alert(id)
}

callbacks.add(active);

$("input").on("click", function() {
  callbacks.fire(document.activeElement.id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="1" autofocus tabindex="1">
<input id="2" tabindex="2">
<input id="3" tabindex="3">

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

3 Comments

So now with your code above, if i were to wrap that code in another function **$(function () { YOUR CODE } ** how can I get that "id" value??
What do you mean by "get that "id" value"? You can pass the value id within active function to another function function active(id) { fn(id); }.
Depending on what you are trying to achieve you can alternatively use a Promise pattern to return a value from an asynchronous function call when the event occurs. Are you trying to await the click on each element then perform a task?

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.