assign a value to javascript variable

Asked

Viewed 80 times

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 grab the input value of the q button was clicked.

this way the bottom returns me the first input of the page but as I have several need my variable take the value of the input above the button clicked. var exchange = $("#exchange"). val();

  • 2

    Describe better because you can close. Take a tour to understand better: http://answall.com/tour

1 answer

4


Don’t use the same ID for different elements, meaning Ids have to be unique and there can only be one per page, no repetitions.

An alternative would be 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 take the value button directly...

and in Javascript:

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

jsFiddle: https://jsfiddle.net/occd1upa/

Browser other questions tagged

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