i am trying to get the query parameter for http://url.com?send_volume=send_300_gb and then set a form select option based on this.
I can grab the get value and assign to var to use in the assignment but for the life of me can't understand why i can't get the option to set as selected:
<script type="text/javascript">
//This will return a given query string parameter from the current url
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var send_volume_value = getParameterByName('send_volume');
$(document).ready(function () {
$("select[name='send_volume'] > option[value="+ send_volume_value +"]").attr('selected','selected');
});
</script>
Select Form looks like this:
<select class="hs-input" id="send_volume-33ab6f27-e084-4f5d-9690-76e8fec2316d_8893" name="send_volume">
<option value="__PLACEHOLDER__">- Please Select -</option>
<option value="send_300_gb">Send up to 300GB/month</option>
<option value="send_500_gb">Send up to 500GB/month</option>
<option value="send_1_tb">Send up to 1TB/month</option>
<option value="send_custom">Custom</option>
</select>
If the value of the parameter send_volume matches one of the values of the options for example lets say
send_volume == "testval"
and the options are
<select name="send_volume">
<option value="">Select one</option>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
<option value="val4">Val 4</option>
</select>
Then this is how you should "select" an option
$("select[name='send_volume']").val(send_volume);
<select> elements do not honor the value attribute, however their DOM API does support a value property shich can be used to set the select's value.
$("select[name=send_volume]").val(send_volume_value);
However, the way you are doing it should also work, but I suspect that either the value of send_volume_value is incorrect, or there is no option with that value. Basically, there are no elements matching your selector in the document.
Related
So i have this SELECT tags here
<select id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</select>
<button onclick="go()">GO</button>
Then a script here
<script>
function go() {
$.ajax({
url: 'url1.php?check=' + value,
type: 'GET',
async: true,
})
Now, I want to change the line of code that says: url: 'url1.php?check=' + value, to say whatever the selected option's id is rather than the hardcoded "ur1.php". How do I achieve these?
NOTE: I cut the code if you're wondering why is it like that.
Here's a working demo of what you need. I changed the following to make it work:
1) give your <option> tags value attributes (as per documentation) rather than ids. The one relating to the chosen option is then automatically read as being the value of the <select>.
2) get the currently selected URL value by using .val() to get the value of the <select>
3) (non-essential but good practice) using an unobtrusive event handler in the script itself rather than an inline "onclick".
4) (non-essential) you don't need async:true because that's already the default value.
var value = "something";
$("#go").click(function() {
var url = $("#url").val() + '.php?check=' + value;
console.log(url);
$.ajax({
url: url,
type: 'GET',
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="url">
<option value="url1">url 1</option>
<option value="url2">url 2</option>
</select>
<button type="button" id="go">GO</button>
The proper way to do this is to give each of your option's a value attribute. You can the get the select-element and get it's value (which will be the value of the selected option)
I added some code to help you:
function go() {
const select = document.getElementById('select');
const value = select.value; // <-- this here is the value you can use to make your request
console.log(value);
}
<select id="select">
<option value="url1">URL 1</option>
<option value="url2">URL 2</option>
</select>
<button onclick="go()">Go</button>
HTML Code:
<SELECT id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</SELECT>
<button id = "button_go">GO</button>
Script:
$("#button_go").click(go);
function go() {
var value =$('#url').children("option:selected").attr('id');
alert("You have selected the ID- " + value);
// your ajax code
}
Check the jsfiddle working code : https://jsfiddle.net/1eq29w6a/4/
Trying to get all options with a selected="selected" attribute on a page.
There are many of these instances on the page but I can only seem to save the first to an array.
How the selected="selected" shows up:
<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6" id="link_list_links__link_type" name="link_list[links][][link_type]">
<option value="frontpage">Store Frontpage</option>
<option selected="selected" value="collection">Collection</option>
<option value="product">Product</option>
<option value="catalog">All Products</option>
<option value="page">Page</option>
<option value="blog">Blog</option>
<option value="search">Search page</option>
<option value="http">Web Address</option>
</select>
What I have tried :
$('#link_list_links__link_type option:selected').map(function () {
return $(this).val();
});
It only returns the first selected="selected" option and not the rest of the iterations.
How do I return all of the options on the page with selected="selected"?
What am I doing wrong?
The problem is the id you have used, ID of an element must be unique, so when you use id-selector it will return only the first element with the said id. which means #link_list_links__link_type selects only 1 select element thus you are getting only one value.
A unique identifier for the element. There must not be multiple
elements in a document that have the same id value.
One solution here is to use a class to group similar elements so
<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6" name="link_list[links][][link_type]" class="link_list_links__link_type">
then
var array = $('.link_list_links__link_type option:selected').map(function () {
return $(this).val();
}).get();
I have this html:
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data="04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data="04f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data="04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data="04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
and js
function check_status(obj){
var uid = obj.getAttribute('data');
alert(uid);
}
but it always alerts null instead of data value
Where is the problem guys? Thanks
The problem is that you get select element and not selected option element as function argument. And it does not have the data attribute. You have to get the option attribute like so:
function check_status(obj) {
var uid = obj.options[obj.selectedIndex].getAttribute('data-uid');
alert(uid);
}
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data-uid="01f2cf35e4d7a1c0158459fd0450a601">open</option>
<option value="in_process" data-uid="02f2cf35e4d7a1c0158459fd0450a602">pending</option>
<option value="finished" data-uid="03f2cf35e4d7a1c0158459fd0450a603">finished</option>
<option value="canceled" data-uid="04f2cf35e4d7a1c0158459fd0450a604">canceled</option>
</select>
Notice that I changed the attribute name to data-uid for it to be valid according to HTML5 specificaion.
You are trying to get select data attribute, and not option's.
Also, I can see that all you data attributes are identical. Then you can move it from option to select itself: <select onchange="check_status(this);" name="status[171]" data="04f2cf35e4d7a1c0158459fd0450a605" > and use code snipped from your question unmodified.
function check_status(obj) {
var uid = obj.options[obj.selectedIndex].getAttribute('data');
alert(uid)
}
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data="open04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data="pending104f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data="finished04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data="canceled04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
You define custom attributes using the "data" attribute. In your code, there is not custome attribute which I'm sure you wanted it to be an ID. The exact format is "data-*", where "*" is replaced with the desired custom attribute name, then set to the desired string value. So in your code, it should ideally be:
<select onchange="check_status(this);" name="status[171]">
<option selected="true" value="open" data-id="open04f2cf35e4d7a1c0158459fd0450a605">open</option>
<option value="in_process" data-id="pending104f2cf35e4d7a1c0158459fd0450a605">pending</option>
<option value="finished" data-id="finished04f2cf35e4d7a1c0158459fd0450a605">finished</option>
<option value="canceled" data-id="canceled04f2cf35e4d7a1c0158459fd0450a605">canceled</option>
</select>
assuming you want the custom attribute to be "id".
There are two ways you can retrieve the value of "data" attributes using pure JavaScript: in addition to the good old fashion get/setAttribute(), you can also access using the "dataset" property of the element
Using DOM's getAttribute() property
function check_status(obj) {
var myoption = obj.options[obj.selectedIndex];
var uid = myoption.getAttribute('data');
alert(uid);
// setting and removing the data-id attribute
myoption.setAttribute("data-id", "foo") //changes "data-id" to "foo"
myoption.removeAttribute("data-id") //removes "data-id" attribute entirely
}
Using JavaScript's dataset property
function check_status(obj) {
var myoption = obj.options[obj.selectedIndex];
var uid = myoption.dataset.id;
alert(uid);
var statusId = myoption.dataset["id"]
alert(statusId);
}
function check_status(obj){
var uid = obj.options[obj.selectedIndex].getAttribute('data');
alert(uid);
}
This has probably been answered, but I am unable to find the answered question anywhere...
Assuming we have the following HTML...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dropdown Test</title>
</head>
<body>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
</body>
</html>
What would the JQuery command look like to set 'My Custom value 2' to be the currently selected option in the dropdown list box, assuming I do not know the index 'value' value, and can only identify the item by the text 'My Custom Value 2'?
You can use jquery .filter():
$('#myDropDownListID option').filter(function() {
//you can use this.innerText too
return $(this).text() === 'My Custom Value 2';
}).prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
Simply like this :
$('select').val($("select option:contains('My custom Value 2')").val());
Another way... use the contains selector to search for a DOM elem by its content.
$('select>option:contains("My Custom Value 2")').prop('selected', true);
People like to say to use .val(), but as you noticed, it doesn't like to set by text, but by using the index, instead. So you should do a find to get that, then set by it. But even that is only part of the story. You should first deselect all other options, and set the attribute of the option you want as selected using the index that you find.
Btw, I hate the $('#myDropDownListID') syntax because it is useless in SharePoint because it auto-generates GUIDs and puts them after the IDs, forcing you to have to grab it with $('[id*=myDropDownListID]'), with the * indicating that it contains that value, so that is how I will set this up, except I'll leave out the * because it's unnecessary in this case. But this syntax is also very useful if you want to use $ instead of * to say it starts with that value, and you can use title or name instead of id, so it is incredibly versatile, and I wish more people used it.
$(document).ready(function() {
var yourText = "My Custom Value 2";
// Remove all 'selected' attributes from all options
$('select[id="myDropDownListID"] option').removeAttr('selected');
// Get the index for the value you want to set
var idx = $('select[id="myDropDownListID"] option').filter(function() {
return $(this).html() == yourText;
}).val();
// Set the dropdown value by index and set it as selected by text
var dropdownBox = $('select[id="myDropDownListID"]');
dropdownBox.val(idx);
dropdownBox.find('option[value="' + yourValue + '"]').attr('selected','selected'); // note that .val() doesn't do this
dropdownBox.click(); // may be useful and necessary for certain engines to cache the value appropriately
console.log(dropdownBox.html()); // should show you that the selected option is My Custom Value 2
console.log(dropdownBox.val()); // should give you the index 2
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="myDropDownListID">
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
ddlListItems is ID of ListBox
if ($('#ddlListItems option:selected').text() == 'My Custom Value 2') {
var itemsByValue = $('#ddlListItems option:selected').text();
}
Is it possible to detect if no option was explicitly selected in a select box?
I have tried these methods but none of them works:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
Trial 1:
alert($('#select option:selected').length); // returns 1
Trial 2:
alert($('#select option[selected=selected]').length); // returns 1
Trial 3:
alert($('#select option:selected').attr('selected')); // returns 'selected'
Any ideas SO people?
Try This:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>
Use this JS:
$('#btncheck').click(function(){
if ($("#mySelect ")[0].selectedIndex <= 0) {
alert("Not selected");
}
else
alert("Selected");
});
It will check if your dropdown was selected.
Try this fiddle: http://jsfiddle.net/aPYyt/
Hope it helps!
PS: You will have to make first value as default value.
This is how a normal select element works: the first option is selected if no other option has selected attribute set. The simplest workaround is to add an empty option as the first option, like this:
$(function() {
console.log($("#mySelect").val());
console.log($("#mySelect").get(0).selectedIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">-- select an item --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
then test one of these conditions:
$("#mySelect").val() === "";
$("#mySelect").get(0).selectedIndex === 0;
$("#mySelect option:selected").index() === 0;
A select box always has a value. If you don't manually change from the default value, you still have a value. For checking for explicit changes, as you say, you could monitor change:
$('#select').change(function() { $(this).data('changed', true); });
Your condition, then, would be:
if(!!$('#select').data('changed')) { ... }
The more common way of achieving something similar would be to insert a placeholder value at the top:
<option value="0">Please select one item</option>
... and test for
$('#select').val() == '0'
If you need to find out whether the select has been changed from its original value, i.e. the above test, but making sure that the user doesn't switch back to the default, you coul simply store the original value at page load:
$('#select').data('original-value', $('#select').val());
And check for
$('#select').val() != $('#select').data('original-value');
By default whatever option comes on index 0 is considered by browser as selected. The solution to problem would be inserting a dummy option at index 0 and before form submission you can validate it using something like
if($("#selectBox option").index("option:selected")>0)
$("#myForm").submit();
var $inputs_select_options = $('option:selected');
// remove empty(first option as default , value=="" ) options:
$inputs_select_options = $inputs_select_options.filter(function() {
return this.value.length; //check by length value
});