JQuery convert string to link - javascript

I have 3 select fields, and the combined value of these I would like to use as a extra part of an url.
Here's the HTML code:
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
And the JavaScript:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text(str);
})
.trigger('change');
https://jsfiddle.net/eZKUU/264/
Right now it's working.. after I select an option in all 3 of the selectfields I get an output like /squad/redblack/1985.
I would like to use this output in an url, so it would look like:
mysite.com/squad/redblack/1985
Is there an easy way of doing this? And also.. To only get the link visible after all three of the selectfields have an option selected?

You can use the following. Add an a element and keep it hidden until is completed. Update a element href attribute with selected options:
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
//update href with selected values
$("#mySite").attr("href", "mysite.com/" + str);
});
//keep anchor element hidden until all three options is selected
$("#mySite").toggle($("#cos").find("option:selected").length > 0 && $("#color").find("option:selected").length > 0 && $("#year").find("option:selected").length > 0);
$("div#output").text(str);
})
.trigger('change');
#mySite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/>
<br/>
<div id="output"></div>
<a id="mySite" href="#">Redirect Link</a>

You can check to see if the number of selected options is the same amount as the number of select elements.
var selectedAllLength = $("select").length;
$("select").change(function () {
var str = location.origin;
var selected = $("select option:selected");
var selectedCount = selected.length;
if(selectedCount == selectedAllLength) {
selected.each(
function () {
str += $(this).attr('value');
}
);
$("#output").html('<a href=' + str + '>The link is here</a>');
}
})
.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>

To only get the link after all three have been selected, simply use an if statement to only generate and display the link if 3 options are selected. To make it a URL, just append the path you get to the base URL. Something like:
$("select").change(function () {
var str = "";
if(#("select option:selected").length === 3){
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text("mysite.com" + str);
// Or, if you want a clickable link and not just a URL:
// $("div#output").append($("<a>").attr({href: "mysite.com" + str}).append("Click me"));
}
})
.trigger('change');

Related

jQuery select option hide not working on mobile

My cascading dropdown works fine, exactly how I want it to on a desktop device, however on mobile, the second option of the dropdown lets me choose any option, even those only meant for a different first dropdown input. Is there any way to fix this? I included a picture of what I am talking about and a link to my code.
html
<select name="category" id='dropdown1'>
<option value="0" rel='start'>Select Model</option>
<option value="1" rel="GFS">GFS</option>
<option value="2" rel="NAM">NAM</option>
</select>
<select name="items" class="cascade", id="imgList" style='display:none'>
<option value="" class='NAM'>Please select a timeframe</option>
<option value="" class='GFS'>Please select a timeframe</option>
<option value='.png' class="GFS">1-Day</option>
<option value='.png' class="GFS">5-Days</option>
<option value='.png' class="NAM">1-Day</option>
</select>
js
$('#dropdown1').change(function() {
$('#imgList').css('display','block');
});
$(document).ready(function(){
var $cat = $('select[name=category]'),
$category = $('select[name=items]');
$cat.change(function(){
var $this = $(this).find(':selected'),
rel = $this.attr('rel');
// Hide all
$category.find("option").hide();
// Find all matching accessories
// Show all the correct accesories
// Select the first accesory
$set = $category.find('option.' + rel);
$set.show().first().prop('selected', true);
});
});
function setClass() {
var img = document.getElementById("image");
img.src = this.value;
return false;
}
document.getElementById("imgList").onchange = setClass;
https://jsfiddle.net/7t5rLa3h/
Looks like hiding the option (display:none) on mobile browsers doesn't work. But you can disable and enable them like options.attr('disable', true).
Alternatively, you can save a set of options in a variable and filter and re-populate the select later.
$(document).ready(function() {
var $cat = $('select[name=category]'),
$category = $('select[name=items]'),
$options = $('select[name=items] option');
$cat.change(function() {
var $this = $(this).find(':selected'),
rel = $this.attr('rel'),
$set = $options.filter('[data-category=' + rel + ']');
$category.html($set)
$set.show().first().prop('selected', true);
});
});
$('#dropdown1').change(function() {
$('#imgList').css('display', 'block');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Choose Model and Timeframe</h1>
<h2>
<select name="category" id='dropdown1'>
<option value="0" rel='start'>Select Model</option>
<option value="1" rel="GFS">GFS</option>
<option value="2" rel="NAM">NAM</option>
</select>
<select name="items" class="cascade", id="imgList" style='display:none'>
<option value="" data-category='NAM'>Please select a timeframe</option>
<option value="" data-category='GFS'>Please select a timeframe</option>
<option value='Model_Data/GFS/meteogram/trends/images/NYC/gfs_1day_temp.png' data-category="GFS">1-Day</option>
<option value='Model_Data/GFS/meteogram/trends/images/NYC/gfs_5day_temp.png' data-category="GFS">5-Days</option>
<option value='Model_Data/NAM/meteogram/images/1_day/NYC/nam_1day_temp.png' data-category="NAM">1-Day</option>

How can I get the latest HTML tags of a changeable elements, like Select, Checkbox, Input in JS/Jquery?

I need to get the HTML tags of the changeable element so that I can pass them to create a PDF. But, whenever I use element.innerHTML or element.html(), I get the HTML tags generated after page load but not after I made the changes.
In HTML:
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
In JS:document.getElementById("testSelect").innerHTML
It returns:
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
And now if I manually change the value to 2, then
In JS:
document.getElementById("testSelect").value
"2"
as you can see the value is changed. But, the HTML tags won't change as
In JS:
document.getElementById("testSelect").innerHTML
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
Still, I get the old tags. Instead, I want something like this.
"
<option id="no">-- not selected --</option>
<option id="one">1</option>
<option id="two" selected="">2</option>
"
I made this script for you hope it helps you!
var selectBox=document.querySelector("#testSelect");
selectBox.addEventListener("change", function(){
const selectBoxOptions=selectBox.querySelectorAll("option");
selectBoxOptions.forEach((option)=>{
option.removeAttribute("selected");
});
detectOptionObjectByValue(this, this.value).setAttribute("selected", "selected");
});
function detectOptionObjectByValue(selectBox, value){
const options=selectBox.querySelectorAll("option");
let pos=0, obj=false;
options.forEach(function(option){
option.value==value?obj=options[pos]:0;
pos++;
});
return obj;
}
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
You can make a function which will iterate through all options and set all the selected attributes to false
$('select option[value=' + i + ']').attr("selected",false);
Then based on the value selected set the attribute to true
$('select option[value=' + this.value + ']').attr("selected",true);
const dropdownElement = document.getElementById('testSelect')
dropdownElement.onchange = function () {
clearSelected()
$('select option[value=' + this.value + ']').attr("selected",true);
console.log("value selected: " + this.value);
console.log("html: " + dropdownElement.innerHTML)
};
// set all the options to unselected
function clearSelected(){
var elements = dropdownElement.options;
for(var i = 0; i < elements.length; i++){
$('select option[value=' + i + ']').attr("selected",false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
<option id="no" value="0">-- not selected --</option>
<option id="one" value="1" selected>1</option>
<option id="two" value="2">2</option>
</select>
On jQuery site you have similar question explained:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
$(function(){
$('#select').change(function(){
$('#output-value').text($(this).val());//get value
$('#output-element').text($(this).find('option:selected').text());//get text of selected element
$(this).find('option').each(function(){
$(this).attr('selected', $(this).is('option:selected')); //adds and removes selected attribute
});
$('#output-html').text($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" >
<option>--</option>
<option value="1" >1 val</option>
<option value="2" >2 val</option>
<option value="3" >3 val</option>
</select>
<br/>
Value
<div id="output-value" ></div>
Element
<div id="output-element" ></div>
HTML
<div id="output-html"></div>

How to change select's option based on a selected option's value?

I have select tag below:
<select name="selID" id="selID" data-mini="true"">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
I want to change value when one of the options is selected except for "Add More..."
Sorry I'm a newbie. Thanks in advance.
You can try this:
The HTML:
<body>
Result: <p id="result"></p>
<select name="selID" id="selID" data-mini="true" onchange="test()">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
<script src="test.js"></script>
</body>
test.js:
function test() {
let listVal = document.getElementById("selID").value;
if (listVal != "0") {
document.getElementById("result").innerHTML = listVal;
}
else {
listVal = 1; // this is value for "Tithes"
document.getElementById("selID").value = listVal;
document.getElementById("result").innerHTML = listVal;
}
}

Change select box value depending other selected option box

i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>

I have an html I want to send values of selected options as url parameteres. With this javascript:

I have this html:
<select name="garden" multiple="multiple" id="garden">
<option value="1">Flowers</option>
<option value="2">Shrubs</option>
<option value="6">Trees</option>
<option value="3">Bushes</option>
<option value="4">Grass</option>
<option value="5">Dirt</option>
</select>
<select name="po" multiple="multiple" id="po">
<option value="1">po1</option>
<option value="2">po2</option>
<option value="6">po3</option>
<option value="3">po4</option>
<option value="4">po5</option>
<option value="5">po6</option>
</select>
<div></div>
I want to send values of selected options as url parameteres. With this javascript:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var option = $(this);
str += '&' + option.attr('name') + "="+ option.attr('value');
});
$("div").text(str);
});
When the other select box changes, str is replaced with another:
How can I send values to url without replacing?
Thanks in advance
Update your jquery code like below.
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += "&"+$(this).parent().attr('name')+"="+ $(this).attr('value');
});
$("div").text(str);
})
.trigger('change');
DEMO

Categories

Resources