Mark checkbox if user writes input text in a table

Asked

Viewed 1,147 times

5

I need it when the user writes to an input text, the checkbox of the respective table row should be marked, and if the user leaves the input text blank again, checkbox is cleared. Follow code:

<table class="table table-striped" id="produtostab">
    <thead>
        <tr>
            <th>Quantidade</th>
            <th>Selecionar</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <input class="inputq1" name="inputquant" type="text" />
            </td>
            <td>
                <input type="checkbox" name="checkboxvar">
            </td>
        </tr>
        <tr>
            <td>
                <input class="inputq1" name="inputquant[]" type="text" />
            </td>
            <td>
                <input type="checkbox" name="checkboxvar[]">
            </td>
        </tr>
    </tbody>
</table>
<button id="add" class="btn btn-default">Adicionar</button>

Fiddle

As you can see, it will be a table with multiple lines, so it is no use for the user to write in a input and mark all the checkbox, it is necessary mark only those of the respective lines inputs are completed. I believe this should be done with Javascript, but as?

This is the PHP that creates HTML:

<?php
$conn = new mysqli('localhost', 'root', '', 'sindigrejinha') or die('Falha ao conectar-se com DB');
mysqli_query($conn, "SET NAMES 'UTF8'") or die("ERROR: " . mysqli_error($con));
$result = $conn -> query("select idProduto, Descricao from produto");
while ($row = $result -> fetch_assoc()) {
    unset($idProduto, $Descricao);
    $idProduto = $row['idProduto'];
    $Descricao = $row['Descricao'];
    echo '<tr>';
    echo '<td>' . $Descricao . '</td>';
    echo '<td><input name="inputquant[]" type="text" /></td>';
    echo '<td><input type="checkbox" value="'. $idProduto .'" name="checkboxvar[]"></td>';
    echo '</tr>';
}
?>
  • I wanted to remove the PHP code because the problem is pure JS/HTML, but as it has an answer that speaks of PHP, did not give...

4 answers

6


I suggest slightly adapting your HTML, including a class (say: CaixaMagica) in each text box and a class in each checkbox. Your HTML will look like this:

<table>
    <tr>
        <td>
            <input class="CaixaMagica" name="inputquant" type="text" />
        </td>
        <td>
            <input class="CheckboxMagico" type="checkbox" value="idProduto" name="checkboxvar" />
        </td>
    </tr>
    <tr>
        <td>
            <input class="CaixaMagica" name="inputquant" type="text" />
        </td>
        <td>
            <input class="CheckboxMagico" type="checkbox" value="idProduto" name="checkboxvar" />
        </td>
    </tr>
</table>

After this, just use this code:

$(function(){
    $(".CaixaMagica").keyup(function(){
        if($(this).val().length > 0){
            $(this).parent().parent().find(".CheckboxMagico").prop("checked", true);
        } else {
            $(this).parent().parent().find(".CheckboxMagico").prop("checked", false);
        }
    });
});

Edit: I forgot the Jsfiddle that I prepared.

  • it is exactly what I sent hehehehehe clear better elaborated example but the result is the same need for adaptation for its only hehehehe very good

  • I get it. It works great, but only if the text input and checkbox are in the same <td>. In my case, they need to stay in <td>s different, as seen in the code I passed. I’m sorry for the ignorance, but my knowledge of javascript is extremely limited.

  • Put your code in the fiddle so we can help more

  • @Otto, of course there’s a lot of resemblance, but I swear I didn’t copy your example; I was preparing my test when you answered.

  • Fine, I put it in jsfiddle, but I had to adapt, after all here it is mounting the table through a database. I’ve updated the question.

  • @Ruipimentel no problem hehehe

  • I updated my answer. I believe you can adapt it now :)

  • Perfect! It worked now. I thank Rui Pimentel and Otto for their help there! Thank you haha

  • Queisso, always good to help :D

  • 1

    Rui, a suggestion, instead of calling .parent() multiple times until reaching td, utilize .closest("td").

  • Living and learning! Thanks, I didn’t know this!!!! ^^

Show 6 more comments

2

I think that makes it practical to understand

$( "#input-a-monitorar" ).keyup(function() {
  $('.myCheckbox').prop('checked', true);
  $('.myCheckbox').prop('checked', false);
});

I am available for more information

  • Dude, it didn’t work. I tried to put the script inside the tag <head> before <body>, before and after the table, I tried to change input-a-monitorar for the id, name and class of my input text and also the mycheckbox for the id, name and class of my checkbox. Nothing worked, I write in input text and no checkbox is checked. Maybe I’m doing something wrong, but I don’t know what.

  • but remembering puts what I sent you inside the $( Document ).ready(Function() to work right so much that I put checked option true and false to exemplify

1

<input class="input" name="inputquant" type="text" />

Putting a class in the text input, js would look like this:

$(function(){
    $(".input").keyup(function(){
        if($(this).val()){
            $("input[type=checkbox]",$(this).parents("tr")).attr("checked", "checked");
        } else {
            $("input[type=checkbox]",$(this).parents("tr")).removeAttr("checked");
        }
    });
});

I hope this can help.

  • Leonardo, the parents will continue to seek elements tr even after finding the first tr, then if there are tables inside tables, your code can introduce a bug. Then the ideal would be to use the .closest(), even for being faster.

0

From what I understand, you want when it enters a quantity for a product, the checkbox stores the ID of this product so that later you can reference which product was entered the quantity.

If it is, I recommend a small modification that will work more optimally in your script PHP, the moment you recover the data.

The moment you mount HTML, make this change:

while ($row = $result -> fetch_assoc()) {
    unset($idProduto, $Descricao);
    $idProduto = $row['idProduto'];
    $Descricao = $row['Descricao'];
    echo '<tr>';
    echo '<td>' . $Descricao . '</td>';
    echo '<td><input name="inputquant['.$idProduto.']" type="text" /></td>';
    echo '<td><input type="checkbox" value="'. $idProduto .'" name="checkboxvar[]"></td>';
    echo '</tr>';
}

The difference is in the stretch name="inputquant['.$idProduto.']", this way you access the quantity of a product using the product ID as the index of the array.

The way the problem was designed, the checkbox is being a quantity field monitor, so I make this suggestion. Even, in an example they gave, it really solves his problem, but in case the user marks the checkbox without having completed anything on input, will give wrong information to the script.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.