1

I have a function addText(), which has 3 variables (textInput, type, rowID). I declared them without the var keyword (so that they can be used outside the function?). I have many checkboxes which I created this way:

<td><input type="checkbox" name="CB" id="monitor_'+rowID+'"/></td>

Then I have this function, which requires the use of those 3 variables:

function monitoring(rowID, number, type) {
    var $check = $('#status_table #monitor_' + rowID);
    $('#test').append($check);
    if($check.is(':checked')) {
        $.post('/request', {
            inputText: number,
            key_pressed: type
        }).done(function (reply) {
            if(reply == "on") {
                $('#test').append("on");
            } else {
                $('#test').append("off");
            }
        });
    }
    return;
}

This function will be called here:

$('#status_table #monitor_'+rowID).each(function(rowID, textInput, type){
    monitoring(rowID, textInput, type);
});

Note: inputText is a variable posted to somewhere.

Questions:

  1. Is this the correct way to call a selector with variable?

    $('#status_table #monitor_'+rowID)

  2. Should I pass the variables twice in the second set of code (both at the selector function and monitoring function)?

  3. How do I pass variables correctly?

  4. Is the selector correct? Or should I change $('#status_table #monitor_'+rowID).each(function(){}) to $('#status_table tr').each(function(){})?

5. ADDED: where and how should i call the function "monitoring" ? i put it under addText (refer codes below) but it makes no sense because the function wil then be only executed when the "add" button is clicked. Furthermore, as my selector is a variable, i would like to make sure it can actually perform the same thing for all the checkbox that is checked. How can i do this?

I tried but my code has no response at all when I check the checkbox.

EDIT:

Here's my addText() function (I've included function monitoring in this function instead of under another jQuery action as above):

function addText(add_type, fb_type) {
  $("#" + add_type + "Add").click(function () {
    $('.TextInput').empty();
    textInput = $("#" + fb_type + "TextInput").val();
    if(textInput.length === 0) {
      alert('please enter the fieldname');
      return;
    }
    index = $('#status_table tbody tr').last().index() + 1;
    type = $("#select-choice-1").find(":selected").text();
    rowID = type + textInput;
    var str = '<tr id="' + rowID + '">' + '<td>' + index + '</td><td>' + rowID + 
      '</td><td class="type_row_' + textInput + '">' + type + '</td><td class="feedback number">' +
      textInput + '</td>' + '<td><img src="static/OffLamp-icon.png" class="image" id="off"></td>' +
      '<td><input type="checkbox" name="CB" id="monitor_' + rowID +
      '" class="custom" data-mini="true" /><label for="CB"> </label></td><td class="outputRemove">x</td>' +
      '</tr>';
    if(alreadyExist(textInput, type)) {
      alert('Entry exists. Please enter another number.')
    } else {
      $('#status_table tr:last').after(str);
    }
    monitoring(rowID, textInput, type);
    return;
  });
}

The HTML of the table:

<table class="config" id="status_table">
  <thead>
    <tr>
      <th colspan="4" ; style="padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em">Output Status</th>
    </tr>
    <tr>
      <th>Index</th>
      <th>Row ID</th>
      <th>Feedback Type</th>
      <th>Feedback Number</th>
      <th>Status</th>
      <th>Monitor?</th>
      <th>Remove?</th>
    </tr>
  </thead>
  <tbody>
    <tr></tr>
  </tbody>
</table>
7
  • Can you finalize your question first? Seems like you've got some names wrong and stuff left out. Commented Apr 29, 2013 at 8:45
  • which one do you mean? i can add more details where necessary. Commented Apr 29, 2013 at 8:47
  • Can we see the HTML for the table, please? Commented Apr 29, 2013 at 8:49
  • 1
    Please read about the arguments provided with .each(). api.jquery.com/each Commented Apr 29, 2013 at 8:49
  • 1
    @yvonnezoe Posting the code surrounding the .each() call would be helpful; if that's inside the addText() function then post the whole of that (or strip it to the relevant parts). Commented Apr 29, 2013 at 8:53

3 Answers 3

1

There are a few issues. First of all, this won't work:

$('#status_table #monitor_'+rowID).each(function(rowID, textInput, type){
  monitoring(rowID, textInput, type);
});

The function passed to .each() has two parameters: indexInArray and valueOfElement , though you can call them whatever you like - in this case, rowID would be the index and textInput would be the value of the element; type will be undefined because there will be no value passed to it.

Second, using .each() after calling an ID selector makes no sense. ID selectors will select, at most, a single element because IDs have to be unique.

If rowID, textInput, and type are in scope when you call that .each(), then you could just call monitoring directly without the need for .each() at all. So just:

monitoring(rowID, textInput, type);
Sign up to request clarification or add additional context in comments.

4 Comments

oh thanks for the correction! i've added the addText() function in the question and it has the HTML of the table. the rest of the table is just the header. added the skeleton of the table in the question as well :)
what do you by "in scope"? do u mean i can just put "$('selector').monitoring(rowID, textInput, type);"?
@yvonnezoe By "in scope" I mean the variables are visible when you execute the code; if you've declared them without using the var keyword then they'll be globally scoped (and therefore always in scope anywhere in your code, unless they're shadowed by another variable). You'd just do monitoring(rowID, textInput, type); since it's not a jQuery function.
but where should i call the function? should there be an event to trigger it like .click() or .change()? (i don't really understand the usage of change() as explained here:api.jquery.com/change can it be used anywhere that will have changes? like for this case, the checkbox may be ticked?
1

Is this the correct way to call a selector with variable?

Selectors are just strings. You assemble selectors with variables like you assemble strings with variables.

Should I pass the variables twice in the second set of code (both at the selector function and monitoring function)?

Depends on which scope the variables live. If the variables are in the same scope as the function, then the function has access to it. If the function is declared outside where the variables are, then you should pass it to them.

How do I pass variables correctly?

As arguments during invocation, like someFunction(theFoo,theBar,theOtherBar)

Is the selector correct? Or should I change $('#status_table #monitor_'+rowID).each(function(){}) to $('#status_table tr').each(function(){})?

IDs are supposed to be unique in the page, and exist only once. Therefore, the id as a selector should suffice, like $('#monitor_[someID]'). But that would only mean getting one at a time for every rowID. Better if you use the $('#status_table tr').each(function(){}) instead, and loop over the tr.

2 Comments

Thank you for your explanation! :) i've added the addText() function in the question as well.
but in my case, i cant determine if the selector is called properly because it does not perform the actions in the function 'monitoring' :/ i've edited the codes above to include the function under addText. please take a look and give me some advices :) thank you.
1
  1. Is this the correct way to call a selector with variable? $('#status_table #monitor_'+rowID)

    Yes. The selector passed to jQuery is just a string so adding a variable to a string like that would be the way to do it. I will note that element IDs are meant to be unique (Look at item 2 in the list on that linked page)

  2. Should I pass the variables twice in the second set of code (both at the selector function and monitoring function)?

    You don't need to if your function has the parameters that the .each function returns, you can just go like $('#status_table #monitor_'+rowID).each(monitoring);.

    I will note however that the arguments in the .each callback are indexInArray and valueOfElement as specified here and doesn't have rowID, number or type as arguments passed back.

  3. How do I pass variables correctly?

    No idea what you mean. If you are referring to passing variables to functions, you have been doing it correctly. eg. myAwesomeFunction(myFirstVariable, mySecondVariable)

  4. Is the selector correct? Or should I change $('#status_table #monitor_'+rowID).each(function(){}) to $('#status_table tr').each(function(){})

    Well it really depends on what you are trying to achieve. The first grabs any elements with the ID that is evaluated from 'monitor_'+rowID that are inside the element with the ID status_table. The second grabs all tr that are inside the element with the ID status_table. It depends what your are trying to do.

3 Comments

but in my case, i cant determine if the selector is called properly because it does not performing the actions in the function monitoring :/ i've edited the codes above to include the function under addText.
It is useful to use tools like Firebug, Chrome Developer Console or even the built-in Developer tools in IE8+ to check how the execution of your functions is going by inserting breakpoints. Honestly though, I went through your code again and I really don't understand what it is doing and why you have it doing what it is. I'm not sure if this is really a valid question for Stack Overflow as it requires multiple different answers.
i've created a fiddle and post a new question here: stackoverflow.com/questions/16328743/… Hope it is clearer now :)

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.