0

So I got this html select which is empty, I want the html to be included from js file, but it's simply not injecting... check it out

<select id="province" name="province"></select>

$("select").change(function(){
        $( "select option:selected").each(function(){
            if($(this).val()=="canada") {

                $('#province').innerHTML = '<option value="">Please select your province...</option>';

                console.log('Canada baby!');
            }
        });
    }).change();
7
  • Is the DOM loaded at the time of injecting? Commented May 27, 2015 at 21:19
  • 3
    If I understand the question correctly, if the select is empty, change will not be triggered Commented May 27, 2015 at 21:21
  • you mean by wrapping the function in a .ready ? Then yesss Commented May 27, 2015 at 21:22
  • @DhirajBodicherla He’s got a .change() at the end though which should work in jQuery. I think the main issue is that there’s no $("select option:selected"), thus there’s nothing to iterate over. Except if there are other select elements… I don’t know about that. Commented May 27, 2015 at 21:25
  • But even if there are multiple selects, $(this).val()=="canada" can never be true as far as I know because there is no value from a selected option because there is no option. Commented May 27, 2015 at 21:27

1 Answer 1

1

I would think you need two select lists. One for country and one for province in case Canada is selected.

<select id="country" name="country">
    <option value="usa">USA</option>
    <option value="canada">Canada</option>
</select>
<div id="state"></div>

$(function(){
$("#country option").click(function(){

        $(this).each(function(){
            if($(this).val()=="canada") {
                $("#state").html('<select id="province" name="province"><option value="">Please select your province...</option></select>');
                console.log('Canada baby!');
            }
        });
    });
});

https://jsfiddle.net/qcmfwqjo/

Sign up to request clarification or add additional context in comments.

Comments

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.