开发者

javascript for…in + if-test (inside of a switch inside of a form)

开发者 https://www.devze.com 2023-03-31 19:18 出处:网络
I have a question in a form asking if you\'ve used alcohol, drugs, both, neither, \"777\", \"999\". alcohol : question 2; drugs : question 3; both : questions 2 + 3; neither or \"777\" or \"999\" :

I have a question in a form asking if you've used alcohol, drugs, both, neither, "777", "999".

alcohol : question 2; drugs : question 3; both : questions 2 + 3; neither or "777" or "999" : question 4.

I have a jquery change() listen setup (and is working), and I have a switch statement setup and is mostly working, except for neither||"777"||"999". Inside case "neither…" I have an array vices and a for…in loop. My assumption is that for…in functions like/similarly to php's foreach.

I need to detect if the question is not already inactive before I hide it and set its value to not applicable (so I know it was purposeful rather than leaving it empty).

case "neither" || "777" || "999":
    var vices = new Array('alcohol','drugs');
    for ( vice in vices ) {
        if ( $("ul#vice").hasClass("inactive") == false ) {
            $("ul#vice").append('<input name="'+vice+'" type="radio" value="not applicable" checked="checked" />');
            $("ul#vice").delay(250).queue( function() {$(this).addClass("inactive");queue()} );
        }
    }

I think the problem has something to do with the $("ul#vice"), but I'm not sure. (I've tried $("ul#"+vice), but that didn't work either).

A question stuff looks like:

.inactive{display:none; z-index:-5}

#

<ul id="alcohol" class="inactive">How many alcoholic drinks do you have?
    <li><input name="alcohol" type="text" maxlength="2" /><span id="alcohol" class="inactive"></span></li>
    <li><input name="alcohol" type="radio" value="777" />Don't know</li>
    <li><input name="alcohol" type="radio" value="999" />Prefer to not answer</li>
    <input name="alcohol" type="radio" value="not applicable" ch开发者_运维技巧ecked="checked" />
</ul>

Thanks in advance!


you are incorrect on your assumption that for...in is similar to foreach...

my previous answer. JavaScript Loops: for...in vs for


Well, a quick search would tell you how for...in actually does work: http://w3schools.com/js/js_loop_for_in.asp

You need:

for (i=0; i<vices.length; i++) { 
    var vice = vices[i]; ...
} 

And since that is a variable, $("ul#" + vice) is in fact correct.

0

精彩评论

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

关注公众号