Darius92
Darius92

Reputation: 311

How to use <select> tag id in javascript. When id is PHP array?

I have HTML <select> tag ID. I need to track with javascript, which option is selected

My html <select> id:

<select id="<?php echo $userArray[$key]["userID"]?>">

My javascript code:

<script type="text/javascript">
    $(document).ready(function(){
        $('#selectionButton').click(function(){
            var selectedValue = $("#<?php echo json_encode($userArray[$key]['userID']);?>").val();
            window.alert(selectedValue);
        });
    });

How to use PHP array as HTML id in javascript?

Upvotes: 2

Views: 1505

Answers (1)

markoffden
markoffden

Reputation: 1468

The point here is not about using particularly only PHP array values as your potential event target identifier, it's generally about using dynamicly generated data as part of elements' id attributes. Here you would better target class instead of id in your JS. So, when the event fires you check target's id value.

$(document).on('click', '.i-am-target-class', function () {
    var targetId = $(this).attr('id');
    // do your stuff knowing id
});

And what you are trying to do passing PHP code as your event target in your JS is far far not the best solution on the market

UPD:

PHP:
<select id="<?php echo $userArray[$key]['userID']; ?>" class="value-to-save"></select>

JS:
var results = {};

$('#save-button').click(function () {
    $('.value-to-save').each(function () {
        var userId = $(this).attr('id');
        var value = $(this).val();
        results[userId] = value;
    });
});

So in the end you will get results object with all your data

Upvotes: 1

Related Questions