Click here to Skip to main content
15,896,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am trying to get value of displayed values, which are boy names and girlsnames - i have a button displaying against each name, in which user can select.

At the moment, i can click the button but it is giving me 'undefined'

can someone help?

What I have tried:

$i = 0;
  while($i < $count) {
    echo '<tr>';
    if(isset($arr['BoysName'][$i])) { echo '<td>'.$arr['BoysName'][$i].'<button type="button" value="favourites" id="favourites"</button><div style="float:right;"> ♥</td>'; }
    else{ echo '<td class="noBorder"> </td>'; }
    if(isset($arr['GirlsName'][$i])) { echo '<td>'.$arr['GirlsName'][$i].'<div style="float:right;"> ♥</td>'; }
    else{ echo '<td class="noBorder"> </td>'; }
    echo '</tr>';
    $i++;
  }

  echo '</table></center>';
}
?>

 
<script>

$(document).ready(function() {
    $("button").click(function(e) {  
		e.preventDefault();
	 
	  var answerid = $(this).prop('i');  
	  alert(answerid);
	  
    });
});
		</script>
Posted
Updated 12-Feb-18 4:25am

1 solution

Before everything else, your HTML is not properly complete.
HTML
<!-- You missed closing angle bracket for opening tag. -->
<button type="button" value="favourites" id="favourites"></button>

Next, you are trying to see if there is a property "i", and if so, then what is the value. In your case, the property doesn't exist, thus it causes the undefined value to be returned. There are multiple solutions to this, and you can do this in many ways.

First one being that you add a property with key, "i".
HTML
<button type="button" value="favourites" id="favourites" i="valuestoshow"></button>

Otherwise, change the jQuery code and use the property key to render the information in the alert box. Something like this,
JavaScript
alert($(this).prop("value"));

// Or
alert($(this).prop("id"));

// Or
alert($(this).text());

That will give you an opportunity to understand how this works, and then proceed with the next logic inside your app.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900