简体   繁体   中英

Jquery check if element exist and if conditon

I have code like this:

<?php if ($this->session->userdata('permission') == 4 || $this->session->userdata('permission') == 3) : ?>
            <select name="caffe" id="caffe">
                <?php foreach($caffe as $key) : ?>
                <option value="<?php echo $key['id_caffe'] ?>"><?php echo $key['name'] ?></option>
                <?php endforeach; ?>
            </select>
            <div id="gll_select">
                <script>
                 var caffe = $("#caffe").val();
                 var cff_name = $("#caffe option:first").text();
                 $("#gll_select").load("<?php echo base_url() ?>form/galleries", {id : caffe}, function(){                 
                          $("#gll").on('change', function(){
            var cff_name  = $("#caffe option:selected").text();
            get_gallery(cff_name);
            console.log(cff_name);
        }); 
                 });  
                </script>
            </div>

            <?php else : ?>

            <input type="hidden" name="caffe_name" id="caffe_name" value="<?php echo $caffe_name ?>" />
            <input type="hidden" name="caffe_id" id="caffe_id" value="<?php  if(isset($caffe_id)) echo $caffe_id; ?>" />
            <div id="gll_select">
                <?php if (isset($gallery)) : ?>
            <select name="gll" id="gll">
        <?php foreach ($gallery as $key) : ?>
            <option value="<?php echo $key['id_gallery'] . " " . $key['name'] ?>"><?php echo $key['name'] ?></option>
        <?php endforeach; ?>
            <?php endif; ?>
            </select>
            </div>

            <?php endif ?> 

and jquery code like this:

if ($("#caffe".length)){var cff_name = $("#caffe option:first").text(); }
    else{var cff_name = $("#caffe_name").val();}

Problem is following - the first statement is always true ( #caffe will not exist if PHP IF statement is FALSE ). What seems to be the problem?

Should be

if ($("#caffe").length) { ... }

Your code:

if ($("#caffe".length)) { ... }

is getting the length of a string constant and passing that to jQuery. You always get a non-null result from a call to the jQuery main function ($), so the result of casting that to boolean as part of the if statement is always true.

When you instead test the .length property of the returned jQuery object made from a search for the selector, you're checking to see whether that number is non-zero.

$("#caffe".length)更改$("#caffe".length) $("#caffe").length

I think I see the problem...

if ($("#caffe").length){var cff_name = $("#caffe option:first").text(); }

.length is not part of the selector, it's an attribute of the wrapped set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM