Dropdown image change with link with submit button - javascript

I would like the image to change based on the dropdown selection, then directed to the URL also associated with the option when submitted.
So, there are two 'values' for each option, the image and the URL. The Image changes instantly and the URL is where the selection is directed to on submit.
I had the image change working, then added the script for a link and the href which did not work.
<select onchange="$('#imageToSwap').attr('src', this.options[this.selectedIndex].value);">
<option value="https://pbs.twimg.com/profile_images/650647649985646593/FEed4zzM_400x400.jpg" selected="" href="detroitcanvas.co">Choice 1</option>
<option value="https://news.artnet.com/app/news-upload/2020/01/Jackie-Saccoccio-256x256.png" href="twitter.com">Choice 2</option>
<option value="https://art-media.s3.amazonaws.com/media/public/tags/tag_animal%20art/2019-11-20T194138.3524830000.thumb.jpeg" href="instagram.com">Choice 3</option>
</select>
<br><br>
<img id="imageToSwap" class="profile" src="http://cdns2.freepik.com/free-photo/facebook-logo_318-49940.jpg">
Submit
<script>document.getElementById('my_selection').onchange = function() {
window.location.href = this.children[this.selectedIndex].getAttribute('href');}</script>

You can use data attributes in each option for additional values, and key your JS to use them, e.g., this pseudocode:
<option data-src="https://pbs.twimg.com/profile_images/650647649985646593/FEed4zzM_400x400.jpg" selected="" value="detroitcanvas.co">Choice 1</option>
<script>
document.getElementById('my_selection').onchange = function() {
image.src = this.children[this.selectedIndex].dataset.src;}
onsubmit uses the selected option value
</script>

Related

Auto check saved data in jQuery Multiselect

I am using this jQuery Multiselect plugin https://github.com/nobleclem/jQuery-MultiSelect to convert all my select boxes that have the multiple attribute enabled in to drop down boxes with check boxes.
I load the options in the select box from a database.
Upon the form submission I can save the multiple selected data, but when I retreive data back from the database I cannot display the saved data back in the multi select box by checking matching check boxes.
The multiselect plugin has a loadOptions method, but using that method I have to generate all option data with option name, option value and the check status, and set it to the multiselect plugin. How can I easily do this if I have an array of data which must be checked/selected in the multiple select plugin?
HTML
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>
JS (I have more than one multiple select boxes and initiate them as shown below)
$.each($("select[multiple]"), function (key, selectbox) {
$("#" + selectbox.id).multiselect({
texts: {placeholder: $("#" + selectbox.id).attr("title")}
});
});
My saved data array is [1,3,4]
I need to set these saved data to the select box and check the check boxes without going through the loadOptions method.
You could use jQuery .filter() function on your select options to preselect those wanted before initializing the multiselect plugin.
Here,
$('option',this).filter((_,e) => saved_data.includes(+e.value)).prop('selected',true);
Preselects every option, before the .multiselect() call.
let saved_data = [1, 3, 4];
$('select[multiple]').each(function() {
$('option', this).filter((_, e) => saved_data.includes(+e.value)).prop('selected', true);
$(this).multiselect({
texts: {
placeholder: $(this).attr("title")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://springstubbe.us/projects/demos/jquery-multiselect/scripts/index.js?1523890673"></script>
<link rel="stylesheet" href="https://springstubbe.us/projects/demos/jquery-multiselect/styles/index.css?1518818712">
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>

How to click a dropdown menu and select option?

I have the following code
<select class="needsclick" id="country" name="order[country]">
<option value="USA" selected="selected">USA</option>
<option value="CANADA">CANADA</option>
</select>
I could do the following javascript command to change the option value
document.getElementById("country").value = 'CANADA'
however, this does not change the selected value and does not change the state box to province.
When I physically click this dropdown menu and change to CANADA, the effects of the change take place (the state box changes to province)
I am using Swift iOS to parse HTML and wondering what line of javascript code is needed to click a option value rather than changing the option value?
If I do the following after changing the value
document.getElementById("country").click()
it just clicks the menu but still does not change the state box to province (happens when physically clicking the option value)
How can I achieve this using a javascript command like the two above?
The state/province box is irrelevant to the code just relevant to the fact it changes when the dropdown is physically clicked and not when programmatically changed.
I can do the following code but it still does not change the state box to province (only if physically clicked)
document.getElementById("country")[1].selected = true
To work with the option elements within a select, you must access the options node list and then select one to work with.
Setting the value is separate from setting the selected flag.
var countries = document.getElementById("country");
var states = document.getElementById("provincesUSA");
var territories = document.getElementById("provincesCanada");
countries.addEventListener("change", function(e) { update(e); });
function update(e){
// show the correct sub-list based on the selected option
var country = countries[countries.selectedIndex];
if(country.value === "USA"){
states.classList.remove("hidden");
territories.classList.add("hidden");
} else if(country.value === "CANADA") {
territories.classList.remove("hidden");
states.classList.add("hidden");
} else {
territories.classList.add("hidden");
states.classList.add("hidden");
}
}
// To dynamically choose
document.querySelector("button").addEventListener("click", function(){
countries.options[2].selected = "selected"; // Canada
// Simulate the change event
update(countries);
});
#provincesUSA.hidden, #provincesCanada.hidden { display:none; }
<select class="needsclick" id="country" name="order[country]">
<option value="" selected="selected">Choose A Country</option>
<option value="USA">USA</option>
<option value="CANADA">CANADA</option>
</select>
<select id="provincesUSA" class="hidden" name="states">
<option value="al">Alabama</option>
<option value="ar">Arkansas</option>
</select>
<select id="provincesCanada" class="hidden" name="territories">
<option value="on">Ontario</option>
<option value="qu">Quebec</option>
</select>
<button>Force A Selection (click me whe CANADA is NOT selected)</button>
document.getElementById("country").selectedIndex = 2;

Multi select onchange event jquery

I'm creating a form. I have two fields, 1. default value field and 2. preview field. Both are multiselect fields. The user will add the options to the multiselect manually. Whenever the user chooses an option in the default value, the same value should be shown as selected in the preview field. When the user removes one option, the same option should be unselected. This is how I've written the onchange event for this multiselect:
$("#MultiSelect_DefaultValues").change(function() {
alert($(this).val());
$("#MultiSelect_Preview").val($(this).val());
});
I get the correct value in the alert. But, in the preview field, there is no reaction. All the options available in the default value field are available in the preview field too. But, the options selected in the default value field is not selected in the preview field. What's wrong with this? What should I change, so that the changes in the default field reflects in the preview field too?
You said you are using select2 so execute like this:
$("#MultiSelect_DefaultValues").change(function () {
alert($(this).val());
var prevSelect = $("#MultiSelect_Preview").select2();
prevSelect.val($(this).val()).trigger('change');
});
The values on the option tags need to match for this, if I'm understanding correctly what you're trying to achieve that is.
e.g.
$("#MultiSelect_DefaultValues").change(function() {
console.log($(this).val());
$("#MultiSelect_Preview").val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="MultiSelect_DefaultValues" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<select id="MultiSelect_Preview" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
You can provide multiple replacements by sending an int array to the select method.
$('#cars').val([1,3]);
//or $('#cars').selectpicker('val', [1,2,3]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars" multiple>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
you can use this code
<script>
$("#MultiSelect_DefaultValues").change(function () {
$('select[id="MultiSelect_Preview"]').find('option[value=' + $(this).val() + ']').attr("selected", true);
});
</script>

How to change "size" of select when click on select?

sorry for my bad english, i have a problem with select :
<form name="reg" style="width:700px;" action="#" method="post">
<p align="center">
<select onChange="reg(this.options[this.selectedIndex].value)" size="1">
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
</p>
</form>
I would like that when i click on select, the size of select changes in size="5", because when the document load the size is size="1" (and this is good) but if i click on select, it shows all ten options, and this is the problem...
While, if i click on select, the size changes, is most beautiful.
EDIT
In future the form could have more 250 options, so is important that when the document load size is 1, and when i click the size is 5 ....
the size must be "5" only when the select show options, and when an option is selected the size must be 1.
The problem is that i don't know how made it, maybe with jquery? or only with css?
Can you help me?
Thanks!
Here is a working solution for your problem:
add focus event handler to the select list with id='selRegs'
set the size attribute to 6 (5 will show 4 options + the "Select the Reg" option)
after option is changed the size will be reset to 1
remove focus from select
https://jsfiddle.net/juaxo8zm/8/
$(document).ready(function () {
var initPos = $("#yourDiv").position();
console.log("init: ");
console.log(initPos);
$('#selRegs').focus(function () {
$('#selRegs').attr("size", "6");
$("#yourDiv").css({
position: "absolute",
top: initPos.top,
left: initPos.left
});
});
$('#selRegs').change(function () {
console.log("selected");
$('#selRegs').attr("size", "1");
$("#selRegs").blur();
$("#yourDiv").css({
position: "static"
});
});
});
I use jQuery for this:
.change()
.focus()
.attr(param1, param2)
.blur()
.position()
Try this:
<select size="1"
onfocus='this.size=5;'
onblur='this.size=1;'
onchange='this.size=1; this.blur();'
>
Use the HTML onclick="myFunction()" event tag from the HTML select tag, or use jQuery click() handler if you want to declare the event handler at the javascript level (I mean if you want add the additional event from javascript).
I mean you have a choice - add the extra event dispatch code in the HTML tag source code or add it from the javascript/jQuery level.
The problem is that onChange() event dispatch doesn't get called until too late for your need (it gets called after a user selects a value).
You need to get notified the moment the button for the drop-down menu is clicked so you can change the selected value (default) value.
In your click function handler change the selectedIndex property and set it to the the index of the line that contains "5"
You should use click event on select
$('select').on('click',function(){
$(this).attr('size',5)
});
Just use javascript :
<select id='sel' onfocus='changesize();' onchange='changesize2();' size='1'>
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
<script>
function changesize(){
document.getElementById('sel').size = '5';
}
function changesize2(){
document.getElementById('sel').size = '1';
document.getElementById('sel').blur();
}
</script>
Demo : http://codepen.io/anon/pen/zxbRZb

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

Categories

Resources