Как получить значения полей ввода нескольких классов с помощью jquery

Мой желаемый результат для приведенного ниже кода должен быть:

a-b-c-d,e-f-g-h,i-j-k-l

Обратите внимание на запятую вместо - после d и h.

Но приведенный ниже код приводит к

a-b-c-d-e-f-g-h-i-j-k-l,a-b-c-d-e-f-g-h-i-j-k-l,a-b-c-d-e-f-g-h-i-j-k-l,

Я пытался искать через переполнение стека, но не сталкивался с таким вопросом. Может ли кто-нибудь помочь мне, пожалуйста, не отмечайте этот вопрос как повторяющийся.

<div class = "test1 yes">
 <input type = "text" class = "xyz" value = "a" />
 <input type = "text" class = "xyz"  value = "b" />
 <input type = "text" class = "xyz" value = "c" />
 <input type = "text" class = "xyz" value = "d" />
</div>

<div class = "test2 yes">
 <input type = "text" class = "xyz" value = "e" />
 <input type = "text" class = "xyz" value = "f" />
 <input type = "text" class = "xyz" value = "g" />
 <input type = "text" class = "xyz" value = "h" />
</div>

<div class = "test3 yes">
 <input type = "text" class = "xyz" value = "i" />
 <input type = "text" class = "xyz" value = "j" />
 <input type = "text" class = "xyz" value = "k" />
 <input type = "text" class = "xyz" value = "l" />
</div>

<input type = "submit" class='submit'>

  <p class='count'></p> 
 <p class='test'></p> 

<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
    $('.submit').click(function(){
        var count = $('.yes').length
        $('.count').text(count);
       
        var texts = "";
        var i = 0;
    while (i < count) {
        texts += $(".xyz").map(function() { return this.value; })
                                   .get().join('-') + ",";
        i++;
    }

    $('.test').text(texts);    

    });
    

</script>
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
0
0
23
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Вместо

var texts = "";
var i = 0;
while (i < count) {
    texts += $(".xyz").map(function() { return this.value; })
                               .get().join('-') + ",";
    i++;
}

просто пиши

var texts = ''
$('.yes').each(function() {
  textx += $(this).children('.xyz')
                  .map(function() { return this.value; })
                  .get().join('-') + ','
})

Это не генерирует желаемый результат, т. е. a-b-c-d, e-f-g-h, i-j-k-l, ваш код генерирует a-b-c-d-e-f-g-h-j-k-l

vamshi g 20.03.2022 15:14

Это произошло из-за вашего +=, что означает, что он будет добавлять результат на каждой итерации. Мое решение состоит в том, чтобы написать только =.

<div class = "test1 yes">
 <input type = "text" class = "xyz" value = "a" />
 <input type = "text" class = "xyz"  value = "b" />
 <input type = "text" class = "xyz" value = "c" />
 <input type = "text" class = "xyz" value = "d" />
</div>

<div class = "test2 yes">
 <input type = "text" class = "xyz" value = "e" />
 <input type = "text" class = "xyz" value = "f" />
 <input type = "text" class = "xyz" value = "g" />
 <input type = "text" class = "xyz" value = "h" />
</div>

<div class = "test3 yes">
 <input type = "text" class = "xyz" value = "i" />
 <input type = "text" class = "xyz" value = "j" />
 <input type = "text" class = "xyz" value = "k" />
 <input type = "text" class = "xyz" value = "l" />
</div>

<input type = "submit" class='submit'>

<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

 <p class='count'></p> 
 <p class='test'></p> 

<p style = "font-weight: bold;" class = "time text-center"></p>

<script>
    $('.submit').click(function(){
        var count = $('.yes').length
        $('.count').text(count);
       
        var texts = "";
        var i = 0;
    while (i < count) {
        texts = $(".xyz").map(function() { return this.value; })
                                   .get().join('-') + ",";
        i++;
    }

    $('.test').text(texts);    

    });
    

</script>

Дампы кода не являются ответами полезный. Чтобы сделать ответ полезным, скажите какая, который вы изменили, и Зачем.

T.J. Crowder 20.03.2022 15:12

Да, это я объясняю :)

Yarin Levi 20.03.2022 15:13

ваш код приводит к a-b-c-d-e-f-g-h-i-j-k-l, тогда как мне нужно a-b-c-d,e-f-g-h,i-j-k-l

vamshi g 20.03.2022 15:15
Ответ принят как подходящий

Прокрутите элементы .yes, создав массив их элементов .xyz и соединив его с помощью -, затем соедините результат с помощью ,:

var texts = $(".yes").map(function() {
    return $(this).find(".xyz").map(function() {
        return this.value;
    }).get().join("-");
}).get().join(",");

Живой пример:

$('.submit').click(function() {
    var count = $('.yes').length
    $('.count').text(count);
    
    var texts = $(".yes").map(function() {
        return $(this).find(".xyz").map(function() {
            return this.value;
        }).get().join("-");
    }).get().join(",");

    $('.test').text(texts);

});

// a-b-c-d,e-f-g-h,i-j-k-l
<div class = "test1 yes">
 <input type = "text" class = "xyz" value = "a" />
 <input type = "text" class = "xyz"  value = "b" />
 <input type = "text" class = "xyz" value = "c" />
 <input type = "text" class = "xyz" value = "d" />
</div>

<div class = "test2 yes">
 <input type = "text" class = "xyz" value = "e" />
 <input type = "text" class = "xyz" value = "f" />
 <input type = "text" class = "xyz" value = "g" />
 <input type = "text" class = "xyz" value = "h" />
</div>

<div class = "test3 yes">
 <input type = "text" class = "xyz" value = "i" />
 <input type = "text" class = "xyz" value = "j" />
 <input type = "text" class = "xyz" value = "k" />
 <input type = "text" class = "xyz" value = "l" />
</div>

<input type = "submit" class='submit'>

<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

 <p class='count'></p> 
 <p class='test'></p> 

<p style = "font-weight: bold;" class = "time text-center"></p>

Более:

  • jQuery.fn.map
  • jQuery.fn.get

Большое спасибо, сэр. Это работает .. Любовь из Индии

vamshi g 20.03.2022 15:23

Другие вопросы по теме