Jquery If 라디오 버튼을 선택한 경우
중복 가능성:
특정 라디오 버튼을 선택합니다.
사용자가 가격에 우편 요금이 포함되어야 하는지 여부를 결정할 수 있도록 현재 두 개의 라디오 버튼이 있습니다.
<input type="radio" id="postageyes" name="postage" value="Yes" /> Yes
<input type="radio" id="postageno" name="postage" value="No" /> No
저는 Jquery를 사용하여 'yes' 라디오 버튼이 선택되어 있는지 확인하고, 선택되어 있으면 추가 기능을 수행해야 합니다.제가 어떻게 해야 하는지 누가 알려주실 수 있나요?
도와주셔서 감사합니다.
편집:
코드를 이것으로 업데이트했는데 작동하지 않습니다.내가 뭘 잘못하고 있나요?
<script type='text/javascript'>
// <![CDATA[
jQuery(document).ready(function(){
$('input:radio[name="postage"]').change(function(){
if($(this).val() == 'Yes'){
alert("test");
}
});
});
// ]]>
</script>
$('input:radio[name="postage"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Yes') {
// append goes here
}
});
또는 위의 - 다시 - 약간 덜 불필요한 jQuery를 사용합니다.
$('input:radio[name="postage"]').change(
function(){
if (this.checked && this.value == 'Yes') {
// note that, as per comments, the 'changed'
// <input> will *always* be checked, as the change
// event only fires on checking an <input>, not
// on un-checking it.
// append goes here
}
});
수정된(개선된) jQuery:
// defines a div element with the text "You're appendin'!"
// assigns that div to the variable 'appended'
var appended = $('<div />').text("You're appendin'!");
// assigns the 'id' of "appended" to the 'appended' element
appended.id = 'appended';
// 1. selects '<input type="radio" />' elements with the 'name' attribute of 'postage'
// 2. assigns the onChange/onchange event handler
$('input:radio[name="postage"]').change(
function(){
// checks that the clicked radio button is the one of value 'Yes'
// the value of the element is the one that's checked (as noted by @shef in comments)
if ($(this).val() == 'Yes') {
// appends the 'appended' element to the 'body' tag
$(appended).appendTo('body');
}
else {
// if it's the 'No' button removes the 'appended' element.
$(appended).remove();
}
});
var appended = $('<div />').text("You're appendin'!");
appended.id = 'appended';
$('input:radio[name="postage"]').change(function() {
if ($(this).val() == 'Yes') {
$(appended).appendTo('body');
} else {
$(appended).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes
<input type="radio" id="postageno" name="postage" value="No" />No
JS 피들 데모.
그리고 더 나아가, (JS 피들 링크뿐만 아니라 스니펫도 포함하도록 편집하고 있었기 때문에) 가벼운 업데이트를 마무리하기 위해.<input />
와의 요소.<label>
s - 텍스트를 클릭하여 관련 내용을 업데이트할 수 있습니다.<input />
추가할 콘텐츠를 만드는 방법을 변경합니다.
var appended = $('<div />', {
'id': 'appended',
'text': 'Appended content'
});
$('input:radio[name="postage"]').change(function() {
if ($(this).val() == 'Yes') {
$(appended).appendTo('body');
} else {
$(appended).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>
<label>
<input type="radio" id="postageno" name="postage" value="No" />No</label>
JS 피들 데모.
또한 사용자가 선택한 요소에 따라 콘텐츠만 표시해야 하는 경우 명시적인 표시/숨기기를 사용하여 표시 여부를 전환하는 약간의 업데이트:
// caching a reference to the dependant/conditional content:
var conditionalContent = $('#conditional'),
// caching a reference to the group of inputs, since we're using that
// same group twice:
group = $('input[type=radio][name=postage]');
// binding the change event-handler:
group.change(function() {
// toggling the visibility of the conditionalContent, which will
// be shown if the assessment returns true and hidden otherwise:
conditionalContent.toggle(group.filter(':checked').val() === 'Yes');
// triggering the change event on the group, to appropriately show/hide
// the conditionalContent on page-load/DOM-ready:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>
<label>
<input type="radio" id="postageno" name="postage" value="No" />No</label>
<div id="conditional">
<p>This should only show when the 'Yes' radio <input> element is checked.</p>
</div>
그리고 마지막으로, CSS만을 사용합니다.
/* setting the default of the conditionally-displayed content
to hidden: */
#conditional {
display: none;
}
/* if the #postageyes element is checked then the general sibling of
that element, with the id of 'conditional', will be shown: */
#postageyes:checked ~ #conditional {
display: block;
}
<!-- note that the <input> elements are now not wrapped in the <label> elements,
in order that the #conditional element is a (subsequent) sibling of the radio
<input> elements: -->
<input type="radio" id="postageyes" name="postage" value="Yes" />
<label for="postageyes">Yes</label>
<input type="radio" id="postageno" name="postage" value="No" />
<label for="postageno">No</label>
<div id="conditional">
<p>This should only show when the 'Yes' radio <input> element is checked.</p>
</div>
JS 피들 데모.
참조:
- CSS:
:checked
선택자- CSS 속성 선택기.
- 일반 형제()
~
조합입니다.
- jQuery:
사용해 보세요.
if($("input:radio[name=postage]").is(":checked")){
//Code to append goes here
}
이와 같은 것:
if($('#postageyes').is(':checked')) {
// do stuff
}
if($('#test2').is(':checked')) {
$(this).append('stuff');
}
$('input:radio[name="postage"]').change(function(){
if($(this).val() === 'Yes'){
// append stuff
}
});
그러면 라디오 버튼의 변경 이벤트가 수신됩니다.사용자가 클릭할 때Yes
이벤트가 실행되고 DOM에 원하는 항목을 추가할 수 있습니다.
$("input").bind('click', function(e){
if ($(this).val() == 'Yes') {
$("body").append('whatever');
}
});
사용해 보십시오.
if ( jQuery('#postageyes').is(':checked') ){ ... }
변경된 이벤트가 재생됩니다.저는 다른 사람들의 답을 시도해 보았지만 그것들은 저에게 효과가 없었고 마침내 이것이 효과가 있었습니다.
$('input:radio[name="postage"]').change(function(){
if($(this).is(":checked")){
alert("lksdahflk");
}
});
또 다른 구현은 다음과 같습니다.
HTML
<h1>Display Radio Buttons</h1>
<form action="/action_page.php">
<p>Please select your favorite Web language:</p>
<!-- 1 -->
<input type="radio" id="html" name="fav_language" value="HTML" checked>
<label for="html">HTML</label><br>
<!-- 2 -->
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<!-- 3 -->
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
<br>
<input type="submit" value="Submit">
</form>
기억:
name
는 라디오 버튼을 그룹화합니다.id
모든 라디오 버튼의 상태를 알려줍니다.value
제출 시 게시할 내용입니다.for
지정된 레이블을 id 명명된 입력 필드에 연결할 수 있습니다.- 제출 단추:선택한 라디오 버튼 값을 웹 서버(백엔드)에 게시합니다.
jQuery
이것은 코드 프런트 엔드라는 것을 기억하세요.
여기서 모든 버튼을 선택합니다.type
원하는 대로 선택할 수 있습니다.이 경우, 우리는 다음을 사용할 것입니다.value
HTML 요소의 일부:
$("[type='radio']").on('change', function (e) {
var selectedValue = $(this).val();
console.log(selectedValue); // So you can see it in the console.
if (selectedValue == 'HTML') {
// Do something.
}
else {
// Or do something else.
// Example:
// someOtherSelectedElement.prop("disabled", false);
}
});
개수만큼 추가if
라디오 단추에 필요한 설명을 입력합니다.
의 사용 덕분이라는 것임을 명심하십시오.value
필드에서 원하는 만큼의 옵션을 설정할 수 있습니다.
결과
레퍼런스
jQuery('input[name="inputName"]:checked').val()
언급URL : https://stackoverflow.com/questions/6654601/jquery-if-radio-button-is-checked
'programing' 카테고리의 다른 글
SSIS vs.오라클 데이터 통합업체 (0) | 2023.08.02 |
---|---|
다른 모듈이 필요한 Node.js 모듈을 유닛 테스트하는 방법과 글로벌 요구 기능을 조롱하는 방법은 무엇입니까? (0) | 2023.08.02 |
div 내에서 버튼의 중심을 잡는 방법은 무엇입니까? (0) | 2023.08.02 |
Javascript 개체 형식 조작 (0) | 2023.08.02 |
$가 무엇입니까?파워셸에서? (0) | 2023.08.02 |