JavaScript
name의 여러개의 Value를 수정
ds-jeung
2022. 7. 12. 17:32
가격수정처리를 하려한다.
여러개의 input이 동일한 name을 가지는데, name의 값을 배열로 초기화하여 처리하는 프로세스이다
Js
$("#priceUpdateBtn").on("click", function () {
let state = $("input[name='state']").val();
let price = [];
$("input[name='updatePrice']").each(function (i) {
price.push($(this).val().replaceAll(",",""));
});
$.ajax({
url : "/priceUpdate",
type : "post",
data : {
state : state
, price : price
},
success : function (data) {
alert("수정되었습니다.");
location.reload();
}, error: function () {
alert("error");
}
});
});
HTML
<input type="hidden" th:value="${state}" name="state"/>
<tr>
<td class="t_right" name="updatePriceInputTag">
<input type="text" value="price" name="updatePrice"/>
</td>
</tr>
Controller
@PostMapping({"/priceUpdate"})
@ResponseBody
public void priceUpdate(@RequestParam(value="state") String state,
@RequestParam(value="price[]") List<String> price) throws Exception{
priceService.priceUpdate(state, price);
}
Service
@Transactional
public void priceUpdate(String state, List<String> price) throws Exception{
//List로 받아온 price의 값을 담을 변수
Integer priceItem = null;
//key와 value로 담을 MAP 객체 초기화
Map<String, Object> obj = new HashMap<String, Object>();
//List로 받아온 price의 값을 반복
for (int i = 0; i < price.size(); i++){
/*System.out.print(state+",");
System.out.println(price.get(i));
*/
//price 하나의 값
priceItem = Integer.parseInt(price.get(i));
//초기화 한 obj에 담는다.
obj.put("state", state);
obj.put("priceItem", priceItem);
//mapper로 보낸다.
//Mybatis에서는 #{obj에 담았던 key명} << 으로 파라미터를 전달
//Mybatis ParameterType은 HashMap으로 선언한다.
priceUpdateMapper.priceUpdate(obj);
}
}
}