Setting dropdown option from Javascript based on querystring - javascript

I have a partial view which has a dropdown in it and I include that partial in my page twice. Here is the dropdown.
<form name="sortbyformtop">
<select onchange="sort('#querystring', this.options[this.selectedIndex].value);" name="sortbyselecttop">
<option value=""></option>
<option value="accommodationtype">Accommodation type</option>
<option value="mostreviewed">Most reviewed</option>
<option value="lowestprice">Lowest price</option>
</select>
</form>
Now, when the page loads, if the querystring contains a key sortby then I would like to take the value of sortby (which will be accommodationtype, mostreviewed, lowestprice i.e. the value of the options). What I'd like to do is set both dropdowns on the page to the option that matches the sortby query string value. I've tried lots of things but nothing is working.
Can you help?
Edit
I tried this but it did not work
$(document).ready(function () {
$("#sortbyselecttop option").filter(function () {
alert($(this).text());
return $(this).text() == "lowestprice";
}).first().prop("selected", true);
});

Not sure if I've read it well, but do you simply want the dropdown to select the value of the query string ?
If so, try this :
$('select[name="sortbyselecttop"]').val('accommodationtype');
It would be better if the select had a class name so you could set both dropdowns with one jQuery command.
here's a fiddle

you can not access a control with name like $("#name") this is a selector to select a DOM with ID only. but still you can set value of the dropdown like
$("select [name='sortbyselectop']").val(value);
assuming value is the variable in which your query string value is
function Querystring(qs)
{
this.params = {};
this.get = Querystring_get;
this.args = {};
qs = qs ? qs.replace(/^#/g, '') : location.search.substring(1, location.search.length);
if (qs.length == 0)
return;
qs = qs.replace(/\+/g, ' ');
this.args = qs.split('&');
for (var i = 0; i < this.args.length; i++)
{
var pair = this.args[i].split('=');
var name = unescape(pair[0]);
var value = (pair.length == 2)
? unescape(pair[1])
: name;
this.params[name] = value;
}
this.joined = function()
{
var join = new Array();
for (var a in this.params)
{
join.push(a + '=' + this.params[a]);
};
return join.join('&');
};
}
function Querystring_get(key, defaultValue)
{
var value = this.params[key];
return (value != null) ? value : defaultValue;
};
try these functions and get value like
var qs = new Querystring().get("sortby", '');
now qs will have your query string value and you can set value of the drop down like
$("select [name='sortbyselectop']").val(qs);
hope this will work.

Related

Slicing nodes within array

When I first select two options from the 2nd select menu, the array becomes is populated with those two selections. What I want is for the second selected option to replace the first, so even if I do begin by selecting two options from the 2nd select menu, the array's length will remain at one, dynamically changing between those selections. I hope you understand. Thanks for any help. I know I could just make it one function and this problem wouldn't exist but for my use of it I can't do that.
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = []
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
array.splice(0, 1, one);
console.log(array);
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(1, 1, two);
console.log(array);
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
use Array.prototype.unshift() to add value at first place. You can check if element exists in array
using includes().And instead of creating two functions you can create same function and pass different parameters to it.
var array = [];
function myFunct(val){
if(!array.includes(val)) array.unshift(val);
console.log(array);
}
<button onclick = 'myFunct("One")'>ONE</button>
<button onclick = 'myFunct("Two")'>TWO</button>
If you want to replace the new value with first value use this code
function myFunct(val) {
array.unshift(val);
array = [... new Set(array)];
console.log(array);
}
Update:
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = [];
let sel1 = false;
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
if(array.length === 1 && !sel1) array.unshift(one);
else array.splice(0,1,one);
console.log(array);
sel1 = true;
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(sel1, 1, two);
console.log(array);
}
Try This:
var array = [];
function myFunct() {
if(array.indexOf('One') === -1 ) { array.unshift('One') ; }
console.log(array);
}
function myFunct2() {
if(array.indexOf('Two') === -1 ) { array.push('Two') ; }
console.log(array);
}
<button onclick = 'myFunct()'>ONE</button>
<button onclick = 'myFunct2()'>TWO</button>

Auto select options in a <select> based on an array Javascript

I'm working on a project and there is a point which gives me some troubles.
I have a select form autofilled by a script. My select looks up to an array and add the array's values in the select as options.
But now I want to auto select options according to an array.
So I have my array which has some option name inside. Each index correspond to an option. So I would like to select options corresponding to one of the value in the array.
Here is some code :
var attributeFieldCrm = window.parent.Xrm.Page.getAttribute(fieldcrm);
var checkFieldCrmValue = attributeFieldCrm.getValue();
if (checkFieldCrmValue != null) {
console.log('breakpont hit !!!');
var optionSelected = new Array();
optionSelected = checkFieldCrmValue.split("$#");
console.log('les valeurs ont bien été récupérées : ', optionSelected);
var recceuilDesSelections = "";
var result = [];
var options = select && select.options;
var opt;
for (i in optionSelected) {
}
<select id="selectForm" class="selectpicker" multiple data-live-search="true">
</select>
I imagined something like 2 loop for, one going thought the array and for each index I check every options.
thanks for your help !
regards.
It seems that you didn't provide working code, but still:
var sel = document.getElementById('selectForm');
optionSelected.forEach((o)=>{
for (var i = 0;i < sel.options.length;i++) {
if (o == sel.options[i].value) sel.options[i].selected = true;
}
)}

jQuery unwanted sorting of array output in Chrome and IE (FF working fine)

I have a jquery script which converts the options of a dropdown select box to ul list items using an array. Each option in the dropdown has a numerical option value, e.g.
<option value="12">Size S</option>
<option value="34">Size M</option>
<option value="7">Size L</option>
which get converted to a list like
<ul>
<li class="opt_12">Size S</li>
<li class="opt_34">Size M</li>
<li class="opt_7">Size L</li>
</ul>
In Firefox everything works as expected and the list items appear in the same order as the dropdown options. However IE and Chrome seem to sort the option values of the array automatically by option value in descending order.
So instead of size order S,M,L,XL like in the dropdown, in Chrome & IE I get a list with something like XL,M,S,L.
I noticed one thing: When I use var options = Array; to construct the array, Firefox displays the list elements in the right order and Chrome and IE the wrong one. When I use var options = [];, all three tested browsers display the list in the wrong order.
Below is the relevant code of the script which I use to transform the dropdown into list items:
(function($) {
$.fn.visualAttribute = function(options) {
var defaults = {
useTitle: false,
attrClicked : function(data) {
return true;
},
attrUpdated : function(data) {
}
};
var settings = $.extend(defaults, options);
//loop all attributes
var selectbox_counter = 0;
return this.each(function() {
//use counter for a unique class for each wrapper
selectbox_counter++;
//store reference to attribute selectbox
var selectbox = $(this);
//hide the default dropdown (but keep it in dom for posting the required values)
$(this).css('position', 'absolute').css('left', '-100000px').show();
//insert wrapper for options
var wrapper = $('<ul />')
.attr("class", "la_wrapper")
.attr("id", "la_wrapper_" + selectbox_counter)
.appendTo($(this).parent());
$(this).parent().append('<div style="clear:both"></div>');
if (selectbox.attr("id") != "") {
wrapper.attr("rel", selectbox.attr("id"));
}
//store all values of the dropdown in an array
var options = [];
var option_counter = 0;
var description = '';
selectbox.children('option').each(function() {
option_counter++;
if (option_counter == 1) {
//first option contains the description, e.g. 'please select size'
description = $(this).text();
}
//only use option if has a value
var value = $(this).val();
if (value != '') {
options[value] = ({value : value, text : $(this).text()});
}
});
//loop all stored options and create custom html
if (options.length) {
for (var index in options) {
if (!isNaN(index)) {
var value = index;
var text = options[index].text;
if (!settings.useTitle) {
description = '';
}
wrapper.append('<li title="' + description + '" class="opt_' + value + '">' + text + '</li>');
}
}
}
//set custom options to same value as current selectbox value (only needed in rare cases)
var current_value = selectbox.val();
if (current_value > 0) {
$("#la_wrapper_" + selectbox_counter + ' li.opt_' + current_value + ' a').addClass('selected');
}
//event handler for catching a clicked attribute
$("#la_wrapper_" + selectbox_counter + ' li a').click(function() {
var value = $(this).attr("href").split('#')[1];
//use callback
if (!settings.attrClicked(options[value])) {
return false;
}
//set value and class
selectbox.val(value);
$("#la_wrapper_" + selectbox_counter + ' .selected').removeClass('selected');
$(this).addClass('selected');
//use callback
settings.attrUpdated(options[value]);
return false;
});
});
};
})(jQuery);
How can I prevent IE and Chrome from "autosorting" the array and keep/transfer the original order of the dropdown options in the resulting list?
If the order is important, don't use the value of the option as the array key, just do an append (P.S. use [], not Array—that isn't doing what you think it's doing)
var options = [];
var option_counter = 0;
var description = '';
selectbox.children('option').each(function() {
option_counter++;
//only use option if has a value
var value = $(this).val();
if ( value ) {
options.push({value : value, text : $(this).text()});
}
});
Then, when looping, get rid of the if (options.length) altogether, and use a regular for loop:
for (var i=0; i<options.length; i++) {
var value = options[i].value;
var text = options[i].text;
if (!settings.useTitle) {
description = '';
}
wrapper.append('<li title="' + description +
'" class="opt_' + value +
'"><a href="#' + value + '">' + text +
'</a></li>');
}
When you iterate an array with this:
for (var index in options)
you are not getting a guaranteed order as you are just iterating properties of an object (not array indexes) which by specification have no guaranteed order. You should be using this:
for (var i = 0; i < options.length; i++)
to iterate an array in the array order. The first form iterates properties of an object in no particular order. The latter form iterates array elements in array index order (which gives you the actual array elements in their array order).
In addition, you declare an array with this:
var options = [];
or
var options = new Array();
You should not be using:
var options = Array;
Your problem is that you're using for...in to enumerate the properties.
Enumeration order for properties of an object (including an array) is undefined in ECMAScript so far. There is a proposal for ECMAScript 6 to define the order as follows, more or less: "first all properties whose names look like integers, in numeric order, then all other properties in the order they were added". This is the behavior Chrome and IE implement. The Firefox behavior is somewhat complicated and depends on whether your object is an array or not and if it's an array on which exact property names got used and in what order and what the length of the array is and a few other things.
In any case, if you want to enumerate the values in order, just store them in an array using array.push() and then enumerate the array's indices. So replace options[value] = ... with options.push(...) and replace for (var index in options) with for (var index = 0; index < options.length; ++index) and get the value from options[index].value just like you get the text already.

Modify code for javascript from php

I am using a series of check boxes all are with different name that is checkbox1....checkbox40. I am generating a series of sting with '1' and '0' that is if check box is checked than sting will be concatenated with '1' else it will be concatenated with '0'. I have successfully implemented idea for PHP but as now I am using Ajax I want to develop same code for java script. My PHP code for that is
if (isset($_POST[submit]))
{
for ($i=1; $i<41; $i++)
{
$walue = "restriction".$i;
if(isset($_POST[$walue])) {$val .="1";} else {$val .="0";}
}
}
echo "Equivalent String: ".$val."<p>";
for implementing it using Javascript I have called a function on submit event of form.
My form id is theForm and my checkboxes name is restriction1....restriction40. Please give me hint to implement the idea.
So.. something like this?
getCheckedString = function () {
var chunks = [];
var checkboxes = $("#theForm").children('input[type=checkbox]').each(function () {
chunks[chunks.length] = $(this).is(':checked') ? '1' : '0';
});
return chunks.join('');
}
This will gather up all of the checkboxes in the order they are on the form, put a '1' or '0' in the array, then return the array joined into a string. It's not specific to a particular name, so if there are other checkboxes in the form let me know and I'll alter my answer.
If you have only named checkboxes, you would do:
function getCheckedString1() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var boxes = document.getElementsByName("restriction" + i); // returns an array
if (boxes[0]) {
val += boxes[0].checked ? "1" : "0";
}
}
// alert(val);
return val;
}
However, it is easier and the usual praxis to identify the referenced HTML elements with ID's. So, you would enhance your HTML:
<input type="checkbox" name="restriction1" id="restriction1" ...
<input type="checkbox" name="restriction2" id="restriction2" ...
and then use:
function getCheckedString2() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var box = document.getElementById("restriction" + i); // returns the unique element
if (box) {
val += box.checked ? "1" : "0";
}
}
// alert(val);
return val;
}

Javascript helper method for generating select tag based on provided values

I am trying to create a helper method in my JS toolkit that looks like this
var selectOptionValues = [" ","NA","Yes","No"];
var selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
// build the selectlist
// if the selectedValue is not null make this value selected
// return select tag
}
I am tried to do something like selectedOption = selectTag[selectedValue] and then selecteOption.selected = true but its not working.
Assuming you're generating option by creating DOM nodes and the part that isn't working, is the selected state of the No option. Try selectOption.setAttribute("selected","selected") - roughly...
var selectOptionValues = [" ","NA","Yes","No"], selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
var selectList = document.createElement("select"), selectOption;
for (var i=0, totalOptions = selectOptionValues.length; i < totalOptions ; i++) {
selectOption = document.createElement("option");
selectOption.value = selectOptionValues[i];
selectOption.innerText = selectOptionValues[i];
if (selectOptionValues[i] == selectedValue) {
selectOption.setAttribute("selected","selected");
}
selectList.appendChild(selectOption);
};
return selectList;
}
In addition to method Dean Burge suggested, you can also set the default value by selectedIndex property of select object. If you make selectedValue the index of desired value, it becomes pretty simple:
//selectedValue==3;
yourPopulatedSelect.selectedIndex=selectedValue;
//"No" will be selected

Categories

Resources