techutopia
Total posts: 202
17 Нояб 2016 11:14

Hi all,

I'm trying to use JQuery to dynamically change a cobalt select field.

This is the HTML code for select box generated by cobalt ...

<select name="jform[fields][21]" class="elements-list cobalt-chosen-21" 
    id="form_field_list_21" style="max-width: 450px" aria-invalid="false">
    <option value="">Select</option>
    <option value="1501">1501</option>
    <option value="1502">1502</option>
    <option value="1503">1503</option>
</select>

And here is my attempt to clear and then add data ...

$('#form_field_list_21').empty();
$('#form_field_list_21').append($('<option>', {
    value: 0,
    text: 'Please Select'
}));

I keep getting the error "Uncaught TypeError: Cannot read property 'empty' of null".

I have got this working outside of cobalt with plain HTML files, but I'm not quite sure why it's not working in a cobalt template.

Would it be an out of date jquery include? I see "/media/jui/js/jquery.min.js" at the top of the file.

Thanks in advance,

Dale.

Последние изменения: 21 Нояб 2016


techutopia
Total posts: 202
17 Нояб 2016 11:48

Addition:

I notice that if I include:

<script src="/ https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js "></script>

... the scripting works ok to change the select boxes, but Google map field fails.

Ta.

Dale.


Sergey
Total posts: 13,748
21 Нояб 2016 15:42

First take a time and edit your topic and see how i formated large blocks of code and learn how to insert it using markdown.

Read this also. this helps you to create correct jQuery code.

Your error is because $ is not a jQuery. Because after jQuery mootools is loaded. So you have to embrace your code in this.

(function($){
    // your code here
}(jQuery));

So you will get something like this.

<script>
    (function($){

        $('#form_field_list_21')
            .find('option')
            .remove()
            .end()
            .append('<option value="whatever">text</option>')
            .val('whatever');

    }(jQuery));
</script>
Работает на Cobalt