ajax 동기처리 질문
본문
현재 아래와 같은 상황에서 순서대로 주문품명 입력하게 되면 g당 단가가 나옵니다.
이후 수량을 입력하면 추가적으로 가격이 붙고 색상을 입히면 추가적인 가격이 g당 단가에 ajax를 통해 최신화가 됩니다.
그런데 문제는 주문품명까지는 무조건 기입을 하고 색상을 먼저 체크를 하여 g당 단가 변화 수치를 보고 난 뒤에 색상 라디오 버튼이 이미 선택되어 있는 상태에서 수량에 숫자를 넣게 되면 색상으로 인한 추가 값이 나오지 않고 주문품명과 수량의 계산으로만 따지고 결과값을 출력합니다.
원하는 것은 주문품명까지는 무조건 기입을 하고 이후 수량을 먼저하든 색상을 먼저하든 정확한 값을 출력하고 싶습니다.
계산순서는 주문품명 -> 수량 -> 색상순서로 동기 처리를 해야하는 것이고 모든 이벤트를 함수화 하여 update()함수 안에 넣어서 하려고도 하는데 잘 안되네요...
1. 페이지 사진
2. index script코드입니다.
/*주문품명 */
$(document).ready(function () {
//select 버튼 클릭시
$('#select_zero').on('change', function () {
var select_zero = $('#select_zero').val();
if (select_zero) {
$.ajax({
type: 'POST',
url: './ajax/information_select.php',
data: 'select_zero=' + select_zero,
success: function (html) {
$('#select_first').html(html);
$('#select_second').html('<option value="">선택</option>');
}
});
} else {
$('#select_first').html('<option value="">선택</option>');
$('#select_second').html('<option value="">선택</option>');
}
});
$('#select_first').on('change', function () {
var select_first = $('#select_first').val();
if (select_first) {
$.ajax({
type: 'POST',
url: './ajax/information_select.php',
data: 'select_first=' + select_first,
success: function (html) {
$('#select_second').html(html);
}
});
} else {
$('#select_second').html('<option value="">선택</option>');
}
});
$('#select_second').on('click', function () {
var select_second = $('#select_second').val();
if (select_second) {
var select_first = $('#select_first').val();
var select_zero = $('#select_zero').val();
$.ajax({
type: 'POST',
url: './ajax/information_price.php',
data: {
select_second: select_second,
select_first: select_first,
select_zero: select_zero
},
success: function (html) {
$('#price_per_gram').text(html);
originalPricePerGram = parseFloat(html);
}
});
} else {
$('#price_per_gram').text('0');
}
});
/* 수량 입력 후 g당 단가 최신화 */
$('#quantity').on('input', function () {
var selectZero = $('#select_zero').val();
var selectFirst = $('#select_first').val();
var selectSecond = $('#select_second').val();
var quantity = parseFloat($('#quantity').val());
if (!isNaN(quantity) && quantity >= 0) {
if (selectZero === "0" || selectFirst === "0" || selectSecond === "0") {
alert('주문품명을 먼저 선택해주세요.');
$('#quantity').val('');
} else {
$.ajax({
type: 'POST',
url: 'ajax/basic_quantity_ajax.php',
data: {
selectZero: selectZero,
selectFirst: selectFirst,
selectSecond: selectSecond,
quantity: quantity,
},
success: function (response) {
quantityPricePerGram = parseFloat(response);
$('#price_per_gram').text(quantityPricePerGram.toFixed(1));
}
});
}
} else {
// 수량이 비어있거나 올바르지 않은 경우, 원래의 g당 단가로 설정
$('#price_per_gram').text(originalPricePerGram);
}
});
/* 개당용량 alert */
$('#capacity').on('input', function () {
var selectZero = $('#select_zero').val();
var selectFirst = $('#select_first').val();
var selectSecond = $('#select_second').val();
var capacity = parseFloat($('#capacity').val());
if (selectZero === "0" || selectFirst === "0" || selectSecond === "0") {
alert('주문품명을 먼저 선택해주세요.');
$('#capacity').val('');
}
});
/* 최소염색 100kg 일때만 염색 가능 알림창 */
$('input[id="colored"]').on('click', function () {
var quantity = parseFloat($('input[id="quantity"]').val());
var capacity = parseFloat($('input[id="capacity"]').val());
if (isNaN(capacity)) {
capacity = 0;
}
else if (isNaN(quantity)) {
quantity = 0;
}
var quantityTimesCapacity = quantity * capacity;
if (quantityTimesCapacity < 100000) {
alert('최소염색 100Kg 일때만 염색가능합니다.');
$('input[name="color_select"]').prop("checked", false); // 라디오 버튼 선택 취소
}
});
/* 색상 선택 후 g당 단가 최신화 */
$('input[name="color_select"]').on('change', function () {
var selectZero = $('#select_zero').val();
var selectFirst = $('#select_first').val();
var selectSecond = $('#select_second').val();
if (selectZero === "0" || selectFirst === "0" || selectSecond === "0") {
alert('주문품명을 먼저 선택해주세요.');
$('input[name="color_select"]').prop("checked", false);
}
var selectedColor = $("input[name='color_select']:checked").attr('id');
if (quantityPricePerGram != 0) {
$.ajax({
type: 'POST',
url: 'ajax/basic_quantity_ajax.php',
data: {
quantityPricePerGram: quantityPricePerGram,
selectedColor: selectedColor,
},
success: function (response) {
colorPricePerGram = parseFloat(response);
$('#price_per_gram').text(colorPricePerGram.toFixed(1));
}
});
}
else if (quantityPricePerGram == 0 && originalPricePerGram != 0) {
$.ajax({
type: 'POST',
url: 'ajax/basic_quantity_ajax.php',
data: {
originalPricePerGram: originalPricePerGram,
selectedColor: selectedColor,
},
success: function (response) {
colorPricePerGram = parseFloat(response);
$('#price_per_gram').text(colorPricePerGram.toFixed(1));
}
});
}
else {
$('#price_per_gram').text('0');
}
});
!-->
답변 1
코드를 좀 더 단순하게 하면 좋겠지만,
우선 위의 코드에서
/* 색상 선택 후 g당 단가 최신화 */ 이 부분에서
quantityPricePerGram 변수가 정의되어 있지 않은 것 같은데 에러가 발생하지 않나요?
칼라값을 변경하였을 때에도 수량값을 가지고 와야 할 것 같습니다.
값을 계산할때 사용하는 값은 품목/수량/색상 이 3가지이므로,
별도의 계산함수를 만들어서 이벤트가 발생했을 때, 이 3가지 값만 체크해서
ajax로 처리 후 할당해 주는 방식으로 하면 될 듯 하네요.
답변을 작성하시기 전에 로그인 해주세요.