자바 스크립트를 통한 JSON 입력을 기반으로 동적으로 생성 된 라디오 버튼을 미리 선택하는 방법

tx-911

아래 스크립트에서는 일부 카테고리 옆에 상태로 라디오 버튼 (녹색 / 노란색 / 빨간색)을 동적으로 생성하고 있습니다.

범주 및 상태 (1- 녹색, 2- 노란색, 3- 빨간색)는 모두 json 개체를 통해 수신됩니다. 내 목표는 현재 상태를 미리 선택된 라디오 버튼으로 표시하는 것입니다. 예 : 아래 양식 {"category":"System Availability","status":"1"}에서 시스템 가용성 상태가 녹색을 의미하는 1임을 나타냅니다. 사전 선택된 녹색 버튼을 어떻게 선택할 수 있습니까? 0이면 아무것도 선택하지 않아야합니다.

다음은 json 입력을 기반으로 라디오 버튼을 미리 선택하는 기능이없는 실행 코드입니다. 결국 내 목표는 json을 통해 데이터베이스를 다시 업데이트하는 것입니다.

시간을내어 도와 주셔서 감사합니다!

					$(document).ready(function() {
					    var appStatus = [{
					        "category": "Overall Status",
					        "status": "0"
					    }, {
					        "category": "System Availability",
					        "status": "1"
					    }, {
					        "category": "Whatever",
					        "status": "2"
					    }];
					    var tr;
					    for (var i = 0; i < appStatus.length; i++) {
					        tr = $('<tr/>');
					        tr.append("<td>" + appStatus[i].category + "</td>");
					        tr.append('<tr id="row' + i + '"><td><input type="radio" name="inlineRadioOptions_' + i + '[]" value="1" id="inlineRadio1"><font color="green">Green &emsp;</font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio2" value="2"><font color="yellow">Yellow &emsp;</font></label><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio3" value="3"> <font color="red">Red</font></label><td></tr>');
					        $('table').append(tr);
					    }


					    $('#result').on('click', function() {
					        var new_status = [];
					        $('.table tbody tr').each(function() {
					            new_status.push({
					                category: $(this).find('td:eq(0)').text(),
					                status: $(this).find(':radio:checked').val()
					            });
					        });

					        console.log(new_status);
					    });
					});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover"><thead>
<th>Category</th>
<th>Status</th>
</thead>
</table>

Cᴏʀʏ

이것을 지나치게 단순화 할 수도 있지만 라디오 버튼을 미리 선택하려면 추가 할 HTML을 변경하여 선택해야 할 때 속성으로 <input>렌더링 되도록합니다 checked.

$(document).ready(function() {
	var appStatus = [{
		"category": "Overall Status",
		"status": "0"
	}, {
		"category": "System Availability",
		"status": "1"
	}, {
		"category": "Whatever",
		"status": "2"
	}];
	var tr;
	for (var i = 0; i < appStatus.length; i++) {
		tr = $('<tr/>');
		tr.append("<td>" + appStatus[i].category + "</td>");
		tr.append('<tr id="row' + i + '"><td><input type="radio" name="inlineRadioOptions_' + i + '[]" value="1" id="inlineRadio1"' + 
			(appStatus[i].status == '1' ? ' checked="checked"' : '') + 
			'><font color="green">Green &emsp;</font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio2" value="2"' + 
			(appStatus[i].status == '2' ? ' checked="checked"' : '') + 
			'><font color="yellow">Yellow &emsp;</font></label><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio3" value="3"' + 
			(appStatus[i].status == '3' ? ' checked="checked"' : '') + '> <font color="red">Red</font></label><td></tr>');
		$('table').append(tr);
	}


	$('#result').on('click', function() {
		var new_status = [];
		$('.table tbody tr').each(function() {
			new_status.push({
				category: $(this).find('td:eq(0)').text(),
				status: $(this).find(':radio:checked').val()
			});
		});

		console.log(new_status);
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover"><thead>
<th>Category</th>
<th>Status</th>
</thead>
</table>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관