How to change data on select option dropdown - javascript

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":"store1#store1.com"},{"product_id":"1","store_id":"2","price":"140.00","sequence":"0","id":"2","parent_id":"0","name":"Store 2","email":"store2#store2.com"}];
$.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
http://jsfiddle.net/A386B
Any help is appreciated.

Check this:-
Demo
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.
Demo
$('#sel').append($('<option>',
{
"value" :option.id,
"data-price" :option.price
}).text(option.name));
}),
$('#sel').change(function () {
$('#price-store').text($('option:selected', this).data('price'));
});

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].

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());
});
http://jsfiddle.net/XcSZL/8/

Related

Form not reading the select attribute when added option via ajax

I am prepending an <option> via ajax like this:
success: function(data) {
jQuery('#usp-cat-combo-1').prepend('<option selected="selected" value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
The thing is when I submit the form, that option says not selected and I need to manually select it, even tho I have given the attribute selectedwhen I added it
Try setting value of the <select> instead of setting selected attribute on the option
jQuery('#usp-cat-combo-1')
.prepend('<option value="'+data.cat_id+'">'+data.cat_name+'</option>');
.val(data.cat_id)
Note this assumes the <select> is not a multiple. If it is a multiple can set prop('selected',true) on the new first child
What you have to do:
Defined the option which you want to select by default like:
var selected;
success: function(data) {
data.cat_id=='1' ? selected = 'selected="selected"' : selected = '';
jQuery('#usp-cat-combo-1').prepend('<option '+selected+' value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
Now it just add Selected Attribute at one option that you defined not every option.
Note :
Assume that you have data as an array.
You can use data.cat_name or other as you want instead of cat_id to defined your Selected Option.
Feel free to comment for more help or other simplification :)

Removing duplicates from a dropdownlist

I have a dropdown that is returning duplicates. I don't know why it is returning duplicates.
Here is the control for my dropdown.
#Html.DropDownList("procDateId", Model.GetEmpHoursDateRange.EmphoursdateSelectList, Model.GetEmpHoursDateRange.selectedEmplhoursdate, new { id = "procDateId" })
I want to be able to remove the duplicates once the page load.
I tested the code below with an alert and am able to get to the document.ready
$(document).ready(function () {
alert("here you go !!!");
[].slice.call($('#procDateId').option)
.map(function (a) {
if (this[a.innerText]) {
$('#procDateId'.option).removeChild(a);
} else {
this[a.innerText] = 1;
}
}, {});
});
Here is the html that my dropdown is rendering.
<select id="procDateId" name="procDateId">
<option value>1/11/2017</option>
<option value>1/11/2017</option>
<option value>1/10/2017</option>
<option value>1/9/2017</option>
</select>
The duplicates are not been removed with my code above. No luck. Kindly assist.
Your jQuery selector for the option appears incorrect: $('#procDateId').option --> ('#procDateId option')
Additionally, you can call remove on the option directly
jsfiddle: https://jsfiddle.net/db9zczr0/
The reason for the double up is you're using an overload with the defaultOption = Model.GetEmpHoursDateRange.EmphoursdateSelectList. The value returned is the duplicate.
The default option appears at the start of the list and its value is
empty. A default option is used to communicate that no option is being
chosen from the list, such as when the drop-down control represents an
optional parameter.
From https://msdn.microsoft.com/en-us/library/gg548012(v=vs.111).aspx
So you will want to use a different overload, e.g.
HtmlHelper.DropDownList Method (String, IEnumerable,
Object)
Then to tell the View to show the selected option using the saved session value, in the controller loop over the IEnumerable<SelectListItem> and set Selected = true for the matching item.

Get selected index of dropdown from array Jquery

I am saving all inputs in a form in the form of array into a variable.
Example: var data = $('inputs,select')
Now, I want to get selected index of dropdown using variable data.
Please help.
Edit: Added Fiddle for reference
Fiddle
If I have understood your question properly, you save a jQuery object with every input and select in a variable­. To get the selected index of a dropdown you would have to iterate over your variable to find out if its a select or a regular input, and then get its selected index.
//loop over every dom element in the variable
data.each(function () {
//if its a select
if ($(this).is("select")) {
//find its selected index using native DOM and do something with it
$(this)[0].selectedIndex;
}
});
You probably want to add $( "select option:selected" ).text(); to select the selected item.
This was from: http://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/

unexpected behaviour in option tag in HTML

I have the following code
<select id="part">
<option>noun</option>
<option>verb</option>
<option>adjective</option>
</select>
In the above code, I don't have any value attribute each option tag.
there is only text node.
when I access the option tag
$("#part").val(); I get what is selected in dropdown box. ie, "noun"
but when I access $("#part").text(), there is empty string.
but when I create, option tags dynamically in jquery for
<select id="part"></select>
using
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
Here the value is attribute is needed to get the option selected.
without value attribute, $("#part") is undefined.
can somebody explain the discrepancy here? of if my understanding is not correct. Thanks
Check here DEMO http://jsfiddle.net/yeyene/yH4Fb/
You need to get only the selected option text coz there are three options,
when you get $("#part").val(); you directly get the selected value (only one selected value). But when you get $("#part").text().. you are getting the text of the whole select text where you have three options and three types of text.
JQUERY
$(document).ready(function(){
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
$("#part").on('change', function() {
alert('Value is '+$(this).val());
var text = $("#part option:selected").text();
alert('Text is '+text);
});
});
$("#part").text() doesn't return nothing but it won't return what you expect (see this fiddle).
Explanation: text returns the text of the object strips out the html (see jQuery docs examples), so what you will be getting is the inner contents of the select after the html was stripped out.
If you want the text of the selected value, include the selected option in your jquery selector: i.e. $('#part option:selected').text() which uses the jQuery psuedo-selector (also in my fiddle).

Unable to select first element from select using Jquery

I am filling a drop down based on the value selected in the first drop down.Data being sent back from server is in JSON format and using JQuery to parse and fill the second select tag
<select name="abc" id="jobName">
<option value="-1">Please select a Job</option>
</select>
This is my Jquery code
var selectedGroup = document.getElementById(groupDropDownId);
var groupdata = selectedGroup.options[selectedGroup.selectedIndex].value;
var formInput='group='+groupdata;
$.getJSON('search/getSchedulerJobListForGroup',formInput,function(data) {
$('.result').html('' + data.jobList + '');
$.each(data.jobList,function(index, value){
var jobId = document.getElementById(resetDropDownId);
var option=new Option(value,value);
try{
jobId.add(option);
}
catch(e){
jobId.appendChild(option);
}
});
});
$("#jobName")[0].selectedIndex = 1;
// $("#jobName").val($("#triggerjobName option:first").val());
in above code groupDropDownId is ID of the drop down based on whose value, second drop down will be filled.resetDropDownId is ID of second drop down which i am trying to fill from JSON data getting from the server.
Upon filling the drop down, its also creating an empty option tag and it is getting select by default.
I am not sure if i can add some default value to that empty option so that i can select that default option value like "please select bla bla."
also i tried to select first element from the drop down but nothing seems working for me.I am wondering what i am doing wrong here?
Based on your question, it looks like you want to know how to change the value and text of an element within a dynamically populated select list.
Currently, you have this statement $("#jobName")[0].selectedIndex = 1; sitting outside of your getJSON request. If you move this inside of the getJSON function, it will work as expected.
If you want to set the value and text of that object, you'll want to use ->
$('#jobId option:first').val("Some Value").text("other stuff");
You can see a working JS Fiddle using dynamically populated select list from a JSON object.
Fiddle

Categories

Resources