renny
renny

Reputation: 203

Get input element inside <tr> with based on data-attribute value

I have the following code:

<tr class="my-field" data-name="background_colour" data-type="color_picker">
    <td class="my-input">
        <div class="my-color_picker">
              <input type="text" class="wp-color-picker">
    </td>
</tr>

I need to get that input text element with class="wp-color-picker".

I can do this with $('input.wp-color-picker'), but that will get all input elements with class=wp-color-picker. I only want to get those elements that are inside a tr with data-name='background_colour'.

Hope that makes sense.

Upvotes: 1

Views: 1573

Answers (3)

Optimus
Optimus

Reputation: 2210

try this

$("tr[data-name='background_colour'] .wp-color-picker")

Upvotes: 0

Dhiraj
Dhiraj

Reputation: 33618

You can do this

$('tr[data-name="background_colour"] input.wp-color-picker')

Example:

alert($('tr[data-name="background_colour"] input.wp-color-picker').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="my-field" data-name="background_colour" data-type="color_picker">
    <td class="my-input">
        <div class="my-color_picker">
              <input type="text" class="wp-color-picker" value="hello world">
    </td>
</tr>
  </table>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Use a descendant selector to combine those to needs

$('tr[data-name="background_colour"] input.wp-color-picker')

Here tr[data-name="background_colour"] will find the tr you are looking for then the descendant selector along with the input selector(input.wp-color-picker) will find the target element.

Upvotes: 4

Related Questions