user1231561
user1231561

Reputation: 3359

Jquery selector string from array doesn't seem to get recognized

I have multiple divs id="p-1", id="p-2", where each div contains a different set of radio buttons.

When clicking the submit button, I check if a radio button is selected and proceed accordingly.

MY ISSUE: Regardsless of selecting a radio button, I am stuck at alert('Nothing is checked!'); - I suspect if (!$(pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked").val() / the selector from the array being the issue, since hardcoding the div works fine like the following: if (!$("#p-1 input[n..... - any ideas?

JS:

var pArrayDefaultIndex = 0;
var pArray = ["p-1", "p-2", "p-3", "p-4"];

$('.submit-btn').click(function(e){
    if (!$(pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked").val()) {
      //alert('Nothing is checked!');
    }
    else {
      //alert('One of the radio buttons is checked!');
      pArrayDefaultIndex++; //count up to check radio in next container
    }
});

HTML:

<div class="p-item" id="p-1">
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      text
    </label>
  </div>
  <div class="radio">
    <label>
    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
      text
    </label>
  </div>
  <button class="submit-btn">Submit</button>
</div> <!-- p-1 -->

<div class="p-item" id="p-2">
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      text
    </label>
  </div>
  <div class="radio">
    <label>
    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
      text
    </label>
  </div>
  <button class="submit-btn">Submit</button>
</div> <!-- p-2 -->

Upvotes: 0

Views: 73

Answers (2)

Jonathon
Jonathon

Reputation: 16283

You are missing the # from your selector

Also, you will probably want to put your code in a loop since you seem to be incrementing pArrayDefaultIndex but your code will only be called once. I'd personally recommend putting a class on them rather than an ID and using something like...

$(".yourclass").each(function(){
    // Find your input element in relation to this object
});

This will execute objects on all elements that match that selector, i.e. all elements that have the class yourclass

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are missing the id selector(#) - p-1 is the id of the wrapper element so you need to use it along with an id selector.

$('#' + pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked")

Another way to write the if condition is

if (!$('#'+ pArray[pArrayIndexCount]+" input[name='optionsRadios']").is(':checked')) {

Upvotes: 3

Related Questions