user2692256
user2692256

Reputation: 25

javascript click function not working on form generated in php

I have a form created using echo command in php. It is being displayed correctly. I have a javascript which detects click on radio button of form and displays the hyperlink/anchor corresponding to each button group, which is not working.

But if I create the form in html only without any php, it works perfectly. please HELP.

Form creation

echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
    echo(($i+1)." ".$row[1]."<br>");
    echo("
    <input type = 'radio' value = $row[2] name = '$i'>$row[2]&nbsp&nbsp&nbsp&nbsp
    <input type = 'radio' value = $row[3] name = '$i'>$row[3]<br>
    <input type = 'radio' value = $row[4] name = '$i'>$row[4]&nbsp&nbsp&nbsp&nbsp
    <input type = 'radio' value = $row[5] name = '$i'>$row[5]&nbsp&nbsp
    <a id='$i' href='javascript:clear($i)'>Reset</a><br>");
    $i++;
    $z[]=$row[6];
}

SCRIPT

$('input:radio').click(function() { 
    var n = $(this).attr('name');
    var k ='#' + n;
    alert($(this).attr('name')); 
    $(k).show(400);
    });

Upvotes: 1

Views: 194

Answers (3)

Ashis Kumar
Ashis Kumar

Reputation: 6554

You can try changing $('input:radio') to $('input[type="radio"]').

Try this

$('input[type="radio"]').on('click', function() { 
    var n = $(this).attr('name');
    var k ='#' + n;
    alert($(this).attr('name')); 
    $(k).show(400);
});

Upvotes: 2

Alwin Kesler
Alwin Kesler

Reputation: 1520

Hmm... your problem is that $row array should be with curly brackets because you're in double quotes

echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
    echo(($i+1)." ".$row[1]."<br>");
    echo("
    <input type = 'radio' value = '{$row[2]}' name = '$i'>{$row[2]}&nbsp&nbsp&nbsp&nbsp
    <input type = 'radio' value = '{$row[3]}' name = '$i'>{$row[3]}<br>
    <input type = 'radio' value = '{$row[4]}' name = '$i'>{$row[4]}&nbsp&nbsp&nbsp&nbsp
    <input type = 'radio' value = '{$row[5]}' name = '$i'>{$row[5]}&nbsp&nbsp
    <a id='$i' href='javascript:clear($i)'>Reset</a><br>");
    $i++;
    $z[]=$row[6];
}

Upvotes: 0

Trevor
Trevor

Reputation: 16116

$('body').on('click','input:radio',(function() { 
  var n = $(this).attr('name');
  var k ='#' + n;
  alert($(this).attr('name')); 
  $(k).show(400);
});

When clicking on dynamically created elements you need to use event delegation.

Upvotes: 0

Related Questions