sourcejob
홈
태그
방명록
programing
의 , 어떻게 수? 의 , 어떻게 수? 의 , 어떻게 수?
sourcejob
2023. 4. 9. 21:27
반응형
의 , 어떻게 수?
element?요소? I thought that adding a "value" attribute set on the <select> element below would cause the <option> containing my provided "value" to be selected by default: 아래 <select> 요소에 "value" 속성 세트를 추가하면 제공된 "value"를 포함하는 <option>이 기본적으로 선택된다고 생각했습니다. <select name="hall" id="hall" value="3"> <이름="hall" id="hall" value="3" 선택> <option>1</option> <옵션> 1 </option> <option>2</option> <옵션> 2 </option> <option>3</option> <옵션> 3 </option> <option>4</option> <옵션> 4 </option> <option>5</option> <옵션> 5 </option></select> </select> However, this did not work as I had expected.그러나 이것은 내가 기대했던 대로 되지 않았다. How can I set which <option> element is selected by default?디폴트로 선택되고 있는<option> 요소를 설정하려면 어떻게 해야 합니까?Set selected="selected" for the option you want to be the default.기본값으로 사용할 옵션에 대해 selected="selected"를 설정합니다. <option selected="selected"> <option selected=3 3</option> </옵션>In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this: 디폴트 텍스트를 플레이스 홀더/힌트로서 사용할 수 있지만 유효한 값으로 간주되지 않는 경우("여기서 완료", "국가 선택" ecc와 같은 작업을 수행할 수 있습니다. <select> <선택> <option value="" selected disabled hidden><option value="선택한 비활성화 숨김>Choose here</option> 여기서 선택 </option> <option value="1">One</option> <option value="1"> 1개 </option> <option value="2"<옵션값="2">Two</option> 2개 </옵션> <option value="3"<옵션값="3">Three</option> 3가지 </옵션> <option value="4">Four</option> <option value="4"> 4개 </option> <option value="5">Five</option> <option value="5"> 5개 </option></select> </select> Complete example: 완전한 예: <select name="hall" id="hall"> <select name="hall" id="hall"> <option>1</option> <옵션> 1 </option> <option>2</option> <옵션> 2 </option> <option selected>3</option> <option selected > 3 </option> <option>4</option> <옵션> 4 </option> <option>5</option> <옵션> 5 </option></select> </select> I came across this question, but the accepted and highly upvoted answer didn't work for me.우연히 이 질문을 접했지만, 받아들여지고 투표율이 높은 답변은 나에게 효과가 없었다. It turns out that if you are using React, then setting selected doesn't work.React 를 사용하고 있는 경우는, 선택한 설정이 동작하지 않는 것을 알 수 있습니다. Instead you have to set a value in the <select> tag directly as shown below: 대신 다음과 같이 <select> 태그에 직접 값을 설정해야 합니다.<select value="<값 선택="B"> B"> <option value="<옵션값="A">Apple</option> A"> 애플 </옵션> <option value="<옵션값="B">Banana</option> B">바나나 </option> <option value="<옵션값="C">Cranberry</option> C"> Cranberry </option></select> </select> Read more about why here on the React page.React 페이지에서 그 이유에 대해 자세히 알아보십시오.You can do it like this: 다음과 같이 할 수 있습니다.<select name="hall" id="hall"> <select name="hall" id="hall"> <option> 1 </option> <옵션> 1 </옵션> <option> 2 </option> <옵션> 2 </옵션> <option selected> 3 </option> <옵션 선택> 3 </옵션> <option> 4 </option> <옵션> 4 </옵션> <option> 5 </option> <옵션> 5 </옵션></select> </select> Provide "selected" keyword inside the option tag, which you want to appear by default in your drop down list.옵션 태그 내에 "selected" 키워드를 입력합니다.이 키워드는 기본적으로 드롭다운목록에 표시됩니다. Or you can also provide attribute to the option tag i.e.또는 옵션 태그에 속성을 제공할 수도 있습니다. <option selected="selected">3</option> <option selected="selected"> 3 </option>if you want to use the values from a Form and keep it dynamic try this with php 폼의 값을 사용하여 역동적으로 유지하려면 php를 사용해 보십시오.<form action="..<폼액션="../<SamePage>/" method="post"> /<SamePage>/" method="post"> <?php <?개요 $selected = $_POST['select'];$selected = $_POST['select']; ?> ?> <select name="select" size="1"> <select name="select" size="1"> <option <?php if($selected == '1'){echo("selected");}?< option < ? selected if selected == '1' ) { selected " ; } 。>>1</option> 1 </옵션> <option <?php if($selected == '2'){echo("selected");}?< option < ? selected if selected == '2' ) { selected " ; } 。>>2</option> 2 </옵션> </select> </select></form> </폼>Best way in my opinion: 내 생각에 가장 좋은 방법:<select> <선택> <option value="" selected="selected" hidden="hidden"<option value=" selected=" selected" hidden=" hidden>Choose here</option> 여기서 선택 </option> <option value="1">One</option> <option value="1"> 1개 </option> <option value="2"<옵션값="2">Two</option> 2개 </옵션> <option value="3"<옵션값="3">Three</option> 3가지 </옵션> <option value="4">Four</option> <option value="4"> 4개 </option> <option value="5">Five</option> <option value="5"> 5개 </option></select> </select> Why not disabled?무효가 되지 않는 이유 When you use disabled attribute together with <button type="reset"비활성 속성을 <button type="disabled"와 함께 사용하는 경우>Reset</button> value is not reset to original placeholder.리셋 </버튼> 값은 원래 자리 표시자로 리셋되지 않습니다. Instead browser choose first not disabled option which may cause user mistakes.대신 브라우저는 먼저 비활성화되지 않은 옵션을 선택합니다.이 옵션은 사용자의 실수를 일으킬 수 있습니다. Default empty value 디폴트 빈 값Every production form has validation, then empty value should not be a problem.모든 생산 양식에는 검증이 있으므로 빈 값은 문제가 되지 않습니다. This way we may have empty not required select.이렇게 하면 빈칸이 선택되지 않을 수 있습니다. XHTML syntax attributes XHTML 구문 속성selected="selected" syntax is the only way to be compatible with both XHTML and HTML 5. It is correct XML syntax and some editors may be happy about this.selected="selected" 구문은 XHTML 및 HTML 5와 모두 호환되는 유일한 방법입니다. XML 구문이 올바르고 일부 편집자는 이에 만족할 수 있습니다. It is more backward compatible.더 하위 호환성이 있습니다. If XML compliance is important you should follow the full syntax.XML 준수가 중요한 경우 완전한 구문을 따라야 합니다.I prefer this: 나는 이것을 선호한다:<select> <선택> <option selected hidden><옵션 선택 숨김>Choose here</option> 여기서 선택 </option> <option value="1">One</option> <option value="1"> 1개 </option> <option value="2"<옵션값="2">Two</option> 2개 </옵션> <option value="3"<옵션값="3">Three</option> 3가지 </옵션> <option value="4">Four</option> <option value="4"> 4개 </option> <option value="5">Five</option> <option value="5"> 5개 </option></select> </select> 'Choose here' disappears after an option has been selected.옵션을 선택하면 '여기에서 선택'이 사라집니다.An improvement for nobita's answer.노비타의 대답에 대한 개선. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.또한 '여기에서 선택' 요소를 숨겨 드롭다운 목록의 시각적 보기를 개선할 수 있습니다. <select> <선택> <option selected disabled hidden><옵션 선택 해제 숨김>Choose here</option> 여기서 선택 </option> <option value="1">One</option> <option value="1"> 1개 </option> <option value="2"<옵션값="2">Two</option> 2개 </옵션> <option value="3"<옵션값="3">Three</option> 3가지 </옵션> <option value="4">Four</option> <option value="4"> 4개 </option> <option value="5">Five</option> <option value="5"> 5개 </option></select> </select> Another example; using JavaScript to set a selected option.다른 예로는 JavaScript를 사용하여 선택한 옵션을 설정하는 방법이 있습니다. (You could use this example to for loop an array of values into a drop down component) (이 예에서는 값 배열을 드롭다운컴포넌트에 루프하기 위해 사용할 수 있습니다).<select id="yourDropDownElementId"><select/> <select id="your Drop Down Element Id"> <select/>// Get the select element // 선택 요소 가져오기var select = document.getElementById("yourDropDownElementId");var = document.getElementById("yourDropDownElementId")를 선택합니다. // Create a new option element // 새 옵션 요소 만들기var el = document.createElement("option");var el = document.createElement("옵션"); // Add our value to the option // 옵션에 가치 추가el.textContent = "Example Value";el.textContent = "예시 값"; el.value = "Example Value";el.value = "예시값"; // Set the option to selected // 옵션을 선택됨으로 설정el.selected = true; el.selected = 참;// Add the new option element to the select element // 새 옵션 요소를 선택 요소에 추가합니다.select.appendChild(el); select.append Child(el);The selected attribute is a boolean attribute.선택한 특성이 부울 특성입니다. When present, it specifies that an option should be pre-selected when the page loads.존재하는 경우 페이지가 로드될 때 옵션을 미리 선택해야 함을 지정합니다. The pre-selected option will be displayed first in the drop-down list.미리 선택한 옵션이 드롭다운 목록에 먼저 표시됩니다. <select> <선택> <option value="volvo">Volvo</option> <option value="volvo">볼보 </option> <option value="saab">Saab</option> <option value="saab"> Saab </option> <option value="vw"><옵션값="vw">VW</option> VW </옵션> <option value="audi" selected><option value="selected">Audi</option> Audi </옵션></select> </select>If you are in react you can use defaultValue as attribute instead of value in the select tag.반응 중인 경우 선택 태그의 값 대신 defaultValue를 속성으로 사용할 수 있습니다.If you are using select with angular 1, then you need to use ng-init, otherwise, second option will not be selected since, ng-model overrides the defaul selected value angular 1에서 select를 사용하는 경우 ng-init을 사용해야 합니다.그렇지 않으면 ng-model이 선택한 값을 덮어쓰기 때문에 두 번째 옵션은 선택되지 않습니다.<select ng-model="sortVar" ng-init='sortVar="stargazers_count"'> <ng-model="sortVar" ng-init='sortVar="stargazers_count" 선택> <option value="name">Name</option> <option value="name"> 이름 </option> <option selected="selected" value="stargazers_count">Stars</option> <option selected="selected" value="stargazers_count"> Stars </option> <option value="language"<option value="언어">Language</option> > 언어 </옵션></select> </select>I would just simply make the first select option value the default and just hide that value in the dropdown with HTML5's new "hidden" feature.첫 번째 선택 옵션 값을 기본값으로 설정하고 HTML5의 새로운 "숨김" 기능을 사용하여 드롭다운에서 해당 값을 숨깁니다. Like this: 다음과 같이 합니다. <select name="" id=""> <select name=" id="> <option hidden value="default"><옵션 숨김값="default">Select An Option</option> 옵션 선택 </option> <option value="1">One</option> <option value="1"> 1개 </option> <option value="2"<옵션값="2">Two</option> 2개 </옵션> <option value="3"<옵션값="3">Three</option> 3가지 </옵션> <option value="4">Four</option> <option value="4"> 4개 </option> </select> </select>value attribute of tag is missing, so it doesn't show as u desired selected.태그의 값 속성이 누락되어 원하는 대로 선택되지 않았습니다. By default first option show on dropdown page load, if value attribute is set on tag....기본적으로는 값 속성이 태그에 설정되어 있는 경우 드롭다운 페이지 로드에 첫 번째 옵션이 표시됩니다. I got solved my problem this way나는 이런 식으로 문제를 해결했다.This example has been tested to work with multiple <select> elements on the page, and can also work with normal text elements.이 예에서는 페이지의 여러 <select> 요소에서 동작하도록 테스트되었으며 일반 텍스트 요소에서도 동작할 수 있습니다. It has not been tested for setting the value to more than one selection when <select multiple="true">, however you can probably modify this sample to support that.<select multiple="true">에서 값을 여러 선택 항목으로 설정하는 테스트를 거치지 않았지만, 이 샘플을 수정하여 이를 지원할 수 있습니다. Add an attribute data-selected to each <select> element and set the value(s) to the value of the option you wish to have selected.선택한 속성 데이터를 각 <select> 요소에 추가하고 값을 선택한 옵션의 값으로 설정합니다. Use javascript's querySelectorAll() to select all elements that have the custom attribute you just added.javascript의 querySelectorAll()을 사용하여 방금 추가한 커스텀 속성을 가진 모든 요소를 선택합니다. In the following example, when run, the first <select> should show option with the value user as selected, and the second <select> should show the option with the value admin as selected.다음 예제에서는 실행 시 첫 번째 <select>는 값 user를 선택한 옵션을 표시하고 두 번째 <select>는 값 admin을 선택한 옵션을 표시합니다. document.문서.querySelectorAll('[data-selected]').query Selector All('[데이터 선택]')forEach(e => { 각(e = > { e.value = e.dataset.e.value = e.value.selected 선택된}); }); <select data-selected="user" class="form-control" name="role"> < select data - selected = "user" class = " form - control " name = " role" > <option value="public"> <option value="public"> Pubblica 푸블리카 </option> </옵션> <option value="user"> <option value="user"> Utenti 우텐티 </option> </옵션> <option value="admin"> <option value="admin"> Admin 관리자 </option> </옵션></select> </select> <select data-selected="admin" class="form-control" name="role2"> <data-selected="admin" class="form-control" name="role2" 선택> <option value="public"> <option value="public"> Pubblica 푸블리카 </option> </옵션> <option value="user"> <option value="user"> Utenti 우텐티 </option> </옵션> <option value="admin"> <option value="admin"> Admin 관리자 </option> </옵션></select> </select> I used this php function to generate the options, and insert it into my HTML 이 php 함수를 사용하여 옵션을 생성하고 HTML에 삽입합니다.<?php <?개요 # code to output a set of options for a numeric drop down list 숫자 드롭다운 목록의 옵션 세트를 출력하는 # 코드 # parameters: (start, end, step, format, default) 파라미터 수: (시작, 종료, 스텝, 포맷, 기본값) function numericoptions($start, $end, $step, $formatstring, $default) 함수 숫자 옵션(start, $end, $step, $formatstring, $default) { { $retstring = ""; $retstring = " , for($i = $start; $i <= $end; $i = $i + $step) for hargi = $start; $i <= $end; $i = $i + $step) { { $retstring = $retstring . '<OPTION '; $retstring = $retstring . ' < OPTION ' ; $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"'; $retstring = $retstring . 'value=' . sprintfretstring formatstring , $i ) . ' ; if($default == $i) if440default == $i) { { $retstring = $retstring . ' selected="selected"'; $retstring = $retstring . ' selected = " selected " ; } } $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> '; $retstring = $retstring . ' > ' . sprintf' formatstring , $i ) . ' //OPTION > ' ; } } return $retstring; $retstring을 반환한다. } } ?> ?> And then in my webpage code I use it as below; 그리고 제 웹페이지 코드에는 다음과 같이 사용합니다.<select id="endmin" name="endmin"> <select id="endmin" name="endmin"> <?php echo numericoptions(0,55,5,'%02d',$endmin); ?<?secho 숫자 옵션(0,55,5,'%02d',$endmin);> ></select> </select> If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.페이지가 로드될 때마다 _POST 변수에서 $endmin이 생성되면(그리고 이 코드가 게시되는 형식 내에 있음) 이전에 선택한 값이 기본적으로 선택됩니다.This code sets the default value for the HTML select element with PHP.이 코드는 HTML 선택 요소의 기본값을 PHP로 설정합니다. <select name="hall" id="hall"> <select name="hall" id="hall"><?php <?개요 $default = 3; $default = 3; $nr = 1; $140 = 1; while($nr < 10){ 한편 < 10 ) { if($nr == $default)ifsyslog == $default){ { echo "<option selected=\"selected\">". $nr ."</option>"; echo "< option selected =\"selected\">."$cho "/option\" } } else{ 그렇지 않으면 { echo "<option>".에코 "<option >". $nr ."</option>"; $140 "/option >", } } $nr++;$180++; } }?> ?></select> </select>You can use: 다음을 사용할 수 있습니다.<option value="someValue" selected><option value="some Value" 선택>Some Value</option> 일부 값 </옵션> instead of, 대신,<option value="someValue" selected = "selected"<option value="some Value" 선택됨= "선택됨">Some Value</option> > 일부 가치 </옵션> both are equally correct.둘 다 똑같이 맞습니다.Set selected="selected" where is option value is 3 selected="selected"를 설정합니다. 여기서 is option value는 3입니다.please see below example 아래의 예를 참조해 주세요.<option selected="selected" value="3" >3</option> <option selected="selected" value="3"> 3 </option>I myself use it 제가 쓰고 있습니다.<select selected=''> <선택한 선택='> <option value=''></option> <option value='> </option> <option value='1'>ccc</option> <option value='1'> ccc </option> <option value='2'>xxx</option> <option value='2'>xx </option> <option value='3'>zzz</option> <option value='3'>zz </option> <option value='4'>aaa</option> < option value = '4' > 명령어 </option> <option value='5'>qqq</option> <option value='5'>qq </option> <option value='6'>wwww</option> <option value='6'>www</option></select> </select>You just need to put attribute "selected" on a particular option instead direct to select element.요소를 직접 선택하는 대신 특정 옵션에 "selected" 속성을 지정하기만 하면 됩니다. Here is snippet for same and multiple working example with different values.다음은 값이 다른 동일한 여러 작업 예제의 일부입니다. Select Option 3 :- [ Option 3 : - ]를 선택합니다. <select name="hall" id="hall"> <select name="hall" id="hall"> <option>1</option> <옵션> 1 </option> <option>2</option> <옵션> 2 </option> <option selected="selected">3</option> <option selected="selected"> 3 </option> <option>4</option> <옵션> 4 </option> <option>5</option> <옵션> 5 </option> </select> </select> <br/> <br/> <br/> <br/> <br/> <br/> Select Option 5 :- [ Option 5 : - ]를 선택합니다. <select name="hall" id="hall"> <select name="hall" id="hall"> <option>1</option> <옵션> 1 </option> <option>2</option> <옵션> 2 </option> <option>3</option> <옵션> 3 </option> <option>4</option> <옵션> 4 </option> <option selected="selected">5</option> <option selected="selected"> 5 </option> </select> </select> <br/> <br/> <br/> <br/> <br/> <br/> Select Option 2 :- [ Option 2 : - ]를 선택합니다. <select name="hall" id="hall"> <select name="hall" id="hall"> <option>1</option> <옵션> 1 </option> <option selected="selected">2</option> <option selected="selected"> 2 </option> <option>3</option> <옵션> 3 </option> <option>4</option> <옵션> 4 </option> <option>5</option> <옵션> 5 </option> </select> </select> Default selected value is Option-4 기본적으로 선택된 값은 Option-4입니다. <html:select property="status" value="<value: select property="status" value="OPTION_4" styleClass="form-control"> OPTION_4" styleClass="폼컨트롤"> <html:option value="">Select</html:option> <value="> 선택 </html: option> <html:option value="<value: option valueOPTION_1" >Option-1</html:option> OPTION_1" > OPTION-1 </html: option> <html:option value="<value: option valueOPTION_2" >Option-2</html:option> OPTION_2" > OPTION-2 </html: option> <html:option value="<value: option valueOPTION_3" >Option-3</html:option> OPTION_3" > OPTION-3 </html: option> <html:option value="<value: option valueOPTION_4" >Option-4</html:option> OPTION_4" > OPTION-4 </html: option> <html:option value="<value: option valueOPTION_5" >Option-5</html:option> OPTION_5" > OPTION-5 </html: option> </html:select> </filename: 선택>You will need an "id" attribute in each option for this solution to work: 이 솔루션이 기능하려면 각 옵션에 "id" 속성이 필요합니다. <script> <스크립트>function select_option (id,value_selected) { 함수 select_option(id, value_selected) { var select; var select(바리 선택); select = document.getElementById(id); = document.getElementById(id)를 선택합니다. if (select == null) return 0; (선택 == null)이 0을 반환하는 경우; var option; var 옵션 option = select.options.namedItem(value_selected)옵션 = select.options.namedItem(value_selected); ; if (option == null) return 0; (옵션 == null)이 0을 반환하는 경우; option.선택.selected = "selected"; selected = "selected"; return true; true를 반환한다.} }</script> </script> <select name="hall" id="hall"> <select name="hall" id="hall"> <option id="1">1</option> <option id="1"> 1 </option> <option id="2">2</option> <option id="2">2 </option> <option id="3">3</option> <option id="3">3 </option> <option id="4">4</option> <option id="4">4 </option> <option id="5">5</option> <option id="5">5 </option></select> </select><script>select_option ("hall","3");</script> <script> select_option("hall", 3";/script> The function first tries to find the <select> with the id, then it will search for the value_selected in the <select> options and if it finds it, it will set the selected attribute returning true.함수는 먼저 ID를 사용하여 <select>를 검색한 후 <select> 옵션에서 value_selected를 검색하여 찾은 경우 선택한 속성이 true를 반환하도록 설정합니다. False otherwise그렇지 않으면 False입니다.The problem with <select> is, it's sometimes disconnected with the state of what's currently rendered and unless something has changed in the option list, no change value is returned.<select>의 문제는 현재 렌더링된 내용의 상태와 연결이 끊길 수 있으며 옵션목록에서 변경이 없는 한 변경 값이 반환되지 않는다는 것입니다. This can be a problem when trying to select the first option from a list.이는 목록에서 첫 번째 옵션을 선택하려고 할 때 문제가 될 수 있습니다. The following code can get the first-option the first-time selected, but onchange="changeFontSize(this)" by its self would not.다음 코드는 처음 선택한 첫 번째 옵션을 얻을 수 있지만 onchange="changeFontSize(this)" 자체로는 얻을 수 없습니다. There are methods described above using a dummy option to force a user to make a change value to pickup the actual first value, such as starting the list with an empty value.위의 방법은 더미 옵션을 사용하여 사용자가 실제 첫 번째 값을 선택하도록 강제하는 방법(예: 빈 값으로 목록을 시작하는 방법)입니다. Note: onclick would call the function twice, the following code does not, but solves the first-time problem.메모: 클릭 시 함수가 두 번 호출됩니다.다음 코드는 호출되지 않지만 첫 번째 문제는 해결됩니다. <label>Font Size</label> <label> 글꼴 크기 </label><select name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)"> <name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)" 선택> <option value="small">Small</option> <option value="small"> 소형 </option> <option value="medium"<옵션값="중간">Medium</option> > 중간 </옵션> <option value="large"<옵션값="대형">Large</option> > 대형 </옵션> <option value="extraLarge"><옵션값="extraLarge">Extra large</option> 초대형 </옵션></select> </select> <script> <스크립트>function changeFontSize(x){ 함수 changeFontSize(x){ body=document.getElementById('body')body=body.getElementById('body'); ; if (x.value=="extraLarge") { (x.value=="extraLarge")의 경우, body.style.fontSize="25px"; body.style.fontSize="25px"; } else { } 기타 { body.style.fontSize=x.value; body.style.fontSize=x.value; } }} }</script> </script>I use Angular and i set the default option by Angular를 사용하여 기본 옵션을 설정합니다.HTML Template HTML 템플릿<select #selectConnection [(ngModel)]< # select Connection [ (ng Model ) ]를 선택합니다.="selectedVal" class="form-control col-sm-6 " max-width="100px" title="="selectedVal" class="form-control col-sm-6 "max-width="100px" title="Select" 선택" data-size="10"> data-size="10"> <option >test1</option> <옵션> test1 </option> <option >test2</option> <option> test2 </option> </select> </select> Script: 스크립트:sselectedVal:any="test1"; sselectedVal:any="test1";You can try like this 이렇게 해봐도 돼. <select name="hall" id="hall"> <select name="hall" id="hall"> <option>1</option> <옵션> 1 </option> <option>2</option> <옵션> 2 </option> <option selected="selected">3</option> <option selected="selected"> 3 </option> <option>4</option> <옵션> 4 </option> <option>5</option> <옵션> 5 </option> </select> </select>To set the default using PHP and JavaScript: PHP 및 JavaScript를 사용하여 기본값을 설정하려면:State: <select id="State"> 상태: <select id="State"><option value="" selected disabled hidden></option> <option value=" selected disabled hidden > </<option value="<옵션값="Andhra Pradesh">Andhra Pradesh</option> 안드라프라데시">안드라프라데시 </option><option value="<옵션값="Andaman and Nicobar Islands"안다만 니코바르 제도>Andaman and Nicobar Islands</option> > 안다만과 니코바르 제도 </option>. .. .<option value="<옵션값="West Bengal"웨스트벵골 주>West Bengal</option> > 웨스트벵골 </옵션></select> </select><?php <?개요if(isset($_GET['State']))if(isset($_GET['State']){ { echo <<<heredoc echo << edoc ><script> <스크립트>document.getElementById("State").document.getElementById("State")입니다.querySelector('option[value="{$_GET['State']}"]').querySelector('option[value="{$_GET['State'}}]])').selected = true; 선택한 = true;</script> </script>heredoc; 유전하다} }?> ?>This is simple method to make default option selected.이 방법은 기본 옵션을 선택하는 간단한 방법입니다. Can be used for multiple selects on an HTML page.HTML 페이지에서 여러 선택 항목에 사용할 수 있습니다. The method: 방법: Find every select 모든 선택 항목 찾기 Read the id and value of that select 선택한 ID와 값을 읽습니다. Make the option selected 옵션을 선택합니다. Note: 주의: Every select must have ID to avoid conflict 충돌을 피하기 위해 모든 선택 항목에는 ID가 있어야 합니다. $(document).$(표준)ready(function() { ready(function) { // Loop for every select in page // 선택 페이지마다 루프 $('select').each(function(index, id) { $('select').각(함수(색인, id) { // Get the value // 값을 가져옵니다. var theValue = $(this).attr('value');var theValue = $(this.attr'value'); // Get the ID // 아이디 가져오기 var the변하다ID = $(this).attr('id');ID = $(this.attr'id'); // Make option selected // 옵션 만들기 선택됨 $('select#' + the$('select #' + theID + ' option[value=' + theValue + ']').attr('selected', true);ID + 'option [ value = ' + value + ' ] . attr " selected " , true ) ; }); });}); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"> </script> <select id="sport" name="sport" class="autoselect" value="golf"> <select id="sport" name="sport" class="autoselect" value="class"><option value="basket">Basket Ball</option> <option value="basket"> 농구공 </option><option value="tennis"<option value = "선택사항">Tennis</option> >테니스 </옵션><option value="golf">Golf</option> <option value="golf"> 골프 </option><option value="bowling">Bowling</option> <option value="bowling"> 볼링 </option></select> </select> <hr> <hr> <select id="tools" name="tools" class="autoselect" value="saw"> <select id="tools" name="tools" class="autoselect" value="saw"><option value="hammer"<option value = "선택사항">Hammer</option> > 해머 </옵션><option value="drill">Drill</option> <option value="drill"> 드릴 </option><option value="screwdriver">Screwdriver</option> <option value="screwdriver"> 스크루드라이버 </option><option value="saw"<옵션값="쏘우">Saw</option> 톱 </옵션><option value="wrench"><option value="filename">Wrench</option> 렌치 </옵션></select> </select> I was having some troubles with it because I need some way to choose the option dynamically accordingly to the value that I have in the database.데이터베이스에 있는 값에 따라 동적으로 옵션을 선택할 수 있는 방법이 필요하기 때문에 문제가 있었습니다. The script bellow works like a charm to me: 아래 대본은 내게 마법처럼 작용한다.<?php <?개요//pick the value of database //데이터베이스 값 선택$selected_sexo = $query['s_sexo'];$selected_sexo = $selected['s_sexo']; ?> ?> <select name="s_sexo" id="s_sexo" required> <이름="s_sexo" id="s_sexo" 필수> <option <?php if($selected_sexo == 'M'){echo("selected");}?<옵션 <?selected_sexo == 'M'){echo("selected");}?> value="> 값="M">M</option> M"> M </option> <option <?php if($selected_sexo == 'F'){echo("selected");}?<옵션 <?selected_sexo == 'F'){echo("selected");}?> value="> 값="F">F</option> F"> F </option></select> </select>Reference언급URL : https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-elementURL : https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element
반응형
공유하기
게시글 관리
sourcejob
'
programing
' 카테고리의 다른 글
WPF 응용 프로그램에서 응용 프로그램 디렉터리 가져오기
(0)
2023.04.09
SQL Server에 IP 주소를 저장하기 위한 데이터 유형
(0)
2023.04.09
SQL Server에서 여러 행에서 하나의 쉼표로 구분된 값 사용
(0)
2023.04.09
현재 Git 작업 트리에서 로컬(추적되지 않은) 파일을 제거하려면 어떻게 해야 합니까?
(0)
2023.04.09
python xlrd 형식이 지원되지 않거나 파일이 손상되었습니다.
(0)
2023.04.09
티스토리툴바