如何在PHP代码中获取下拉框的选定选项值
我有一个下拉框,列出了一组徽标,如花,蝴蝶等。
Logo
<option id="" value="">
假设我从下拉框中选择徽标’Flower’,我希望花卉图片以div显示。 这是我必须显示图片的div:
<img height="50" width="50" src="https://stackoverflow.com/FormBuilder/app/webroot/img/themes/" class="float_left user_profile_image user_profile_image" alt="Default50"/>
此代码的问题是它显示表中找到的所有图片。 因为在我的控制器代码中,我只给出了’Logo’的属性id,但是没有给出哪个徽标。
$this->set('defaultLogos',$this->Subproperty->find('all',array('conditions'=>array('Subproperty.property_id'=>1,'Subproperty.values'=>"Flower"))));
在这里,我有硬编码’花’,所以我只得到花卉图片。
如果我从下拉框中选择徽标,如何将所选值传递给控制器代码? 或者,如果我使用jQuery获取所选的徽标名称,如何在foreach循环中的if条件中使用该值?
我正在使用CakePHP
框架。
$("#logoMenu option").click(function(){ selectedLogo=$(this).attr("value"); $('#subproperty_id').val($(this).attr("id")); if(selectedLogo=="Your logo"){ $("#themes_upload").show(); } else{ alert(selectedLogo); $("#themes_upload").hide(); $("#theme_logos").show(); } });
编辑:
现在我尝试了一个AJAX POST,我将所选的徽标传递给控制器的同一个动作。 当我在ajax函数的success函数中提醒传递的值但是没有出现图片时,我得到了值。
$("#logoMenu option").click(function(){ selectedLogo=$(this).attr("value"); $('#subproperty_id').val($(this).attr("id")); if(selectedLogo=="Your logo"){ $("#themes_upload").show(); } else { alert(selectedLogo); $.ajax({ type: "POST", url: "http://localhost/FormBuilder/index.php/themes/themes/", async: false, data: "selectedLogo="+selectedLogo, success: function(msg){ alert( "Data Saved: " + msg); } }); $("#themes_upload").hide(); $("#theme_logos").show(); } function themes(){ $this->set('themes',$this->Theme->find('all')); $logo=$this->params['form']['selectedLogo']; echo "logo:".$logo; $this->set('defaultLogos',$this->Subproperty->find('all',array('conditions'=>array('Subproperty.property_id'=>1,'Subproperty.values'=>$logo)))); }
当我尝试在页面中显示图像时,它不会出现。 是因为div show命令是在AJAX请求之后吗?
如果您可以将图像的src放在您的值中选择选项或将隐藏div中的图像属性放入您在选择选项中显示的项目的值,那将非常简单。 喜欢:
CASE 1)将img src放在option的value属性中
$("#logoMenu").change(function(){ var logo=$("#logoMenu option:selected").attr("value"); $("#theme_logos img").hide(); $("#theme_logos img[src='"+logo+"']").show(); })
情况2)将图像的alt设置为选项中的值
$("#logoMenu").change(function(){ var alt=$("#logoMenu option:selected").attr("value"); $("#theme_logos img").hide();//hide any other logo that is showing $("#theme_logos img[alt='"+alt+"']").show();//show selected logo })
编辑: – 测试代码(案例2)