Reputation: 714
need a small help to change data from option selected.
The data is populated first to the dropdown option list from a JSON result, in the same JSON is the second data thta need to be changed on select the option from dropdown.
What i want os to change the price on select the store.
This is my javascript code:
$(function() {
var pricestore = [{"product_id":"1","store_id":"1","price":"120.00","sequence":"0","id":"1","parent_id":"0","name":"Store 1","email":"[email protected]"},{"product_id":"1","store_id":"2","price":"140.00","sequence":"0","id":"2","parent_id":"0","name":"Store 2","email":"[email protected]"}];
$.each(pricestore, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
}),
//Trying to populate the price on div id
$$('#price-store').each(function(el) {
el.innerHTML = pricestore;
});
})
This is the HTML to get the data
<select id="sel"></select>
<div id="price-store"></div>
Here is also an example on jsfiddle
Any help is appreciated.
Upvotes: 0
Views: 2831
Reputation: 123739
Check this:-
As per what i understood from your question you need to show the price in the div as the dropdown values are changed. You can use below method. You need to use use a change event on the dropdown
.
This approach uses Index() of the option element selected and retrieves the corresponding record from JSON
.
$('#sel').change(function () {
$('#price-store').text(
pricestore[$('option:selected', this).index()].price);
});
Another way is to use data-attributes
on the option element to store the respective price and retrieve it on change of dropdown value.
$('#sel').append($('<option>',
{
"value" :option.id,
"data-price" :option.price
}).text(option.name));
}),
$('#sel').change(function () {
$('#price-store').text($('option:selected', this).data('price'));
});
Upvotes: 1
Reputation: 182
Or this one:
<div id="price-store"></div
<form>
<select id="price">
<option>120</option>
<option>140</option>
<option>160</option>
</select>
</form>
and:
$('#price').change(function() {
$('#price-store').text($('#price').find(":selected").text());
});
Upvotes: 0
Reputation: 97707
You use $$
to select your div instead of $
. $('#price-store')
The second parameter of the function passed to the .each()
method is the element not the first. function(i, el) {
Why are you using .each()
for one div?
You'll have to format the data in pricestore
to display it in a div, otherwise all you'll get is [Object object],[Object object]
.
Upvotes: 0