问题
I'm using PHP, Smarty and MySQL for my website. I'm having a select control. The code for it is as follows:
<select name="contact_label" id="set_contact_label">
<option value=""> -- Select label-- </option>
{if $enquiries_labels}
{foreach from=$enquiries_labels item=label key=key}
<option value="{$key}" {if $contact_label == $key} selected="selected" {/if}>{$label}</option>
{/foreach}
{/if}
</select>
Equivalent HTML output is as follows:
<select name="contact_label" id="contact_label">
<option value=""> -- Select label-- </option>
<option value="0" selected="selected">New Enquiry</option>
<option value="1" >Retail Enquiry</option>
<option value="2" >Feedback</option>
<option value="3" >Payment Query</option>
<option value="4" >Package Query</option>
<option value="5" >Test Query</option>
</select>
Now my issue is I want the option --Select label-- selected by default when the if condition gets failed. If the if condition is satisfied then that option value should get selected. Now what's happening is the value "New Enquiry" is kept selected in the select box when the if condition fails. Actually I want the value --Select label-- to be selected by default when the if condition fails. I tried a lot to achieve this but couldn't succeed. Can anyone please help me in this regard?
回答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>
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.
回答2:
Just use a strict comparison operator:
{if $contact_label === $key}
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.
回答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>
来源:https://stackoverflow.com/questions/20969801/how-to-keep-a-specific-value-selected-in-a-select-html-control-in-following-scen