0

I'm still new to jQuery and stuck trying to figure this one out, hope someone can help. I have this jQuery code that needs to pass different values depending on the clicked element. Each element created has a unique number in it's ID (which is needed). If I manually change the jQuery code to a specific ID and call, for example:

http://mysite/examplepost?effect=113

This will work. But I need to have $('#div- ...different numbers here...') to be able to handle multiple elements on the same page. I already have the PHP side producing different values using:

if($_GET['effect'] == $id){

I just need this to work with ajax so that it doesn't reload the page.

Example:

$('#div-113').on('click', function() {

    var dataString = 'effect=113';  

        jQuery.ajax(
            {
            type:'GET',
            url:'?',
            data: dataString,
            success: function(data){
                alert('Works');         
            }
          }
        );

      });

Any help would be appreciated.

0

1 Answer 1

2

I would give all your divs a common classname (i.e. myClickableDiv) and also a specific data-id.

This way you can target all your divs by that common classname, rather than having to figure it out depending on how the id is formed. The data-id allows you to only provide very specific information to the click handler (like an integer), without having to parse the id.

HTML:

<div class=".myClickableDiv" id="div-XXX" data-id="XXX">My Div</div>

JS:

$('.myClickableDiv').on('click', function() {

    var dataString = $(this).attr('data-id');  

    jQuery.ajax({...});

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.