How to get the value from a label

42,336

Solution 1

Labels aren't submitted with forms, so it isn't going to work the way you have it. Why not create a hidden input field beneath it that echoes the same value? Then your $_POST[''] will work.

<input type="hidden" name="lblItemName" value="<?php echo $ItemName; ?>">

Solution 2

Very easily done.

alert($('label').html());

Solution 3

Without great changes in your code, you can get what you need using a hidden field initialized with the same value that the label.

Share:
42,336
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    Okay so the problem is that I have a label which is in a form and I'm trying to access this label when I press a button, my form looks like:

    <form method = 'POST'>
    <img src = 'ItemIcons/<?php echo $ItemPicture;?>.png' alt = '<?php echo $row["ItemDesc"];?>'/>
    <label name = 'lblItemName'><?php echo $ItemName; ?></label> 
    <br>
    <label> <?php echo "Gold:" . $row["ItemPrice"]; ?> </label> 
    
    
    <input type = 'submit' value = 'Buy <?php echo $ItemName; ?>' name = 'ItemPurchase'/>
    </form>
    

    and my code for calling the button looks like:

    if(isset($_POST['ItemPurchase'])) {
        $ItemName = $_POST["lblItemName"];
        ?>
            <script>
                alert('<?php echo $ItemName;?>');
            </script>
        <?php
    }
    

    Currently it alerts an empty value, it works when I place it as a textbox and not a label, but it needs to be a label sadly, any help would be great, thanks.

  • Gary Hayes
    Gary Hayes over 10 years
    @ Sythnet This is a good solution if the information doesn't need to dynamically change. If the information changes, you'll need to use javascript / jquery and update that hidden field before submit. So use this idea along with my answer.
  • Admin
    Admin over 10 years
    Yeah, the information doesn't change and I got it working with the hidden text field, thanks for the information, if you could answer one more question though that be great! Why doesn't a label send information, is there a reason it was built to not send information?
  • spacebean
    spacebean over 10 years
    Well, labels are meant to explain what the expected content of the related input field is, and since input fields have names that put it in context on the end the data is received, there generally wouldn't be a need for the label information to be included as well.
  • Anu
    Anu about 3 years
    @spacebean I know this is an old thread. But just curious, if use input as hidden field, then people can actually manipulate that hidden field by going into Chrome tools such as inspect element, make it visible and change values accordingly right?