benhowdle89
benhowdle89

Reputation: 37494

see if item exists in a select element with jquery/PHP

This is a bizarre request but i have two select elements on my page, one for old project numbers and one for new project numbers. I am using PHP to populate the dropdowns from a mysql db. I have also set up a GET variable which will hold an incoming project number from a hyperlink people click on another page. But what i want to do is use jQuery/PHP to take that incoming project number and see if it exists in either of the dropdowns?

This is the GET code:

<?php echo $_GET['project_no']; ?>

Upvotes: 2

Views: 669

Answers (3)

David Thomas
David Thomas

Reputation: 253396

You can assign a JavaScript variable with PHP:

<?php
/*... other php */
echo 'var projectNumber = "' . $_GET['project_no'] . '";';
/*... other php */
?>

Which renders to:

var projectNumber = "12345"; // or whatever value 'project_no' might contain

And then, in jQuery:

$('select > option:contains(' + projectNumber + ')').attr('selected',true);

This, obviously, selects the value. You could just as easily use an if statement of some sort, though. It depends on what you wanted to do with the values, if found.


Edited to add the following selector, which is slightly more meaningful, and uses a slightly more obvious attribute equals selector, though this doesn't look at the text, which the previous example, with :contains() does:

$('select > option[value=' + projectNumber + ']').attr('selected',true);

Upvotes: 1

amosrivera
amosrivera

Reputation: 26514

view online demo here: http://jsfiddle.net/APXGv/

//jQuery sweetness
if($("#dropdown option[value='<?php echo $_GET['project_no']; ?>'").size()){
    alert("exists");
    //your code here...
}

Upvotes: 1

jAndy
jAndy

Reputation: 236092

You would need to interate through the option nodes and compare the values.

function lookup(check, cb) {
    $('#somedropdown').find('option').each(function(index, elem) {
        if( elem.value === check ) {
            cb();
            return false;
        }
    });
}

$.ajax({
    // ...
    success: function(data) {
         lookup(data.project_name_for_instance, function() {
              // match
         });
    },
    // ...
});

Upvotes: 1

Related Questions