Jquery获取选定选项的值和自定义属性值

时间:2015-04-21 06:21:51

标签: javascript jquery html

var x = document.getElementById("selectCity"); 
var options = ["Bangalore", "Pune", "Kolkata"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var element = document.createElement("option");
    element.textContent = opt;
    element.value = opt;
    x.appendChild(element);
}

$('select[name="cityDropdown"]').change(function(){
  cityName=$(this).val();
 });

现在每个城市都要存储我的圈子名称。并将其保存为属性并在选择城市时传递

3 个答案:

答案 0 :(得分:0)

制作一个合适的选择器..这个..

 $('#selectCity').change(function(){
       cityName = $(this).val(); 
       console.log(cityName); // do something
     });

HERE是小提琴......

答案 1 :(得分:0)

您可以将自定义属性硬编码为select选项。例如,

<option circle="UP" value="Lucknow">Lucknow</option>

并使用像这样的jquery获取它的值,

var circle = $('option:selected', this).attr("circle");

<强> HTML

<select name="cityDropdown">
  <option circle="UP" value="Lucknow">Lucknow</option>
  <option circle="Bihar" value="Patana">Patana</option>
  <option circle="Punjab" value="Chandigarh">Chandigarh</option>
</select> 

<强>的Javascript

$('select[name="cityDropdown"]').change(function(){
    var cityName = $(this).val();
    var circle = $('option:selected', this).attr("circle");
    console.log(cityName + " : " + circle);
});

注意:您还可以使用其他自定义属性(例如,自定义属性城市)。但您只需要将城市用作选项的value

这是fiddle

答案 2 :(得分:0)

var x = document.getElementById("selectCity"); 
var options = ["Bangalore", "Pune", "Kolkata"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var element = document.createElement("option");
    element.textContent = opt;
    element.value = opt;
    element.setAttribute('circle-name', 'your value'); // your attribute
    x.appendChild(element);
}

$('select[name="cityDropdown"]').change(function(){
  cityName=$(this).val();
 });