简体   繁体   中英

Why is this javascript not working - select box if

I have this code on my site. The idea is to hide a specific class when a specific select box value is selected.

This is my code

$(document).ready(function(){
var txt = 'Marketing';
$("div.ginput_container select#input_3_1 option").each(function(){
    if($(this).val()==txt){
        $('.mar').hide();    
    }

   });
});

The result I'm getting is .mar class being hidden as soon as the page is loaded. I can't see the error, I have also tryied with

var num = 1

but I have the same issue.

$(document).ready(function() {
    var txt = 'Marketing';
    $("#input_3_1").change(function () {
        if ( this.value == txt ) $('.mar').hide();
    });
});

Here's the fiddle: http://jsfiddle.net/9Cyxh/


If you want to show $('.mar') when a different option is selected, use toggle instead:

$('.mar').toggle( this.value != txt );

Here's the fiddle: http://jsfiddle.net/9Cyxh/1/


If you want this to also run on page load (before an option is manually selected), trigger the change event:

$(document).ready(function() {
    var txt = 'Marketing';
    $("#input_3_1").change(function () {
        $('.mar').toggle( this.value != txt );
    }).change();
});​

Here's the fiddle: http://jsfiddle.net/9Cyxh/2/

You don't need the loop in the first place

Attach your select to the change() event handler and that should be it..

$(document).ready(function(){

     $("select#input_3_1").on('change', function() {
         var txt = 'Marketing';
         if(this.value === txt){
             $('.mar').hide();    
        };

     }).change()
});

If you only want to hide ".mar" class when the value is changed and it equals "Marketing" try

$("#input_3_1").change( function() {
    if( $(this).val().toUpperCase() === "MARKETING" ) {
        $(".mar").hide();
    }
});

Demo here

$("#input_3_1").change(function(){
  if ($("#input_3_1").val()=='Marketing'){
    $(".mar").hide();
  }
});

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