0

I need to add a number to the end of each javascript variable and JQuery element.

Here's my code:

$("#insert1").click(function(){
    var collegeId1=$("#collegeId1").val();
     $.post('insert.php', {collegeId: collegeId1});
    return false;
});

$("#insert2").click(function(){
    var collegeId2=$("#collegeId2").val();
    $.post('insert.php', {collegeId: collegeId2});
    return false;
});

... and so on. I need to continue adding numbers to the end of each element and variable (i.e. collegeId[number] and ("#insert[number]"). I've tried looping, .append, +, etc and nothing seems to be working.

Any help would be greatly appreciated!

3
  • It is not possible in javascript like php $$var; U should use array instead variable name Commented Oct 3, 2013 at 4:56
  • 1
    Please post the html also. Commented Oct 3, 2013 at 4:56
  • it seems you are making it more complex.. post your html code. Commented Oct 3, 2013 at 5:04

2 Answers 2

6

Correct way to do this is using "data"-fields You have buttons like this:

<button data-id="1" class="insert">

And just one function for all this shit:

$('.insert').click(function(){
    var id = $(this).data('id');
    var collegeId = $('#collegeId' + id).val();
    $.post('insert.php', {collegeId: collegeId});
    return false;
});

Also you can store collegeId right in the button-tag (dont write "data-collegeId" since data-fields don't support uppercase):

<button data-collegeid="1" class="insert">

then you get it in 1 line:

var collegeId = $(this).data('collegeid');
Sign up to request clarification or add additional context in comments.

Comments

0

If you must work with the markup you've already got, try this...

$('[id^="insert"]').filter(function() {
    return /insert\d+$/.test(this.id); // filter to make sure the id matches /insert\d+/
}).on('click', function(e) {
    e.preventDefault();
    var i = /\d+$/.exec(this.id)[0], // fetch index from id
        collegeId = $('#collegeId' + i).val();
    $.post('insert.php', {collegeId: collegeId});
})';

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.