0

Having an html code like this:

<table>
    <tr>
        <td bgcolor=yellow>LED #1</td>
        <td id=led0 bgcolor=red>ON</td>
    </tr>
    <tr>
        <td bgcolor=yellow>LED #2</td>
        <td id=led1 bgcolor=red>ON</td>
    </tr>
    <tr>
        <td bgcolor=yellow>LED #3</td>
        <td id=led2 bgcolor=red>ON</td>
    </tr>
    <tr>
        <td bgcolor=yellow>LED #4</td>
        <td id=led3 bgcolor=red>ON</td>
    </tr>
    <tr>
        <td>
            <button>number 1</button>
        </td>
    </tr>
    <tr>
        <td>
            <button>number 2</button>
        </td>
    </tr>
    <tr>
        <td>
            <button>number 3</button>
        </td>
    </tr>
</table>

I would like to achieve something like this:

$('button').click(function() {
  var index = $("button").index(this);   
 // alert(index);
  $("#led[index]").html('<div style="background:#cccccc" >OFF</div>');

  
});

In words: I want to detect the button pressed (which is already working) and then modify the html code of the td element with id="led[index]" and using the variable "index" to find the right led number.

Any idea?

0

4 Answers 4

2

Cancatenate the following way:

$("#led" + index);
Sign up to request clarification or add additional context in comments.

Comments

1

I went one step further and made it so that you can toggle ON or OFF. Your main issue is that you did not concatenate index, this should be done like so + index +. I used the following jQuery code:

$('button').click(function() {
var index = $("button").index(this);   
// alert(index);
  // You must concatenate index with "+"
  if ($("#led"+index+":contains('ON')").length > 0)
    $("#led"+index).html("OFF").css("background-color", "red");
  else if ($("#led"+index+":contains('OFF')").length > 0)
    $("#led"+index).html("ON").css("background-color", "green");
});

I also made a working JSFiddle so that you can see it work.

You can put whatever HTML you want where the ON or OFF is changed.

Comments

0

You would want to use $(this).attr("id"); and then concatenate the index to the #led id

        $('button').click(function() {
          var index = $(this).attr("id");
          $("#led" + index).html('<div id="led'+index+'" style="background:red" >ON</div>');

        // code
    });

HTML:

<button id="someID">

Comments

0

You need to make two edits to your code:

First, you need use the attr('id') method to get the index.

Secondly, you need to concatenate the index onto your jQuery selector.

$('button').click(function() {
    var index = $(this).attr('id');   
    $("#led"+index).html('<div id="led'+index+'" style="background:red" >ON</div>');
});

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.