Как установить значения следующего элемента в jQuery - PullRequest
1 голос
/ 04 февраля 2020

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

<span id="clear_promotion_brand_search" class="myButtonClass"><i class="fa fa-times"></i></span>
<span id="error_brand" class="show-error-msg"></span>
<input type="hidden" name="promotion_brand_id" value="" data-id="brand" class="search-id is-validate form-fields-value">

$(document).on('click','.myButtonClass',function(e){
  console.log($(this).closest(".search-id").length); // returning 0
  console.log($(this).next(".search-id").val()); // returning undefined
  if($(this).next(".search-id").length){
    var myval = $(this).next(".search-id").find('input[type=hidden]').val();
    console.log('Val -'+myval);
  }
});

Что я делаю не так?

Ответы [ 4 ]

0 голосов
/ 04 февраля 2020

Вы можете использовать функцию $ (this) .next (). Next (), чтобы найти поле ввода.

$(document).ready(function(){
   $(".myButtonClass").on('click',function(){
      $(this).next().next().val('Hello World')
   })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="clear_promotion_brand_search" class="myButtonClass"><i class="fa fa-times">click me</i></span>
<span id="error_brand" class="show-error-msg"></span>
<input type="hidden" name="promotion_brand_id" value="" data-id="brand" class="search-id is-validate form-fields-value">

enter image description here

0 голосов
/ 04 февраля 2020

Ваш .next() элемент буквально является следующим элементом в вашем HTML коде, поэтому в вашем случае это <span id="error_brand" class="show-error-msg"></span>

Я адаптировал ваш код. .find() также исключает текущий элемент. Поэтому, если вы запустите это на элементе, который хотите найти, он не найдет его.

Я немного обновил ваш фрагмент, только что добавил реальную кнопку и немного контента. Кроме этого это то же самое.

$(document).on('click','.myButtonClass',function(e){
  e.preventDefault();
  if($(this).next().next().length){
    var myval = $(this).next().next().val();
    console.log('Val -'+myval);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="clear_promotion_brand_search" class="myButtonClass">Click me!<i class="fa fa-times"></i></button>
<span id="error_brand" class="show-error-msg"></span>
<input type="hidden" name="promotion_brand_id" value="testvalue" data-id="brand" class="search-id is-validate form-fields-value">
0 голосов
/ 04 февраля 2020

Используйте братьев и сестер () вместо next().

Запустите ниже рабочего кода -

$(document).on('click','.myButtonClass',function(e){
  console.log($(this).closest(".search-id").length); // returning 0
  console.log($(this).siblings("input:hidden.search-id").val()); // returning undefined
  if($(this).siblings("input:hidden.search-id").length){
    var myval = $(this).siblings("input:hidden.search-id").val();
    console.log('Val -'+myval);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="clear_promotion_brand_search" class="myButtonClass">Click Here<i class="fa fa-times"></i></span>
<span id="error_brand" class="show-error-msg"></span>
<input type="hidden" name="promotion_brand_id" value="Hidden Input Value" data-id="brand" class="search-id is-validate form-fields-value">
0 голосов
/ 04 февраля 2020

Вы можете использовать nextUntil и next, чтобы получить желаемое входное значение, как показано ниже: code

$(function(){
  $(document).on('click','.myButtonClass',function(e){
    var input = $(this).nextUntil(".search-id").next();
    console.log(input.length);
    console.log("value = " + $(input).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="clear_promotion_brand_search" class="myButtonClass">Button<i class="fa fa-times"></i></span>
<span id="error_brand" class="show-error-msg">Error</span>
<input type="hidden" name="promotion_brand_id" value="Test Value" data-id="brand" class="search-id is-validate form-fields-value">

ИЛИ вы можете использовать nextAll с :first селектором

 $(function(){
      $(document).on('click','.myButtonClass',function(e){
        var input = $(this).nextAll(".search-id:first");
        console.log(input.length);
        console.log("value = " + $(input).val());
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="clear_promotion_brand_search" class="myButtonClass">Button<i class="fa fa-times"></i></span>
    <span id="error_brand" class="show-error-msg">Error</span>
    <input type="hidden" name="promotion_brand_id" value="Test Value" data-id="brand" class="search-id is-validate form-fields-value">
...