assign a value to the javascript variable

4

The problem is the following php returns me several buttons with a hidden input to identify the button.

$nome = $mysqli->query("SELECT * FROM menbros ORDER BY id");
while ($row = $nome->fetch_assoc()) {
$nome = $row['identifier'];
$i    = $row['id'];
<input type='hidden' value='".$i."' id='troca'/>
<button type='button' onclick='troca()'>
}

I need the javascript variable to get the value of the input of the button that was clicked.

This form down returns the first input of the page but as I have several I need my variable to get the value of the input above the button clicked.          var exchange = $ ("# exchange"). val ();     

    
asked by anonymous 06.11.2016 / 18:21

1 answer

4

Do not use the same ID for different elements, ie IDs must be unique and there can only be one per page, without repetitions.

An alternative would look like this:

$nome = $mysqli->query("SELECT * FROM menbros ORDER BY id");
while ($row = $nome->fetch_assoc()) {
    $nome = $row['identifier'];
    $i    = $row['id'];
    echo "<button type='button' onclick='troca(this)' value='".$i."'>";
}

without input and without id . So you can get the value of the button directly ...

and in JavaScript:

function troca(btn) {
    alert('Botão nr: ' + btn.value);
}

jsFiddle: link

    
06.11.2016 / 18:54