How i can toggle the input statue disabled

人盡茶涼 提交于 2019-12-25 00:45:10

问题


before i ask the question i searched on Stackoverflow about this and found out that i can disable or enable the input by prop or attr, but when i tried to implement this - like the following example- it does not want to toggle, am i missing something? thank you

$(function() {

  $('#submit').on('click', function() {
    $('body').prepend('<div class= "item" ></div>');
    if ($('.item').length > 0) {
      $('#search').removeAttr('disabled');
    }
    if ($('.item').length == 0) {
      $('#search').attr('disabled', 'disabled');
      //$('#search').prop('disabled', true);

    }

  });

  $('#reset').on('click', function() {
    $('.item').remove();
  })
});
button {
  display: inline-block
}

input {
  position: fixed;
  bottom: 0;
  right: 0
}

.item {
  width: 50px;
  height: 50px;
  background: orangered;
  margin: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='search' id='search' disabled>
<button id='submit'>Submit</button>
<button id='reset'>Reset</button>

回答1:


You dont need to check the lenght of generated divs, just play with disabled true or false depending on the click:

$(function() {

  $("input").prop('disabled', true);
  $('#submit').on('click', function() {
        $('body').prepend('<div class= "item" ></div>');
        $("input").prop('disabled', false);
  });

  $('#reset').on('click', function() {
        $('.item').remove();
        $("input").prop('disabled', true);
  })
});
button {
  display: inline-block
}

input {
  position: fixed;
  bottom: 0;
  right: 0
}

.item {
  width: 50px;
  height: 50px;
  background: orangered;
  margin: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='search' id='search'>
<button id='submit'>Submit</button>
<button id='reset'>Reset</button>



回答2:


For your HTML, use this:

<input type='search' id='search' disabled="disabled">
<button id='submit'>Submit</button>
<button id='reset'>Reset</button>

Notice that of [disabled="disabled"], then your JavaScript use:

<script>
(function() {
  var searchInput = $("#search");
  var searchAttr = $("#search").attr("disabled");

  $( "#submit" ).click(function() {
    $('body').prepend('<div class= "item" ></div>');
    if ( $('.item').length === 0 ) { // Use triple equals for exact type check

      searchInput.attr( "disabled", searchAttr );
    } else{
      searchInput.removeAttr("disabled");
    }
  });

  $('#reset').on('click', function() {
    $('.item').remove();
    searchInput.attr( "disabled", searchAttr );
  })
})();
</script>

This should work.



来源:https://stackoverflow.com/questions/46712794/how-i-can-toggle-the-input-statue-disabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!