如何使用jquery使用选择选项的值更改提交按钮的颜色

时间:2019-04-30 15:10:49

标签: javascript jquery

例如,我想更改提交按钮的颜色,例如:跑车的购买者单击以下选项之一: 1.法拉利 2.兰博基尼 3.保时捷

根据所选选项中的所选汽车,提交按钮应将颜色变为绿色。我该如何使用jquery库和代码?

我尝试了以下代码,但是不起作用!

jquery代码:

`$(document).ready(function() {
    $('select.cars').bind(function(){
    $('.SubmitButton').addClass('ButtonColor'); 
    });
    });`

html代码:

`<select class="cars">
      <option value="ferrari">Ferrari</option>
      <option value="lamborghini">Lamborghini</option>
      <option value="porsche">Porsche</option>
    </select> 
      <input class="SubmitButton" type="submit" value="Go to Car">`

CSS代码:

.SubmitButton {width:150px;} .ButtonColor {color:green;}

我的代码无法正常工作-请问有人如何修复它?

2 个答案:

答案 0 :(得分:1)

您需要更改绑定才能更改事件

addV()

$(document).ready(function() {
    $('select.cars').change(function(){
      if($(this).val() == 'lamborghini'){
         $('.SubmitButton').removeClass('ButtonColor1');
         $('.SubmitButton').addClass('ButtonColor');
      }else if($(this).val() == 'porsche'){
      $('.SubmitButton').removeClass('ButtonColor');
         $('.SubmitButton').addClass('ButtonColor1');
      }
    });
});
$(document).ready(function() {
    if($("select.cars").val() == ""){
        $(".SubmitButton").attr("disabled", "disabled");
      }
    $('select.cars').change(function(){
      if($(this).val() == 'lamborghini'){
         $(".SubmitButton").removeAttr("disabled");
         $('.SubmitButton').removeClass('ButtonColor1');
         $('.SubmitButton').addClass('ButtonColor');
         
      }else if($(this).val() == 'porsche'){
       $(".SubmitButton").removeAttr("disabled");
      $('.SubmitButton').removeClass('ButtonColor');
         $('.SubmitButton').addClass('ButtonColor1');
      }
      else if($(this).val() == 'ferrari'){
       $(".SubmitButton").removeAttr("disabled");
      $('.SubmitButton').removeClass('ButtonColor');
         $('.SubmitButton').addClass('ButtonColor2');
      }
      else if($("select.cars").val() == ""){
        $(".SubmitButton").attr("disabled", "disabled");
      }
    });
    
    var mstart = $("select.cars option").filter(function() { return $(this).text().indexOf("M") === 0; })
    
    
});

Updated:

If you want to find option start with M you can use this 

var mstart = $("select.cars option").filter(function() { return $(this).text().indexOf("M") === 0; })
.SubmitButton {width:150px;}
.ButtonColor {color:green;}
.ButtonColor1 {color:red;}
.ButtonColor2 {color:blue;}

答案 1 :(得分:0)

<div class="form-group">
    <label class="col-sm-6 col-form-label" for="name">Account Number</label>
    <input type="text" class="form-control col-sm-3" 
    [(ngModel)]="record.accountid" name="accountid">
    <button (click)="loadData()">Load</button>
</div>

<app-console [consoleMessages]="consoleMessages"></app-console>