João Alves
João Alves

Reputation: 1941

jquery on click event input

Imagine this: i have multiple divs with attr "data-question-id" and inside this divs i have one or more inputs that may or may not have a attr "has-next-question". See the example below:

<div data-question-id="5">
<input type="radio" has-next-question="true" value="2"> test1
<input type="radio" value="3"> test2
</div>

<div data-question-id="6">
<input type="radio" has-next-question="true" value="5"> test3
<input type="radio" has-next-question="true" value="7"> test4
</div>

As you can see in the first div i have two inputs, but one doesnt have the attr "has-next-question". My question is, how can i bind a click event on the input that have a parent div with attr "data-question-id" and this div have at least an input with attr "has-next-question".

I already accomplish this:

$(document).on('click', 'div[data-question-id] input', function(e) {
          alert('click');
});

any help? thanks guys

Edit: Changed attr "has-next-question" because its a invalid html attribute.

Imagine this: if i click in "test1" it should trigger the event, but if i click in "test2" it should too, because the parent div with attr "data-question-id" have at least one input with attr "has-next-question", corresponding to the "test1". If there is none input with attr "has-next-question" in the parent div, the event shouldnt trigger.

Upvotes: 4

Views: 190

Answers (3)

Jashwant
Jashwant

Reputation: 29005

Its not correct html. has-next-question is not a valid attribute.

But this should work,

$(document).on('click', 'div[data-question-id] input[has-next-question]', function(e) {
          alert('click');
});

Edit: (after change in original question),

No, you cannot make a selector out of that. jQuery uses CSS selector and they do not work from child to parent.

However, you can do something like this,

$(document).on('click', 'div[data-question-id] input', function(e) {
       if($(this).parent().find('[has-next-question]').length === 0 ) return;

       // Other code which needs to be executed.
});

i.e. if parent does not have child with [has-next-question] attribute, then comes out from the function.

Upvotes: 1

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

Just extend your selector:

$(document).on('click', "div[data-question-id] input[has-next-question='true']", function(e) {
          alert('click');
});

Upvotes: 1

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You did it for the div, so repeat it.

div[data-question-id] input[has-next-question]

Demo

Upvotes: 3

Related Questions