Stop dropdown from redirecting to homepage - javascript

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>

Related

Jquery : Identify text change with out page refresh

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>

How do I disable certain options of 'Dropdown B' depending on an option selected on 'Dropdown A'?

Im new to this so apologies if my question is not presented as it should be.
Basically, my aim is with jQuery is to make it so that when the field called 'Apple' is selected from the first dropdown box, the second dropdown box will only allow the field 'Firm' to be selected and the other two be disabled. However if any of the other fruits other than 'Apple' is selected from the first dropdown box then all of the options in the second dropdown box (texture dropdown) will be available to be chosen.
I have looked all over the internet for jQuery code to help me with this issue but as I am new to jQuery I have difficulty finding the solution I need.
Here is my HTML code:
<div class="ingredients_div">
<select name="ingredients_form" id="ingredients_form_1">
<option value="Apple" selected="">Apple</option>
<option value="Orange">Orange</option>
<option value="Lemon">Lemon</option>
<option value="Mango">Mango</option>
</select>
</div>
<div class="texture_div">
<select name="texture_form" id="texture_form_1">
<option value="Firm" selected="">Firm</option>
<option value="Soft">Soft</option>
<option value="Blended">Blended</option>
</select>
</div>
Many thanks
please check this code , i think it works for you.
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Lemon</option>
</select>
<select name="select2" id="select2">
<option value="1">Firm</option>
<option value="2">Soft</option>
<option value="3">Blended</option>
</select>
To achieve what you mentioned, you need to use jQuery's event binding on the first select box. As soon as the value is changed, you need to write logic to enable/disable options in the second select box as per the value changed in the first box.
Here is how you can achieve it.
$("#ingredients_form_1").change(function() {
if ($(this).val() === "Apple") {
$("#texture_form_1 option").prop("disabled", true);
$("#texture_form_1 option[value='Firm']").prop("disabled", false);
} else {
$("#texture_form_1 option").prop("disabled", false);
}
});
Please go through jQuery's documentation to know more about selectors, event binding, and most importantly, in the next post, include what you've achieved till then.

How to remove/hide select options from select-list

I've got a select list like this:
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
Unfortunately I can't edit it.
Is there any method which let me hide the "Product 4" option by default?
I'm trying with CSS, but it doesn't work with IE.
To hide it, wrap it with a span tag.
$( "#selectlist option[value=4]" ).wrap( "<span>" );
To show it, unwrap the span tag if it has one.
if ( $( "#selectlist option[value=4]" ).parent().is( "span" ) ){
$( "#selectlist option[value=4]" ).unwrap();
}
using css to hide options is not supported in IE, so you need to update the options list itself.
Try something like
$('#selectlist option[value=4]').remove();
Demo: Fiddle
or if you want to enable it later
var sel = $('#selectlist');
var opts = sel.find('option');
$(':checkbox').click(function(){
sel.empty().append(this.checked ? opts : opts.filter('[value!=4]'));
}).click()
Demo: Fiddle
You can hide option using following line include in scripting.
$("#selectlist option[value='4']").hide();
And if you want to again show this option use following line.
$("#selectlist option[value='4']").show();
To save your time, please read the following answer.
OK, I searched for a few hours and I noticed that there is NO WORKING WAY to "hide" (what I mean is make the option temporally disappeared from the drop-down list) for all browsers, such as set the visibility to be hidden or style="display: none".
My final approach is:
1. Create an array to store all the options for the dropdown list.
2. Use a method to dynamically update the drop-down list according what you want to be shown.
That's it, if you want to use a drop down list without using any library
You can "hide" the option by moving it to a hidden select element or cached document fragment, then move it back when you want to show it:
var selectTool = (function() {
var frag = document.createDocumentFragment();
return {
hideOpt: function (selectId, optIndex) {
var sel = document.getElementById(selectId);
var opt = sel && sel[optIndex];
console.log(opt);
if (opt) {
frag.appendChild(opt);
}
},
showOpt: function (selectId) {
var sel = document.getElementById(selectId);
var opt = frag.firstChild;
if (sel && opt) {
sel.appendChild(opt);
}
}
}
}());
Then you can hide the 4th option like:
<input type="button" value="Hide option" onclick="
selectTool.hideOpt('selectlist',4);
">
and show it again using:
<input type="button" value="Show option" onclick="
selectTool.showOpt('selectlist');
">
All play code of course, but you should get some ideas. If you want to store many options, you'll need a way of referencing them so maybe store them in an object with some form of referencing scheme.
Try to disable that option with disabled attribute.
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" disabled="disabled">Product 4</option>
</select>
Check demo
see this link
http://jsfiddle.net/DKKMN/
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" id="i">Product 4</option>
</select>
#i{display:none;}
create an id and in style make it invisble
I suppose you are using JQuery as well.
$("#selectlist option[value='option4']").remove();
to append the child below the list of option using java script.
`var option = document.createElement("option");
option.text = "All Users";
option.value = "all_user";
var select = document.getElementById("log_user_type");
select.appendChild(option);`
if you want to remove some option from select list you can use this code:
<script type="text/javascript">
$(window).bind("load", function() {
$('#select_list_id option[value="AB"],option[value="SK"]').remove();
});
</script>
<option value="4" style="display:none">Product 4</option>
hides the 4th option by default.

Swaping images injquery on select dropdown action

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'/>");

Submitting a value with jQuery

I've been pulling my hair out with this one, although I'm certain the solution is embarrassingly simple! I have developed a pull-down menu that requires a selection before presenting more choices, based on the initial selection. It works fine.
However, I need to have jQuery submit the value of the option chosen without a submit button present. So, basically, when a user selects a fruit size, the user is taken to the relevant page in the option value. I cant figure it out! Heres my code:
jQuery:
<script type="text/javascript">
$(document).ready(function()
{
$('#fruit').change(function()
{
var val = $('#fruit').val();
$('.fruitSubSelect').hide();
if(val)
{
$('#fruit'+val).show();
$('#noFruit').hide();
}
});
});
</script>
CSS to hide size select:
<style type="text/css">
.fruitSubSelect {display: none;}
</style>
HTML:
<form action="nothing">
<select id="fruit">
<option value="">Choose Fruit</option>
<option>Apple</option>
<option>Orange</option>
</select>
<select id="fruitApple" class="fruitSubSelect">
<option value="">Choose Size</option>
<option value="http://www.mysite.com/big-apple.html">Big Apple</option>
<option value="http://www.mysite.com/small-apple.html">Small Apple</option>
</select>
<select id="fruitOrange" class="fruitSubSelect">
<option value="">Choose Size</option>
<option value="http://www.mysite.com/big-orange.html">Big Orange</option>
<option value="http://www.mysite.com/small-orange.html">Small Orange</option>
</select>
<select id="noFruit">
<option value="">Choose A Fruit First</option>
<option value="">Please Select Fruit First</option>
</select>
</form>
Would appreciate any help! Thanks.
I think you're looking for something like this:
$(".fruitSubSelect").change(function(){
window.location.href = this.value;
});
Example: http://jsfiddle.net/jonathon/bWUnR/
This will get the selected value of the dropdown and set the window location to it (so the page will go to it).
the addition of this into your jquery alert's the selected option's URL:
$('.fruitSubSelect').change(function(){
alert($(':selected',$(this)).val());
});
live example: http://jsfiddle.net/274Gv/
With dropdowns, do not use .val(). :selected is what you're looking for. http://api.jquery.com/selected-selector/

Categories

Resources