1 Replies - 162 Views - Last Post: 19 May 2017 - 10:20 AM

#1 dday9  Icon User is offline

  • D.I.C Regular

Reputation: 94
  • View blog
  • Posts: 495
  • Joined: 17-April 13

Get Radio by Name and If Statement Issue

Posted 19 May 2017 - 10:11 AM

I'm having difficulties with my jquery where I have three radio buttons, and I want to check if the first radio is checked, the last radio is checked, or the middle radio is checked. So this is the code that I'm using:
if($('input[name="step1"]:first') === $('input[name="step1"]:checked')) {
  setIframe(generateTemplate1);
} else if($('input[name="step1"]:last') === $('input[name="step1"]:checked')) {
  //todo: create template for #3
} else {
  setIframe(generateTemplate2);
}


Where the markup of the radio buttons look like this:
<input type="radio" name="step1" checked />
<input type="radio" name="step1" />
<input type="radio" name="step1" />


The issue that I am having is that no matter which radio is checked, it will always execute the Else statement. Why is that?

Edit - This is the second time that I fixed my issue shortly after I posted the question... I was able to fix the code by using the is jquery function:
if($('input[name="step1"]:first').is(':checked')) {
  setIframe(generateTemplate1);
} else if($('input[name="step1"]:last').is(':checked')) {
  //todo: create template for #3
} else {
  setIframe(generateTemplate2);
}

This post has been edited by dday9: 19 May 2017 - 10:16 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Get Radio by Name and If Statement Issue

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4129
  • View blog
  • Posts: 13,024
  • Joined: 08-June 10

Re: Get Radio by Name and If Statement Issue

Posted 19 May 2017 - 10:20 AM

View Postdday9, on 19 May 2017 - 07:11 PM, said:

The issue that I am having is that no matter which radio is checked, it will always execute the Else statement. Why is that?


because of the strict comparison, which would only evaluate to true, if you compared identical objects. but since you create two separate jQuery objects, they can never refer to the same Java­Script object.

var a = {};
var b = {};
var c = a; // creating a reference

a === b // false

a === c // true


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1