2015-12-12 31 views
-3

我有一個文本框,用於輸入汽車註冊號碼。註冊基於年份,格式爲GT 74454 12,最後一位數12代表年份2012這意味着這輛車在2012註冊。我想要一個將自動檢測最後兩位數字並影響下拉列表值的腳本。基於文本域中最後2個變量的下拉列表更改值

例如,如果年份範圍從09 - 12下拉的值應該是紅色。如果範圍從13 - 16,則下拉列表的值應變爲藍色。

HTML

<form id="form1" name="form1" method="post" action=""> 
    <label for="car_no"></label> 
    <input type="text" name="car_no" id="car_no" /> 
    <label for="select"></label> 
    <select name="select" id="select"> 
    <option>Color Code</option> 
    <option>Red</option> 
    <option>Blue</option> 
    <option>White</option> 
    </select> 
</form> 

http://jsfiddle.net/y18c2hzo/

EDIT 
there are some registrations that comes in a different format too which goes like this "GT 74454 X". How do i make the script autodect if the last digit is an alphabet the value shoud change to white 
+1

你可以請張貼迄今爲止已經嘗試過的js嗎? – Rhono

+0

2009年之前註冊的汽車應該發生什麼和/或不適合這種格式? –

+0

@DavidThomas,這是一個偉大的建議,我修改了帖子 –

回答

2

試試以下代碼。

$(document).ready(function(){ 
 
$("#car_no").change(function(){ 
 
    var value= $(this).val(), 
 
     year = value.split(" ")[2]; 
 
    if(year >=9 && year<=12) 
 
    \t $("#select").val("Red") 
 
    if(year >=13 && year<=16) 
 
    \t $("#select").val("Blue") 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="form1" name="form1" method="post" action=""> 
 
    <label for="car_no">car number</label> 
 
    <input type="text" name="car_no" id="car_no" /> 
 
    <label for="select"></label> 
 
    <select name="select" id="select"> 
 
    <option>Color Code</option> 
 
    <option>Red</option> 
 
    <option>Blue</option> 
 
    <option>White</option> 
 
    </select> 
 
</form>

希望這會幫助你。

+0

謝謝,劇本的作品,也有不同的格式,就像這樣的「GT 74454 X」。如果最後一位數字是字母表,數值應該變成白色,我該如何使腳本自動檢測 –

+0

檢查此小提琴。 https://jsfiddle.net/ooz0wLr3/。使用** isNaN()**方法可以檢查值是否爲數字。 – balachandar

+0

哇,謝謝它的工作。耶穌祝福你 –

0

嘗試

$('select').on('change', function() { 
    alert(this.value); // or $(this).val() 
    if(your condition){ 
    $("select").css("background-color", "red"); 
    }else if (your condition){ 
    ///your codes 
    } 
}); 
1

我做了一個簡單的例子here

$('#car_no').keyup(function (event) { 
    var value = $(event.target).val(); 
    var year = parseInt(value.trim().substr(-2), 10); 
    if (year >= 9 && year <= 12) { 
     $('#select').val('Red'); 
    } else if (year >= 13 && year <= 16) { 
     $('#select').val('Blue'); 
    } 
}); 

該代碼只是檢測文本輸入中的關鍵事件並檢索其值。通過刪除任何空格並取出字符串的最後兩位數字並將其轉換爲整數來確定年份。然後,您可以比較年份的值並相應地調整組合框的值。

相關問題