开发者

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

开发者 https://www.devze.com 2023-02-04 12:24 出处:网络
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

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 开发者_如何学Cfrom 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']; ?>


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);


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
         });
    },
    // ...
});


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...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号