skip to Main Content

We have a JQUERY challenge in that we need to find checkboxes in a JQuery SELECTOR by matching on part of a string that is in the OnClick Attribute.
If we were matching on a NAME or ID, it would be very easy, but the checkboxes are created by our application that creates the HTML as follows.

  <input type="checkbox"  name="alternate" value="" onClick="moreStudyDetFunctions.setValue(moreStudyDetFunctions.formObj,24242,1)">

In the old version of Jquery, we were able to find this
jQuery("input:checkbox[onclick*=,24242]").attr("checked")

The current version of JQuery seems not to support this and requires me to change my code.

I can get the OnClick Attribute as follows:
$(‘input:checkbox’).attr(‘onClick’)

But I do not know how to limit the checkbox selector to only match on ‘24242’ found inside the onClick attribute

The :contains command does not seem to apply to checkboxes.
This will not work $(‘input:checkbox’).contains(‘24242’)

Perhaps $(‘input:checkbox’).filter ?

2

Answers


  1. Chosen as BEST ANSWER

    Yes, I need to use a .filter, but since its a string search Ill need an anonomous function.

    $(document).ready(function(){
      alert($('input:checkbox').filter(function() {
                    return $('input:checkbox').attr('onClick').indexOf('24242') > 0
                }).length);
    });
    
        <input type="checkbox"  name="alternate" value="" checked   onClick="moreStudyDetFunctions.setValue(moreStudyDetFunctions.formObj,24242,1)">
      
    

  2. You can use indexOf, if doesn’t exist it will print -1 else index of the first occurrence

    console.log($('input:checkbox').attr('onClick').indexOf('24242'))
    //if -1 not found else found
    
    //example
    if ($('input:checkbox').attr('onClick').indexOf('24242') > -1) {
      console.log(`found at index ${$('input:checkbox').attr('onClick').indexOf('24242')}`);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="alternate" value="" onClick="moreStudyDetFunctions.setValue(moreStudyDetFunctions.formObj,24242,1)">

    Reference:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search