Cold_Class
Cold_Class

Reputation: 3484

Change event fired twice on changing radio group manually with jQuery

When selecting "A&L" in the select, the radio group is hidden and its value is set to "n".
I try to trigger the change event so that the "Hello"-div disappears too, but it doesn't work correctly - on debugging I noticed that the change event is executed twice - the first time correctly and then again with the value "j".

What's my mistake?

Here's the full code: https://jsfiddle.net/95Lxroqy/

After I looked through some other questions it seemed to me that .val(['n']).change(); (line 24) should have worked -
but it seems like I'm still missing something.

// find elements
var banner = $("#banner-message");
var button = $("#place");
var langs = $("#langs");
var trans = $("#trans");
var radioGroup = $("input[type=radio][name=translate]");
var div = $("#dynamic");

radioGroup.change(function() {
    if (this.value === 'n') {
       div.hide();
    }
    else if (this.value === 'j') {
        div.show();
    }
});

// handle click and add class
button.change(function(event){
	var al = button.val() === "al";
	if(al){
  langs.show();
  trans.hide();
  radioGroup.val(['n']).change();
  }else{
  trans.show();
  langs.hide();
  }
}).change();
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
   <select id="place">
  <option value="in">Internal</option>
  <option value="al">A&L</option>
</select> 
   <select id="langs">
  <option value="volvo">German</option>
  <option value="saab">English</option>
</select> 
<fieldset id="trans">
    <input type="radio" id="n" name="translate" value="n">
    <label for="n"> Nein</label> 
    <input type="radio" id="j" name="translate" value="j">
    <label for="j"> Ja</label>
  </fieldset>
  <div id="dynamic">
  Hello
  </div>
</div>

Upvotes: 1

Views: 249

Answers (1)

Mamun
Mamun

Reputation: 68933

val() get/set the value of the element. Your code matches all the options exist in the collection variable, it does not match the specific element you are looking for. You can target the parent element from which you can find the the specific element by using attribute selector.

Try

radioGroup.parent().find('[value=n]').change();

Update: The more feasible solution is using the filter()

radioGroup.filter('[value=n]').change();

Upvotes: 1

Related Questions