Reputation: 303
I'm trying to gain a better js-knowledge, and got a little problem. I want to give a option more than one vaule, and from what i could find other places, arrays with split was the best solution. But I can't get it to work. One side of the script is supposed to calculate a price, dependent on the selected destionation, while the other is the name on the destinaton.
<form name="ORDER" method="post" >
<select name="destination" id="destination_trV">
<OPTION VALUE="10,Cannes"> Cannes</option>
</form>
I want one part to grab the "10" to use this calculation purposes, and another to grab "Cannes" to write.
var dest_1 = (document.getElementById("destination_trV").value);
var vari_1 = dest_1.split(",",1);
var vari_2 = dest_1.split(",",1,2);
this is supposed to write out "10"
document.getElementById("linje5").innerHTML="Priceclass: " + vari_1 + "<br>";
this is supposed to write out "Cannes"
document.getElementById("linje6").innerHTML="Destination: " + vari_2 + "<br>";
But this doesn't work :)
Upvotes: 0
Views: 56
Reputation: 179176
What would happen if one of those values were to contain a ,
character? You'd need some form of encoding to preserve the original data. Instead of trying to jam multiple values into a single attribute, you'd be better off splitting those values into separate [data-*]
attributes:
...
<option value="Cannes" data-destination="Cannes" data-price-class="10">Cannes</option>
...
That way, when you want the values, you can select the element and get the attribute values separately:
(function () {
var opt,
destination,
priceClass;
opt = document.getElementById("destination_trV");
destination = opt.getAttribute('data-destination');
priceClass = opt.getAttribute('data-price-class');
document.getElementById('linje5').innerHTML = 'Priceclass: ' + priceClass + '<br>';
document.getElementById('linje6').innerHTML = 'Destination: ' + destination + '<br>';
}());
Upvotes: 1
Reputation: 207527
Split does not work that way MDN split
string.split([separator][, limit])
Just do the split once
var vals = dest_1.split(",");
var vari_1 = vals[0];
var vari_2 = vals[1];
A better way would be to use data attributes.
Upvotes: 1