2

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?

3
  • I've read that people are using json_encode wenn putting php in javascript.Am not right? Commented Mar 12, 2016 at 17:27
  • How to embed php in js: stackoverflow.com/questions/3352576/… Commented Mar 12, 2016 at 17:40
  • Also, make sure the ID doesn't include any spaces and make sure to escape special characters, or the jQuery selector won't work. Commented Mar 12, 2016 at 17:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

ok, what is the better way to pass it.If i have for example 100 rows from database, and i need 100 dropdownlists?
it doesn't matter how many rows do you have, give them all unique dynamic id and common class and bind your event to this class, then when event is fired on one of the elements you just check the id of the particular event target
Could you give me a simple example?It would be very usefull for me.Thanks
how many unique <select> elements with dynamicly generated id attribute you are expecting in your document?
From 10 to 30 maybe.I have users information from database, and i need dropdownlist for every user in row isAdmin.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.