1

I have the following HTML that can appear but only one at a time:

<a id="menuRange" class="button" href="#">1 - 100</a>
<a id="menuRange" class="button" href="#">101 - 200</a>
<a id="menuRange" class="button" href="#">201 - 300</a>

and I used this code to get the range:

var $field = $('#menuRange');
var nums = $field.text().split('-').map(function (a) {
    return parseInt(a, 10) + d * 100
});

Now I want to change the HTML into:

<a id="menuRange" class="button" href="#">Lines 1 - 100</a>
<a id="menuRange" class="button" href="#">Lines 101 - 200</a>
<a id="menuRange" class="button" href="#">Lines 201 - 300</a>

How can I make it so I still get nums data like before. In other words, how can I make it ignore the word "Lines " as though it was not there?

4
  • 1
    You should consider using unique ID for different elements. Commented Jun 25, 2012 at 11:10
  • One only of the lines will appear in a page at once. thanks Commented Jun 25, 2012 at 11:12
  • 1
    @Joy there is a hidden gotcha that apparently only one of those elements is on the page at a time Commented Jun 25, 2012 at 11:13
  • @Gemma, Then it's fine, I didn't get that. :) Commented Jun 25, 2012 at 11:14

2 Answers 2

5

Just put a .substring() after .text():

var nums = $field.text().substring(6).split('-')...

i.e. just cut out the first 6 characters of the returned text.

Alternatively, if the prefix isn't always there:

var nums = $field.text().replace(/^Lines /, '').split('-')
Sign up to request clarification or add additional context in comments.

Comments

2

If you want complete freedom in what you put in the anchors' content move the value used by your code for calculations into an attribute. Then you can change your mind about the content the user sees without needing to change your JS code at all:

<a id="menuRange" class="button" href="#" data-lines="1-100">Lines 1 - 100</a>
<a id="menuRange" class="button" href="#" data-lines="101-200">Anything here</a>
<a id="menuRange" class="button" href="#" data-lines="201-300">still works</a>

var $field = $('#menuRange');
var nums = $field.attr("data-lines").split('-').map(function (a) {
    return parseInt(a, 10) + d * 100
});

You could opt for separate attributes for the min and max:

<a id="menuRange" class="button" href="#" data-min="1" data-max="100">Lines 1 - 100</a>

And then you could retrieve them separately rather than splitting out from a single string:

var min = $field.attr("data-min"),  // to get it as a string
    max = $field.attr("data-max");  // use .attr()
// OR
var min = $field.data("min"),       // to have jQuery automatically convert
    max = $field.data("max");       // it to a number use .data()

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.