1

i need to know if this is possible and how....

I have a series of linkk

< a href="#" id="hello" > HELLO < /a >

< a href="#" id="welcome" > welcome < /a >

< a href="#" id="start" > start < /a >

< a href="#" id="finish" > finish < /a >

what i want to do is as i click on the link I wish to add the id value to an array(words). so if i click all the 4 links my array should have hello, welcome,start,finish. Consequently if that is not possible can you concatenate them to a single variable on each click without destroying the previous data in the variable..words=(hello|welcome|start|finish).

any help is appreciated.

thanks andy

3 Answers 3

1

so if your js file looks like this (and jquery has been included on the page)

var ClickedLinks = [];
$(function () {
    $('a').click(function () {
        var id = $(this).attr('id');
        if ($.inArray(id, ClickedLinks) == -1) {
            ClickedLinks.push(id);
        }
    });
});

This will check the array and NOT add it again.

EDIT: Fixed $.inArray returning a position, rather than a boolean (as I incorrectly assumed)

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

10 Comments

@alastair new thing learnt from your code , inArrya , i wrote my function uncessaryly , thanks + 1 for you
@gov: it's a really convenient little function :)
var ClickedLinks = []; $(function () { $('a').click(function () { var id = $(this).attr('id'); if (!$.inArray(id, ClickedLinks)) { ClickedLinks.push(id); } }); $.each(ClickedLinks, function(key, value) { alert(key) }); }); < a href="#" id="hello" class="examle"> HELLO < /a >
var ClickedLinks = []; $(function () { $('a').click(function () { var id = $(this).attr('id'); if (!$.inArray(id, ClickedLinks)) { ClickedLinks.push(id); } }); $.each(ClickedLinks, function(key, value) { alert(key) }); }); < a href="#" id="hello" class="examle"> HELLO < /a > it didnt work...as in no error but no output either
I made a couple of mistakes, as well as where you placed you checking code: see jsfiddle.net/cPUKr/3
|
0
var myVar = Array()

$('a').click(function(){
    myVar[] = $(this).attr('id');
})

1 Comment

you have add a check condition if it already exists//// alastair code takes care of it.
0

@andy first give a class to all hrefs//

  < a href="#" id="hello" class="examle"> HELLO < /a >

    var arrayResults=new Array();

    $('.examle').click(function() {
        var textval= $(this).attr('id');;// do a check if it already exists
       if(!exitsts){ //write a function to check if already exists..
       arrayResults.push(textval);
       }
    });

finally arrayResults will have all the values

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.