如何改变 select 元素的值?

前台 html,用的是 springmvc form

<form:select id="goodSelectId" path="goodId" items="${goodsList}"
      itemLabel="name" itemValue="goodCode">
      <form:option value="">请选择商品</form:option>
</form:select>
<form:checkbox path="flag" id="flag" value="1"
      onchange="change(this, 'goodSelectId')"/>  

javascript 脚本函数:

    function change(self, targetId) {
        if ($(self).is(':checked')) {
            $("#" + targetId).val("");
            $("#" + targetId).attr("disabled", true);      
        }
        else {
            $("#" + targetId).attr("disabled", false);
        }
    }
    

当下面的 checkbox 打钩后,要使得 select 元素的值为空
我用$("#id").val("");
但是发现不起作用
传到后台“ goodId ”依然有值
怎么回事?

真正的问题是设值不能传给form:select里的path(这个关联java后台)
也就是用select选的可以传值,但是用这个javascript函数设的值就不能传给path

阅读 5.5k
5 个回答
  function change(self, targetId) {
        if ($(self).is(':checked')) {
            $("#" + targetId + " option:eq(2)").attr("selected", "selected");
            $("#" + targetId).attr("disabled", true);
            console.log($("#" + targetId + " option:selected").val());
            console.log($("#" + targetId).length);
        }
        else {
            $("#" + targetId).attr("disabled", false);
        }

        $("#show").html($("#" + targetId).val());
    }

直接 val("") 似乎并没有什么问题啊,jsfiddle: https://jsfiddle.net/f7yo111n/

我觉得你可能要把 disabledval() 换下位置,设置了值再 disable

好像有点明白你的意思了……我按给出的Demo改了下代码,你再试试看:

<select id="test">
    <option value="">请选择</option>
    <option value="1">选项一</option>
    <option value="2">选项二</option>
</select>

<input type="checkbox" id="flag" value="1" onchange="change(this, 'test')" />
<div id="show"></div>
function change(self, targetId) {
    if ($(self).is(':checked')) {
        $("#" + targetId).prop("selectedIndex", -1);
    } else {
        $("#" + targetId).prop("disabled", false);
    }

    $("#show").html($("#" + targetId).val());
}

传不了值用ajax啊,应该可以直接把数据发到后台吧。

你可以在chrome里打断点来确定错误的具体原因,以及赋值情况:

clipboard.png

disable这个属性要用$.prop("disable",value)方法去设置属性,$.attr对于标签内置属性会经常不起作用。

function change(self, targetId) {
    if ($(self).is(':checked')) {
        $("#" + targetId).val("");
        $("#" + targetId).prop("disabled", true);      
    }
    else {
        $("#" + targetId).prop("disabled", false);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题