Obsivus
Obsivus

Reputation: 8359

Array problems with Jquery

I have a Jquery code that is following:

var selectedQuestions = $("#SelectedQuestions");
var selectedCustomQuestions = $("#SelectedCustomQuestions");
var currentIds = new Array();
var currentText = new Array();

$("#CustomPickedTable td[data-question-id]").each(function () {
    var clickedId = $(this).attr("data-question-id");
    currentIds.push(clickedId);

    $('#CustomPickedTable tr').each(function () {
        var ClickedText= $(this).find("td[data-attr-id]:first").html();
        currentText.push(ClickedText);
    });
});

selectedCustomQuestions.val(currentText.join("|"));
selectedQuestions.val(currentIds.join(","));

$("form").submit();
}

I have two types of TD in my table that is following:

<td data-question-id="7">test</td>

and

<td data-attr-id="5">test</td>

I want to be able to sort em into different hiddenfields these are my hiddenfields:

@Html.HiddenFor(model => model.SelectedCustomQuestions, new { @id = "SelectedCustomQuestions" }) 
@Html.HiddenFor(model => model.SelectedQuestions, new { @id = "SelectedQuestions" })

my Jquery code works when it comes to fill my array with CurrentIds but with currentText I get problems, if I have two <td data-attr-id="5">test</td> in my table they get duplicated in my array list and my array lenght is 7-10 which is weird. The CurrentText should only have 2 length and its not. How can I fix this?

Example on the problem.

I have this following inside my table:

<td data-attr-id="5">aaaa</td>
<td data-attr-id="5">ddd</td>
<td data-question-id="5">test</td>
<td data-question-id="15">test</td>

and this is what happens when i debug my jquery code

example

Thanks in advance!

Upvotes: 0

Views: 133

Answers (2)

Willem D&#39;Haeseleer
Willem D&#39;Haeseleer

Reputation: 20200

You seem to be using "td[data-attr-id]:first" in your find selector, but you are "using data-attri-id" in your html, notice the added i.

edit : You might also wanna use

var currentIds = [];
var currentText = [];

instead of :

var currentIds = new Array();
var currentText = new Array();

see: What does [] mean in JavaScript?

Upvotes: 0

naim shaikh
naim shaikh

Reputation: 1111

Just try this one with slight modification.

var selectedQuestions = $("#SelectedQuestions");
    var selectedCustomQuestions = $("#SelectedCustomQuestions");
    var currentIds = new Array();
    var currentText = new Array();

    $("#CustomPickedTable td[data-question-id]").each(function () {
        var clickedId = $(this).attr("data-question-id");
        currentIds.push(clickedId);
    });
    $('#CustomPickedTable td[data-attr-id]').each(function () {
        var ClickedText = $(this).html();
        currentText.push(ClickedText);
    });

    selectedCustomQuestions.val(currentText.join("|"));
    selectedQuestions.val(currentIds.join(","));

Upvotes: 1

Related Questions