vendredi 28 novembre 2014

How to compare “data-names” in an “if” statement?


I have a slight issue. I have options with a “value” and a “data-name”.



<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>


I want the computer return a specific value if the selected option is a certain “data-name”


Say there are 2 “data-names”, X and Y.


How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?


I’m thinking something along the lines of this:





var data_name1 = e.options[e.selectedIndex].dataset.name1;

if (data_name1 == “X”) {

}
else if (data_name == “Y”) {

}
else {

}




Is this possible?


Thanks!


Full code---





<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded


function getData(){
var e = document.getElementById("qwert"); // get the <select> element

var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute



// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute



var value = e.options[e.selectedIndex].value; // get the value of the selected <option>


//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>











<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</option>
</select>

<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>



<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>






Aucun commentaire:

Enregistrer un commentaire