简体   繁体   中英

Jquery get selected option's value and custom attribute value

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();
 });

Now with each city i want to store my circle name. and save it as an attribute and pass when the city is selected

You can Hardcode a custom attribute to a select 's option. For example,

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

and get it's value with jquery like this,

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);
});

Note : You can also use other custom attribute (custom attribute city for example). But you just need to use city as value of the option.

Here is the fiddle .

make a proper selector ..try this ..

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

HERE is the fiddle..

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();
 });
var optionAttr = $('#cityDropdown option:selected').attr("circle");
var optionAttr1 = $(this).find('option:selected').attr("circle");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM