I am trying to extract the price from parent div class. It is working fine when initial page load. But I have a dropdown in my page. When I change the item, parent div price will be changed. But the extracted price is not changing. Because page is not refreshing.
var a = $('.price').text();
var t_section += '<p>Sign up to earn '+ rewardPts + ' points for this purchase</p>';
$('#msg').append(t_section );
How to find the price change?
I have tried change(), trigger() events. But, that is not working.
Check out my code, it might help you.
$('#priceSelect').change(function() {
var rewardPts = $(this).find(":selected").val();
var t_section = '<p>Sign up to earn '+ rewardPts + ' points for this purchase</p>';
$('#msg').append(t_section);
});
<select name="price" id="priceSelect">
<option value="10">10</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500">500</option>
</select>
<div id="msg"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Bind the change() function directly to the drop-down element? This is AFAIK most precise answer.
$('#yourDropdown').change(function () {
var selection = this.value;
// do something with the value
});
This is a far broader answer:
Generally, for most stuff, you can bind to DOMSubtreeModified - which is consistent and fires off on changes in the subtree of certain DOM node. If you bind it to the select element. When one option is selected it should fire.
$('#yourDropdown').bind('DOMSubtreeModified', function(e) {
var selection = this.value;
// handle the detected change
})
Problem is without exact HTML code where I can see exact classes and structure of dropdown (maybe is something non-standard?) it's hard to write the handle part. Also, when change is detected where is the value stored? A fiddle would be nice so I can edit in the parts you are missing ;)
Try Below Code for Your issue
HTML CODE
<select name="price" id="priceSelect">
<option value="10">10</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500">500</option>
</select>
<div id="msg"></div>
JS CODE HERE
calcuateRewardPoint(); // Function Call initial pageLoading
$('body').on("change","select",function() {
calcuateRewardPoint();
});
// Calculate RewardPoint
function calcuateRewardPoint(){
var rewardPts = $("#priceSelect").find(":selected").val();
var t_section = '<p>Sign up to earn '+ rewardPts + ' points for this purchase</p>';
$('#msg').append(t_section);
}
[To see in jsFiddle][1]
$("#priceSelect").change(function(){
var t_section = ('<p>Sign up to earn '+ $(this).val()+ ' points for this purchase</p>');
$("#msg").html(t_section)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="price" id="priceSelect">
<option value="10">10</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500">500</option>
</select>
<div id="msg"></div>
Related
sI am using the following code to remove text starting from the "+" character from dropdown menu choices:
$("select").each(function(){
var $wrapper=$(this);
var $options=$wrapper.find("option");
$(this).empty();
$options.each(function(index){
$wrapper.append(new Option($(this).text().split("+")[0]))
})
})
So if a menu original choices would be:
Audi
BMW
Mercedes + Trailer
The dropdown only shows:
Audi
BMW
Mercedes
THE PROBLEM:
I also have dropdowns that need to refresh the page when a choice is made. When not using the above code this works fine, but when adding the code above the webpage redirects to the homepage instead. How I can ensure that when the user makes a dropdown choice the user stays on the same page?
Following the jquery spirit "write less, do more" you could also do the text replacement operation like this:
$("select.cars option").each(function(){
with ($(this)) {
text(text().split("+")[0].trim());
val(val().split("+")[0].trim());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="cars">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>
To limit the effect of the script on the selects you want to change and protect all the others I also added the class "cars" into the picture. Maybe something along those lines can be helpful for your project?
But this will not touch your current problem, that you leave the current page as soon as a select option has been selected. I suspect there must be another piece of (as yet unpublished) script that is responsible for that behaviour.
You just need to add value to newly created option.
Try this:
$("select").each(function(){
var $wrapper=$(this);
var $options=$wrapper.find("option");
$(this).empty();
$options.each(function(index){
var text = $(this).text().split("+")[0].trim();
var newOption = new Option(text);
// get value from previous option
newOption.value= $(this).val();
$wrapper.append(newOption)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>
So this works!
$("select option").each(function(){
with ($(this)) text(text().split("+")[0].trim());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="cars">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>
In select option change event,why can't we get this or event.target to get selected value instead of writing clumsy code like $( "select option:selected" ) to get selected value ?
Pure JavaScript
If you want a pure JavaScript approach, then use the event.target. To quote the official MDN documentation...
The target property of the Event interface is a reference to the object onto which the event was dispatched. (Source: MDN Web Docs: Event.target.)
Since that gives us the element selected, all we then need is the value attribute, and getting the text display would be nothing more than event.target[event.target.selectedIndex].text...
function getSelectedValue(event) {
console.log("Value: " + event.target.value + "; Display: " + event.target[event.target.selectedIndex].text + ".");
}
<select onchange="getSelectedValue(event)">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
Using the above approach, it would be trivial to update it to add in other attributes of the selection option value, all in pure JavaScript.
jQuery
If you want a jQuery approach, then try using the :selected query term...
$("#selector").on('change', function(){
console.log("Value: " + $(this).val() + "; Display: " + $(this).find('option:selected').text() + ".");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
$("select").on('change', function(){
console.log($(this).val());
console.log($(this).find('option:selected').attr('data-attribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option data-attribute="a">1</option>
<option data-attribute="b">2</option>
<option data-attribute="c">3</option>
<option data-attribute="d">4</option>
</select>
You can't get the selected value, but of course you can get the element and the event.target.
<select onchange="mySelectOnchange(this, event)"></select>
function mySelectOnchange(elm, e) {
// **
}
It exists... take a look at this code for example
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', onSelect_change);
function onSelect_change(domEvent){
// get the selected value :
var selectedValue = domEvent.target[domEvent.target.selectedIndex].value;
// you can also do it using domEvent.target.value but the other solution allows you to get every option's property you want
console.log("Selected: " + selectedValue);
}
<select id="select" name="select">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Hope it helps ;)
PS: have a look on http://www.w3schools.com/jsref/prop_select_selectedindex.asp if you want more examples
The only property that's automatically transferred from the selected option to the <select> element itself is the value, because that's the main purpose of selecting an option from a drop-down menu. Other attributes like data-* are not automatically copied, because it's possible for the <select> to have its own attributes, e.g.
<select id="x" data-name="select">
<option value="1" data-name="option1">1</option>
<option value="2" data-name="option2">2</option>
</select>
It wouldn't make sense for $("#x").data("name") to return the name of the selected option instead of the name of the <select>.
<select onchange="getSelectedValue(this)"></select>
...
function getSelectedValue(select) {
console.log(select.value)
}
I have a select tag where it contains some values, as shown below:
<select id="menu" SIZE=6 onChange="go()">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Now i am using below script for this, where it get the selected value from the drop down,
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
// here i need to make a specific link using this selected drop down value
}
</script>
I just need to know how can i make use of this selected value and go to specific link like
window.location.href='getCityDetails.jsp?c=sv'; // this is not working properly
Can anyone suggest me best solution for this.
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
window.location.href='getCityDetails.jsp?c=' + sv;
}
</script>
Hope it helps you
HTML :
<select id="menu" SIZE=6 onChange="go(this.value)">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Javascript :
function go(desination){
if (destination != ''){
window.location.href='getCityDetails.jsp?c=' + desination;
}
}
you need to concatenate the string properly. try this:
window.location.href='getCityDetails.jsp?c=' + sv;
-- You can use--
var TaskType = document.form1.SelTaskType.value;
-- TaskType will display selected option from below
<select id="SelTaskType" name="SelTaskType" >
<option selected>-- select --</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
I want set a dropdown(select) to be change based on the value of the entries.
I have
<select id="mySelect">
<option value="ps">Please Select</option>
<option value="ab">Fred</option>
<option value="fg">George</option>
<option value="ac">Dave</option>
</select>
And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?
You should use
$('#dropdownid').val('selectedvalue');
Here's an example:
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3 is the index of the option you want.
Live Demo
$('#mySelect').val('fg');...........
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can use this jQuery code which I find it eaiser to use:
$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="your_id" name="name" class="form-control input-md">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
<option value="3">Option #3</option>
<option value="4">Option #4</option>
<option value="5">Option #5</option>
<option value="6">Option #6</option>
<option value="7">Option #7</option>
</select>
You can simply use:
$('#select_id').val('fg')
In your case $("#mySelect").val("fg") :)
May be too late to answer, but at least some one will get help.
You can try two options:
This is the result when you want to assign based on index value, where '0' is Index.
$('#mySelect').prop('selectedIndex', 0);
don't use 'attr' since it is deprecated with latest jquery.
When you want to select based on option value then choose this :
$('#mySelect').val('fg');
where 'fg' is the option value
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
This code worked for me:
$(function() {
$('[id=mycolors] option').filter(function() {
return ($(this).text() == 'Green'); //To select Green
}).prop('selected', true);
});
With this HTML select list:
<select id="mycolors">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.
The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.
So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:
$('#project-locationSearch-dist-input').val('1');
<label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
<select id="project-locationSearch-dist" data-tabindex="1">
<option id="optDistrictOne" value="01">1</option>
<option id="optDistrictTwo" value="02">2</option>
<option id="optDistrictThree" value="03">3</option>
<option id="optDistrictFour" value="04">4</option>
<option id="optDistrictFive" value="05">5</option>
<option id="optDistrictSix" value="06">6</option>
<option id="optDistrictSeven" value="07">7</option>
<option id="optDistrictEight" value="08">8</option>
<option id="optDistrictNine" value="09">9</option>
<option id="optDistrictTen" value="10">10</option>
<option id="optDistrictEleven" value="11">11</option>
<option id="optDistrictTwelve" value="12">12</option>
</select>
Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:
//SPN
spnDDL.combobox({
select: function (event, ui) {
var spnVal = spnDDL.val();
//fire search event
$('#project-locationSearch-pid-input').val('');
$('#project-locationSearch-pid-input').prop('disabled', true);
pidDDL.empty(); //empty the pid list
}
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();
//PID
pidDDL.combobox({
select: function (event, ui) {
var pidVal = pidDDL.val();
//fire search event
$('#project-locationSearch-spn-input').val('');
$('#project-locationSearch-spn-input').prop('disabled', true);
spnDDL.empty(); //empty the spn list
}
});
Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.
Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)
The only other thing to note, much in addition to the post, is:
/*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked. Thus, it's created at that point in time
and its value must be picked fresh. Can't be put into a var and re-used
like the drop down list part of the UI control. So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL); But you can't
do this with the input part of the control. Winded explanation, yes. That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :)
*/
//district
$('#project-locationSearch-dist').combobox({
select: function (event, ui) {
//enable spn and pid drop downs
$('#project-locationSearch-pid-input').prop('disabled', false);
$('#project-locationSearch-spn-input').prop('disabled', false);
//clear them of old values
pidDDL.empty();
spnDDL.empty();
//get new values
GetSPNsByDistrict(districtDDL.val());
GetPIDsByDistrict(districtDDL.val());
}
});
All shared because it took too long to learn these things on the fly. Hope this is helpful.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
$('select#myselect option[value="ab"]')
either can be used to get the selected option value
$('#dropdownID').on('change', function () {
var dropdownselected=$("#dropdownID option:selected").val();
});
or
$('#dropdownID').on('change', function () {
var dropdownselected=this.selectedOptions[0].value;
});
Actually I have a select dropdown. On the select of every option, I need to load an image(Say in a Div). How do I accomplish this is jquery.
I tried something here:
http://jsfiddle.net/refhat/T65Lx/2/
My other two images are here:
http://www.google.com/doodle4google/2010/images/doodle-holiday.gif
http://www.google.com/doodle4google/2010/images/doodle-popeye.gif
UPDATE 1:
My question is something like this.
jQuery add image inside of div tag
UPDATE 2
#JellyBelly: No offence, In deed this is a good answer so far, But It has quite a few bugs, First after selecting some image in the dropdown and then if you go back to first select with value="", It shows some non existing image(Actually this doesn't exist.) (Screen Shot Atached)
2: If you were in the page and had selected say 2nd Image and then if you refresh, It doesn't reset the image, rather shows that Image for first option of select.the scripts crashes, It doesn't load anything. I think this is because we are just doing this on DOM ready.
THANKS
try this: http://jsfiddle.net/JellyBelly/T65Lx/10/
HTML
<select id="sel">
<option value="">Please Select the Logo</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-sesame.gif">Logo 1</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-holiday.gif">Logo 2</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-popeye.gif">Logo 3</option>
</select>
<div style="height:200px; width:250px;border:1px solid red;"><img id="swapImg" src="http://www.google.com/doodle4google/2010/images/doodle-sesame.gif"></div>
JS
$(document).ready(function() {
$("#sel").change(function() {
var imgUrl = $(this).val();
$("#swapImg").attr("src", imgUrl);
});
});
You EDIT Question and I edit my Answer
If I understand correctly, you have the initial state and an empty div in the first selection you want to hang a picture and subsequent selections you want to replace the image right?
If so 'it was, here's how you do:
HTML:
<select id="sel">
<option value="">Please Select the Logo</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-holiday.gif">Logo 1</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-popeye.gif">Logo 2</option>
</select>
<div id="swap" style="height:200px; width:250px;border:1px solid red;">
<input type="hidden" id="state" name="state" value="noImage"/>
</div>
JS
$(document).ready(function() {
$("#sel").live("change", function() {
if ($("#state").val() == "noImage") {
$("#swap").append(
"<img id='swapImg' src='" + $(this).val() + "'>"
);
$("#state").val('image')
} else {
$("#swapImg").attr("src", $(this).val());
}
});
});
demo: http://jsfiddle.net/JellyBelly/T65Lx/23/
If the image is dependant on the option that's selected, I would take the following approach:
HTML:
<select id="sel">
<option value="">Please Select the Logo</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-holiday.gif">Logo 1</option>
<option value="http://www.google.com/doodle4google/2010/images/doodle-popeye.gif">Logo 2</option>
...
</select>
<div style="height:200px; width:250px;border:1px solid red;">
<img id="myImage" src="http://www.google.com/doodle4google/2010/images/doodle-sesame.gif">
</div>
JavaScript:
//Bind to change event of select and update image based on option value.
$("#sel").change(function() {
$("#myImage").attr("src", $(this).val());
});
Here's a working jsFiddle.
Pretty straight forward: http://jsfiddle.net/T65Lx/4/
$(document).ready(function() {
$("#sel").change(function() {
$("#swap").attr("src", "http://www.google.com/doodle4google/2010/images/doodle-holiday.gif");
});
});
Or do swap the image out based on the item selected:
http://jsfiddle.net/T65Lx/5/
And if you want to get fancy, preload those puppies outside your document ready:
(function(){
var preLoadImg1 = new Image();
preLoadImg1.src = "http://www.google.com/doodle4google/2010/images/doodle-holiday.gif";
var preLoadImg2 = new Image();
preLoadImg2.src = "http://www.google.com/doodle4google/2010/images/doodle-popeye.gif";
})();
To insert an image into your div:
$("#myDivId").append("<img src='whatever.gif'/>");