Lily
Lily

Reputation: 375

How to set value on the `path` attribute of a spring form `select` element?

I'm working on a java web project based on springmvc.

On one page, a html source snippet is as below:

<form:select id="goodSelectId" path="goodId" items="${goodsList}"
      itemLabel="name" itemValue="goodCode">
      <form:option value="">select the product</form:option>
</form:select>


<form:checkbox path="flag" id="flag" value="1"
      onchange="change(this, 'goodSelectId')"/>  

related jquery function :

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

When I tick the checkbox, I want to make the select element value null, and then disable the select element.

"disable" is Ok, but the value "" can't be set to path of select:form.

That is:

1) if I USE select drop-down to choose a option, the value can be passed to path

2) but if I set the value through the javascript function above, the value can't be passed to path

my question is: how can I pass the value set inside the javascript function to path?

Upvotes: 0

Views: 2682

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

Thats because your options values are 1 or 2.
Try this line:

  $("#" + targetId).val(1);

Your modified code:

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

  $("#show").html($("#" + targetId).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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')" />

<p id="show">xx</p>

Upvotes: 1

Milan Chheda
Milan Chheda

Reputation: 8249

I used $("#" + targetId + ' option:first').attr('selected', 'selected'); and seems thats what you are looking for, check the code below:

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

  $("#show").html($("#" + targetId).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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')" />

<p id="show">xx</p>

Upvotes: 0

Related Questions