0

I am trying to use the django's jQuery library as follows. domain is a select field with id =id_domain on the form with form id = emailaccount_form. These ids are auto generated by django.

In the static file test.js code for jquery is as follows:

<script type="text/javascript">
(function($){
    $(document).ready(function($){
    var form = $("emailaccount_form");
    var domain = $("id_domain");
    //number of domains include null as 1 value
    alert(domain.length);
    if ((!domain[0].value) && (domain.length > 1)){ 
        if (domain.length == 2){ 
        //select domain by default as it is the only available choice
        domain.selectedIndex = 1;
        alert('Domain ' + domain.value);
        }
    }
    });
})(django.jQuery);
</script>

On execution, I find that the domain.length value is 0, whereas there are actually 2 options in the select choices. Why? domain if displayed as alert(domain) displays object Object and not as object HTMLSelectElement.

Consider the 2nd case a javascript as below where I get the expected results:

<script type="text/javascript">
   var domain = document.getElementById("{{ adminform.form.domain.auto_id }}");
   alert(domain);
   alert ("Number of domains: " + (domain.length-1));
   </script>

What is wrong with the django.jQuery. Can anyone guide? Also how do I get rid of the 1st blank value of the Select box as one of the options. I want to use django.jQuery only!

1 Answer 1

1

Are you simply missing a hash mark? Remember jQuery needs one out front to select ID's, whereas JavaScript's native getElementById does not.

var form = $("#emailaccount_form");
var domain = $("#id_domain");
Sign up to request clarification or add additional context in comments.

5 Comments

Lol - such a simple answer and yet correct (I think) :) Good catch
Thanx just my 2nd day at jQuery
also how to set the selectedIndex property in case there is only 1 choice in the select dropdown in jquery
I think you can use $('select').val('text value of dropdown here') ? but to be honest I haven't used that trick in some time.
I used $('#select')[0].selectedIndex = "some integer value" it worked great. Thanx bahoo!

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.