Jquery скрыть div на основе значения проверки ввода - PullRequest
1 голос
/ 25 сентября 2019

Я пытаюсь скрыть div на основе значения проверки ввода.Также это должно работать, если элемент уже проверен, пока мой код не работает.Как всегда показывает div, который я хочу скрыть?Я создал JS Fiddle , чтобы повторить проблему

Код выглядит следующим образом:

var test = $("input[value='home']");

if (test == true) {
  $(".title").hide();
} else {
  $(".title").show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="radiogroup">
  <input type="radio" name="gender" value="home" checked> Male
  <br>
  <input type="radio" name="gender" value="female"> Female
  <br>
  <input type="radio" name="gender" value="other"> Other
  <br />
  <br />
  <div class='title'>
    This is the title not on home value
  </div>
</div>

Любой ввод будет отличным.

Ответы [ 5 ]

2 голосов
/ 25 сентября 2019

Вы можете сделать это только с помощью CSS:

input[name="gender"][value="home"]:checked ~ div.title {
  display: none;
}
<input type="radio" name="gender" value="home" checked> Male
<br>
<input type="radio" name="gender" value="female"> Female
<br>
<input type="radio" name="gender" value="other"> Other
<br />
<br />
<div class='title'>
    This is the title not on home value
</div>
1 голос
/ 25 сентября 2019

Вам необходимо добавить прослушиватель событий для радиогруппы, а затем получить значение отмеченной опции.Кроме того, вы, вероятно, захотите запустить его один раз при загрузке страницы, что и делает .change() в последней строке.

//run this anytime a radio input changes
$('input[name="gender"]').on('change', function() {
    //get the currently selected value
    let test = $('input[name="gender"]:checked').val();

    //check the current value
    if (test == 'home') {
        $(".title").hide();
    } else {
        $(".title").show();
    }
}).change(); //trigger this on page load
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div role="radiogroup">
    <input type="radio" name="gender" value="home" checked> Male
    <br>
    <input type="radio" name="gender" value="female"> Female
    <br>
    <input type="radio" name="gender" value="other"> Other
    <br />
    <br />
    <div class='title'>
        This is the title not on home value
    </div>
</div>
1 голос
/ 25 сентября 2019

Попробуй это.Сначала при готовности функция проверить, проверен ли вход.А затем проверьте функцию изменения входа.

$(document).ready(function() {
    var test = $("input[name='gender']");
    var home = $("input[value='home']")[0];
    var title = $(".title");
    if(home.checked) {
        title.hide();
    }

    test.on('change', function(e) {
        if(e.target.value === 'home') {
        title.hide();
      } else {
        title.show();
      }
    })
});
1 голос
/ 25 сентября 2019

Дубликат Если флажок переключателя установлен, показывать div

Вот адаптированный код для вашего случая:

$('input[type="radio"]').click(function(){
    if($(this).attr("value")=="home"){
        $(".title").hide('slow');
    }
    else{
       $(".title").show('slow');
    }  
});
$('input[type="radio"]').trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="radiogroup">
    <input type="radio" name="gender" value="home" checked> Male
    <br>
    <input type="radio" name="gender" value="female"> Female
    <br>
    <input type="radio" name="gender" value="other"> Other
    <br />
    <br />
    <div class='title'>
        This is the title not on home value
    </div>
</div>
1 голос
/ 25 сентября 2019

проверьте, есть ли какие-либо входы с домашним значением, которые проверены :

// hide show title on load
if ($("input[value='home']:checked").length) {  // can use :checked selector to see if input with value of home is checked (see link above)
  $(".title").hide();
} else {
  $(".title").show();
}

$("input").on('change', function() {             // hide or show title on change of input (probably use a class here instead of a bare input selector)
  if (this.value === "home" && this.checked) {
    $(".title").hide();                          // hide title if value is home and checkbox is checked
  } else {
    $(".title").show();                          // otherwise show title
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="radiogroup">
  <input type="radio" name="gender" value="home" checked> Male
  <br>
  <input type="radio" name="gender" value="female"> Female
  <br>
  <input type="radio" name="gender" value="other"> Other
  <br />
  <br />
  <div class='title'>
    This is the title not on home value
  </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...