2

I want to get the count of data-fields in HTML form using JavaScript or jQuery

<input data-table="assessment_rating" data-field="x_PERFORMANCE_MEASURE" 
name="x1_PERFORMANCE_MEASURE" id="x1_PERFORMANCE_MEASURE" 
placeholder="Performance Measure" 
value="" class="form-control" type="text">

I have 10 input fields with same name data-field = "x_PERFORMANCE_MEASURE".

I want to get the count dynamically using jQuery or JavaScript.

I used below code

var x = $('#ewTableHeaderCell .x_PERFORMANCE_MEASURE').length;
alert (x);

I am not getting with the above script... please help me out.

1
  • got the solution...Thnx Commented Oct 6, 2017 at 12:08

2 Answers 2

4

You need to use another selector: look at the example.

//look
var x = $('input[data-field="x_PERFORMANCE_MEASURE"]').length;
alert (x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input data-table="assessment_rating" data-field="x_PERFORMANCE_MEASURE" 
name="x1_PERFORMANCE_MEASURE" id="x1_PERFORMANCE_MEASURE" 
placeholder="Performance Measure" 
value="" class="form-control" type="text">

Of course since your example didn't include the original #ewTableHeaderCell table header cell, I've omitted it out of my snippet. But you get the idea. in your case it is:

var x = $('#ewTableHeaderCell input[data-field="x_PERFORMANCE_MEASURE"]').length;

Since uses css selectors under the hood, click the link to learn more.

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

6 Comments

Your selector will select every input that has data-field no matter where it's placed (I mean in parent container).
@Justinas, I generalized it, because of lacking HTML in the OP's question and commented it in my answer.
if i have select in place of input?how do i replace the code?
replace input with select. Read the documentation through the provided link. It is really useful. You should get to know CSS selectors.
is this correct $('select[data-field="x_PERFORMANCE_MEASURE"]').length;?
|
4

Since x_PERFORMANCE_MEASURE is not a class, you can't use class selector .

Select it using attribute selector:

$(document).ready(function() {
  alert($('#ewTableHeaderCell [data-field="x_PERFORMANCE_MEASURE"]').length);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="ewTableHeaderCell">
<input data-table="assessment_rating" data-field="x_PERFORMANCE_MEASURE" 
name="x1_PERFORMANCE_MEASURE" id="x1_PERFORMANCE_MEASURE" 
placeholder="Performance Measure" 
value="" class="form-control" type="text">
</span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.