【问题标题】:How to disable the button if the input has no arrays?如果输入没有数组,如何禁用按钮?
【发布时间】:2013-02-18 15:32:36
【问题描述】:

我的 HTML 内容中有以下内容,输入值将由用户选择填充并以数组格式存储值(45[45, 6, 33], 67[67,2,5] and so on..)。基本上该值将如下所示:

<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">

如果输入在{} 中没有数组,我现在需要禁用提交按钮或提醒一些消息,例如“选择所有值”。

更新:

var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);

   var myArray = new Array();
      myArray[0] = window.batch_question_id;
      myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
      myArray[2] = window.build_id

上面这段代码将值存储到{}。我只想禁用并让用户选择所有字段来处理表单。如果值为{},则应禁用该按钮。以及里面的任何值,它应该被启用。

我尝试过如下方法:

 $('.submit_updates').click(function () {
    if ($('#question_string') == {}) {
      return false;
      alert("Select all the Values");
    } else {
      return true;
    }
  });

它不工作..

任何帮助将不胜感激!谢谢

【问题讨论】:

  • 您当前将$('#question_string') 与空对象文字进行比较,它们永远不会相同。您要比较的是 input value 与 string "{}".
  • 您可能希望在输入中使用valid JSON,例如 [[45, 6, 33], [67, 2, 5]]。
  • 这几乎感觉你应该在这些元素上使用 jQuery data() 功能(当然不知道更多关于你的解决方案)
  • @emallove 它只是一个有效的 JSON 输入...
  • 显示您如何填充#question_string 输入,这可能使我们能够为您提供更好/更全面审查的解决方案。

标签: javascript jquery html css


【解决方案1】:
$('.submit_updates').on('click', function (e) {
   e.preventDefault();
   if ( $.trim($('#question_string').val())=='{}' ) {
       alert('no question !');
   }else{
       this.form.submit();
   }
});

【讨论】:

  • 如果点击了禁用的按钮,是否可以添加闪信?
  • “闪信”是什么意思?
  • @adeneo 它只是一次发出警报,当值存储到哈希中时......它没有启用。我猜
  • @Sri - 再次编辑,将在不禁用按钮的情况下发出警报,如果值不是“{}”,则提交表单??
【解决方案2】:

您在提醒消息之前返回 false。

试试这个:

$('.submit_updates').on("click", function () {
  if ($('#question_string').val() == "{}") { //Adjusted condition
    //Alert message
    alert("Select all the Values");

    //Disable the submit button
    $(".submit_updates").prop("disabled", true);
    return false;
  } else {
  return true; //Not really needed
 }
});

正如@adeneo 建议的那样,使用on 和prop 而不是click 和attr 会更好。

【讨论】:

  • 使用 .prop() 禁用而不是 .attr() 否则从 1.9+ 开始你会遇到问题 – Mark Schultheiss
  • 传递给 {} 的值.. 但它没有提交.. 有什么猜测吗?
【解决方案3】:

试试这个

$(function(){
     $('.submit_updates').on('click', function () {
        if ($('#question_string').val() == "{}") {
              $(this).prop('disabled', 'disabled'); 
              alert("Select all the Values");
        } else {
        }
      });
});

DEMO

【讨论】:

  • 使用 .prop() 禁用而不是 .attr() 否则从 1.9+ 开始你会遇到问题
  • @Mark 谢谢你的建议。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多