How To Keep A Specific Value Selected In A Select HTML Control In Following Scenario? July 30, 2022 Post a Comment I'm using PHP, Smarty and MySQL for my website. I'm having a select control. The code for it is as follows: Solution 1: Well, maybe there's more elegant way, but since maybe you do not want to overload the server side you can use javascript to find if any of the elements has selected attr, and if none - to add to the first one. <script> $( document ).ready(function() { var opts = document.getElementById("contact_label").options; var i, len = opts.length; var hasAttr = false; for(i = 0; i < len; i++) { if (opts[i].getAttribute("selected" ) != null ) { hasAttr = i; break; } } if(!hasAttr) { $("select option[value='']").attr("selected","selected"); } }); </script> Copy This might be overcomplicated, I tried it this way, because just ussing prop() or attr() will add selected attribute, but if you select manualy another one the parser will think this option has selected attribute and after refresh it won't get the real option which has the attribute. Solution 2: Just use a strict comparison operator: {if $contact_label === $key} Copy also, have you tried using {html_options}? not sure, as I seldom use a 0 index value in my selects, but it probably already takes care of it. Solution 3: You should try this In php file you need : $smarty->assign('MyArray',$enquiries_labels); $smarty->assign('selectedOption',0); Now in template <select name="contact_label" id="set_contact_label"> <option value="0">Please Select label</option> {html_options options=$MyArray selected=$selectedOption} </select> Copy Share Post a Comment for "How To Keep A Specific Value Selected In A Select HTML Control In Following Scenario?"
Post a Comment for "How To Keep A Specific Value Selected In A Select HTML Control In Following Scenario?"