Build URL link from Custom Options using JS logic - javascript

Thank you in advance.
I am still learning JavaScript and as a project approached, really need some help/insight.
The logic that I am working on is this:
1. HTML structure:
<input title="Type Here" class="search" type="text" placeholder="Type Here">
<select id="device_select">
<option id=one value='a'>a</option>
<option id=two value='b'>b</option>
<option id=three value='c'>c</option>
<option id=many value='many'>many</option>
</select>
<span class="content-btn-1" type="button"></span>
2. JS structure:
$(function(){
var one = {title:"titletext", description:"descrtext", keyword:"text",
subject:"533,567,457", provider:"c9drlt-sdgtrzz", training:"true"};
var two = {title:"titletext", description:"descrtext", keyword:"textthis",
subject:"537", provider:"c9drlt-sdgtrjt", training:"false"};
});
3. JS logic structure:
function search_class() {
if (training == true) {training = "&tr=0";} else {training = "";}
return training;
}
function search_custom() {
// NOT SURE HOW TO PULL IT UP
// if subject has more than 1 variable like subject:"533,567,457"
// then construct the logic to separate them:
// &s=533&s=2&567&s=3&457
return subject;
}
var url = "www.website.com";
var text_area = $('.search');
var btn_click = $('.content-btn-1');
btn_click.click (function () {
var value = text_area.val();
var ty = "#s=";
if ($.trim($(text_area).val())) {
window.location.href = url+ty+search_class()+search_custom();
}
});
4. The outcome:
www.website.com#s=titletext&d=descrtext&t=text&p=c9drlt-sdgtrzz&tr=0&s=533&s=2&567&s=3&457
5. The hard part:
How can we do the logic so it takes that array in #2, attaches to the option id one, two ... etc in #1 and then constructs the link in #3 on click?
In nutshell: This is a search function with options that has unique variables.
Appreciate any help!

First off, I think you want to clean up your select box a bit, and give it values you can actually use in javascript.
<input title="Type Here" id="search_text" type="text" placeholder="Type Here" />
<select id="device_select">
<option value='1'>a</option>
<option value='2'>b</option>
<option value='3'>c</option>
<option value='0'>many</option>
</select>
<input id="submit_button" type="button" />
Then we need to clean up your object a bit so it's a) more readable, and b) it links to your select box nicely. If we nest it into one object, referencing it later will be easier.
// we would like an array that corresponds with our values in the select box.
var options = [
false,
{
title: "titletext",
description: "descrtext",
keyword: "text",
subject: "533,567,457",
provider: "c9drlt-sdgtrzz",
// a boolean like "false" or "true" should not be surrounded by braces, is easier to manipulate.
training: true
},{
title: "titletext",
description: "descrtext",
keyword: "textthis",
subject: "537",
provider: "c9drlt-sdgtrjt",
training: false
}
];
The final bit is in the logic. I've tried to streamline it a bit but the most important change is the for-loop in this case, as it will list every key/value pair and then we can add it to our search string. I Have also included some error dodging here, like checking if theres empty values and if the selected values actually exist (for example, if you select 3 in device_options, we don't have that index in our options array above, so we can't actually construct that - but it won't actually error out.)
$("#submit_button").on("click", function(event){
// now for the hard part, converting your select item into a string and appending the text
// 1. get the search string from the input
var searchstring = "#searchText=" + $("#search_text").val().trim();
// 2. get the select box value of the selected option
var selected = $("#device_select").val();
// 3. Get the corresponding value.
// If the corresponding value is false (remember the first item in the array above?), then we do nothing.
// We also do nothing if we are looking for an undefined number in the array (say, item #238)
selected = typeof options[selected] != "undefined" && options[selected] !== false
? options[selected]
: false;
// if selected was not set to false, then it exists in our options and we can use it.
if(selected){
for(key in selected){
// if you set a value in options to false, we'll ignore it here using a 'continue'
// continue will move on to the next iteration of the for loop immediately
if(!selected[key]) continue;
searchstring += "&" + key + "=" + selected[key];
}
window.location.href = "http://www.mysite.tld/" + searchstring;
} else {
// log an error here.
if(console) console.log("Could not find device!");
}
});
Does this make sense/help? I have not tested this myself, but it should all work.

Related

how to get text from multiple selected values of select2 input using javascript

I used select2 for my input select and set multiple is true. In my case, I tried to get text array from multiple selected values using javascript function.
This is my javascript and html input :
<script type="text/javascript">
function getRoles(val) {
$('#role-cm_role_text').val('');
var data = $('#role-cm_role').select2('data')[0].text;
$('#role-cm_role_text').val(data);
$('#role-cm_role').on('select2:unselecting', function (e) {
$('#role-cm_role_text').val('');
});
}
</script>
<select id="role-cm_role" class="form-control" name="Role[CM_ROLE][]" multiple size="4" onchange="getRoles(this.value)" style="display:none">
<option value="INQUIRY">CM Inquiry</option>
<option value="SUPERVISOR">CM Supervisor</option>
<input type="hidden" id="role-cm_role_text" class="form-control" name="Role[CM_ROLE_TEXT]">
So if I try to select one value, the result of CM_ROLE_TEXT is same with CM_ROLE. But if I try to select multiple values, the resul of CM_ROLE_TEXT is just get a first value of CM_ROLE.
Result if try to select multiple values :
[CM_ROLE] => Array
(
[0] => INQUIRY
[1] => SUPERVISOR
)
[CM_ROLE_TEXT] => CM Inquiry // I need the result of CM_ROLE_TEXT is same with the result of CM_ROLE
Anyone can help me how to fix my issue? Thank you
From what i can see, the problem is with this line right here
var data = $('#role-cm_role').select2('data')[0].text;
As you are only selected the 1st [0] of the array only. So this is indeed the expected behaviour. So to get all the results text in the array, you can perhaps do something like this
var data = $('#role-cm_role').select2('data').map(function(elem){
return elem.text
});
then you will have an array of all the strings selected. Read about map function here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Here is a live example : https://jsbin.com/qujocujuko/edit?html,js,output

html select list - get text value by passing in a variable?

I have a select list that displays a list languages.
<select name="language_code" id="id_language_code">
<option value="ar">Arabic - العربية</option>
<option value="bg">Bulgarian - Български</option>
<option value="zh-CN">Chinese (Simplified) - 中文 (简体)‎</option>
<option value="en" selected="selected">English (US)</option>
<option value="fr-CA">French (Canada) - français (Canada)‎</option>
</select>
I am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:
$('#id_language_code option:selected').text()
How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?
This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".
I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!
Here is an example of how you can use CSS selectors to query the value attribute:
function getOptionTextByValue(value) {
return $('#id_language_code option[value=' + value + ']').text();
}
var bgText = getOptionTextByValue('bg');
Here is a working example
http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview
You have some data, and you have the view of this data (html/dom), but it's best if you go data -> view, rather than view -> data.
For example, say you have this array:
var languages = [
{short: "ar", text: "Arabic - العربية"},
{short: "bg", text: "Bulgarian - Български"},
{short: "en", value: "English (US)"}
];
Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"
languages.filter(function(x){ return x.short === 'bg' })[0].text;
Or create DOM nodes from it:
function option(x){
var el = document.createElement('option');
el.value = x.short; el.textContent = el.text;
return el;
}
function select(options){
var el = document.createElement('select');
options.forEach(function(x){ el.appendChild(x); });
return el;
}
var element = select(languages.map(option));
element.id = 'id_language_code';
Hmm, if I understand correctly, you want to retrieve the label associated with a given value of one of the options of the <select> element, which will not necessarily be the currently selected option. Using pure JavaScript approach (aka. No jQuery, since there's already a nice one provided by someone else):
function getOptionLabel(selectId, optionValue){
// Get select element and all options
var sel = document.getElementById(selectId);
var selOpts = sel.options;
// Cycle through each option to compare its value to the desired one
for(var i = 0; i < selOpts.length; i++){
if (selOpts[i].value == optionValue){
return selOpts[i].label;
}
}
// Default return value
return "Option not found.";
}
To get the Bulgarian option from a <select> of the given id, you could call it like so:
getSelectLabel("id_language_code", "bg");
Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

Pass HTML dropdown menu values to JavaScript function & onclick function call

I know that this question has been asked in several ways, but they have not helped me, and I'm getting an "undefined" error when I try to debug this.
It's simple: I have an HTML dropdown menu with several different metric units on it, and I have given each a value. I want to pass the selected value to a JavaScript function that will check the metric unit type and then convert it to a corresponding English unit.
The dropdown HTML:
e<p><span><label for="metric-unit">Select metric unit</label></span>
<select name="metric" id="metric">
<option value="cel">Celsius</option>
<option value="cm">Centimeters</option>
<option value="kg">Kilograms</option>
<option value="ml">Milliliters</option>
</select>
</p>
My JavaScript function attempt to pass the value:
metricUnit = document.getElementById("metric").value;
My second question is on calling the conversion function. I want to do that once the metric unit is selected, and a number entered into a text field, and then the user clicks a submission button. Should I call the function with or without arguments, especially if I use getElementById to get the value of the metric unit and the number before any math occurs?
Would it be
onlick ="convertMeasure()"
or
onclick = "convertMeasure(metric, numVal)"
Assuming the id of submission buttons and text field are sub and txt respectively, and you've a default <option> like "choose unit" with value = 0:
var button= document.getElementById("sub");
button.onclick= function(){
var select= document.getElementById("metric");
metricUnit = select[select.selectedIndex].value; //value selected in select
val = document.getElementById("txt").value; // value entered in text field
if(metricUnit!=0 && !isNaN(val)){ // make sure selected item is not default and the text in textbox is a number
convertMeasure(metricUnit, val); // call your function
}
}
It seems like you're putting your click binding somewhere in the html like this
<div onclick='callThisFunction()'> Click on this div </div>
Then in your javascript, you can have that function. In it, you can get the selected value of the drop down list and do whatever logic you need.
<script>
function callThisFunction() {
var dropdown = document.getElementById("metric");
var unit = dropdown.options[dropdown.selectedIndex].value;
var nameOfUnit = dropdown.options[dropdown.selectedIndex].text;
if (unit == "cm") {
// do stuff
} else if (unit == "ml") {
// do stuff
}
// etc.
}
</script>
First get your select element
var select = document.getElementById("metric");
and then you can go read the value from options with the selected index
var metric = select.options[select.selectedIndex].value;
As for how to call the convertMeasure() method I would suggest the first one if you are going to get values from multiple elements on the fly.
Here is a jsfiddle to play with http://jsfiddle.net/zEncN/

Specifying the values of two elements in an If Statement by (separate) classes and/or data-values

My apologies for writing such a lengthy question but I was asked to clarify several details about the function
What would be the correct way to add another element to these If Statements if I want to call it by class or data-name (or another method which doesn't require creating separate If Statements for each element which will utilize it)?
The function is used on pairs of 2 interconnected elements (who's classes are complaint and ranking). The name of the 1rst Element matches the data-name of the 2nd Element, and since the function already identifies data-name of "ranking" maybe it can say that the name of the 1rst element = data-name of the 2nd element?
if ($(this).val() == 1 && !$(this).data("decrease_priority1")) { ... }
if ($(this).data("decrease_priority1") && $(this).val() != 1) { ... }
Here's what I'm trying to do:
1rst If Statement - Set element if values are: ".complaint" = "Too_small" AND ."ranking" = "1"
2nd If Statement - Update element if values are: ".complaint" = "Too_small" OR ."ranking" = "1"
This 2nd element is the value of the select tag under the .complaint class, however there are several element with the same class so I need a way to specify which one it is. I'm trying to avoid using ID's because there are 25 Select elements (so well over 100 combinations).
Method I've Tried
This doesn't work properly (It doesn't accept input unless the 1rst pair (Shoulders) is selected before the 2nd pair (Waist))
if ($(".complaint select").val() === "Too_small" && $(this).val() == 1 && !$(this).data("increase_priority1"))
{ ... }
if ($(this).data("increase_priority1") && ($(this).val() != 1 || $(".complaint select").val() != "Too_small"))
{ ... }
What the function does
The purpose of this Change function is to take all the complaint names selected (i.e. Shoulders, Waist) and group them into actions (i.e. increase or decrease) by ranking, so there are different functions that get called for the various combinations - in this case "Too_small" AND "1". This snippet adds values to "increase_priority1" when the user selects both a complaint and ranks the importance level of the issue, and removes the value when the user changes either element.
If you want to see this in context, I created 2 fiddles. The first is of the existing script http://jsfiddle.net/chayacooper/vWLEn/171/ and the second is a working example of what I'm trying to do but it uses ID's to do so http://jsfiddle.net/chayacooper/gYtZw/61/
Javascript
var $increase_priority1 = $(".increase_priority1");
// variables for other issues and priority levels go here
$(".ranking").change(function () {
var name = $(this).data("name"); // Gets data-name of ".ranking"
// Sets & Unsets increase_priority1
// I need to change this to state If values are "Too_small" AND "1" AND (...)
if ($(this).val() == 1 && !$(this).data("increase_priority1")) {
//rank is 1, and not yet added to priority list
$("<option>", {text: name, val: name}).appendTo($increase_priority1);
$(this).data("increase_priority1", true); // flag as a priority item
}
//If either ranking or complaint value changes
if ($(this).data("increase_priority1") && $(this).val() != 1) {
//is in priority list, but now demoted
$("option[value=" + name + "]", $increase_priority1).remove();
$(this).removeData("increase_priority1"); // no longer a priority1 item
}
// Similar If Statements go here to set & unset elements for other priority types
});
If the value of $increase_priority1 is "Shoulders", complaint was Shoulders too small (select name=Shoulders value=Too_small), and it was assigned a level 1 priority (select class="ranking shoulders" value=1).
HTML
<label>To Increase - 1rst Priority
<select name="modify_increase_1rst[]" class="increase_priority1" multiple></select></label>
<span class="complaint"><label>Shoulders</label>
<select name=Shoulders><option value="null">Select</option><option value="Too_small">Too Small</option><option value="Too_big">Too Big</option><option value="Too_expensive">Too expensive</option>
</select></span>
<label>Ranking</label>
<select name="importance_bother_shoulders" class="ranking shoulders" data-name="Shoulders">
<option value="Null">Select</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>
<option value="5">5</option>
</select>
I'm finding your question a bit confusing, but
$(".ranking, .complaint select")
referring to two different elements there seems a bit scary with all of your use of $(this) within the function, as well as the fact that from within the selected .complaint select you've brought in to the jQuery factory, you're again calling all
$('.complaint select')
in your first if statement. That jQuery factory call pulls in an array of all of your .complaint select elements, so, checking .val() on it probably has undesired results. I'm sure you intend to check $(this).val() instead, or at least target only one .complaint select element, and not the entire array. If you want to check the entire array, you should investigate using .each().
More along the lines of what you're trying to do? Again, it's very hard to decipher what you're actually trying to do here between confusion about the code (it's very haphazardly) and confusion about the application purpose itself. This is moreso conceptual to show you how to separate these elements. You need to modularize them, they shouldn't share any concerns:
$(".complaint select").change(function() {
var name = $(this).data("name"); //get priority name
// Why was it && before? It's either Too_small or 1 or "Too_small" == 1 so
// you don't have to check twice for the same thing
if (($(this).val() === "Too_small" || $(this).val() == 1)
&&!$('.ranking').data("increase_priority1")) {
//rank is 1, and not yet added to priority list
$("<option>", {text:name, val:name}).appendTo($increase_priority1);
// .complaint select does not contain a data "increase priority"
//$(this).data("increase_priority1", true); //flag as a priority item
});
$('.ranking').change(function(){
if ($(this).data("increase_priority1") &&
($(this).val() != 1)) {
$(".complaint select").each(function(){
if($(this).val() != "Too_small"){
//is in priority list, but now demoted
$("option[value=" + name + "]", $increase_priority1).remove();
$(this).removeData("increase_priority1"); //no longer a priority item
}
}
});
Special thanks to #Lorax for helping me figure this out :-)
I've included the final code below and created a working example of it at http://jsfiddle.net/chayacooper/6YnQd/42/
Javascript
$('.complaint select.complaintOpt').change(function() {
var $container = $(this).parent(),
$item = $container.find('.complaintItem'),
itemId = $item.attr('id'),
itemVal = $item.val(),
itemText = $item.find('option[value=' + itemVal + ']').html(),
rank = $container.find('.complaintRanking').val();
// Ignore if not a complete complaint
if((itemVal == 'Null') || (rank == 'Null')) {
return;
}
// Remove any existing complaint
$('select.priorityIssue option.' + itemId).remove();
var $selectedOption = $item.find('option:selected');
var targetBase = '';
if($selectedOption.hasClass('goal-increase')) {
targetBase = '#priorityIncrease';
}
else if($selectedOption.hasClass('goal-decrease')) {
targetBase = '#priorityDecrease';
}
if(targetBase != '') {
// Add new complaint
$(targetBase + rank + 'Issues')
.append($('<option>' + $item.attr('name') + '</option>').addClass(itemId));
}
});
HTML
<label>To Increase </label><br/>
<label for="priorityIncrease1Issues">First Priority</label>
<select name="modify_increase_1rst[]" id="priorityIncrease1Issues" class="priorityIssue" multiple></select>
<label for="priorityIncrease2Issues">Second Priority</label>
<select name="modify_increase_2nd[]" id="priorityIncrease2Issues" class="priorityIssue" multiple></select>
<br/>
<label>To Decrease </label><br/>
<label for="priorityDecrease1Issues">First Priority</label>
<select name="modify_decrease_1rst[]" id="priorityDecrease1Issues" class="priorityIssue" multiple></select>
<label for="priorityDecrease2Issues">Second Priority</label>
<select name="modify_decrease_2nd[]" id="priorityDecrease2Issues" class="priorityIssue" multiple></select>
<br />
<div class="complaint">
<label for="shoulders">Shoulders</label>
<select name=Shoulders id="shoulders" class="complaintOpt complaintItem">
<option value="Null">Select</option>
<option value="too_big" class="goal-decrease">Too Big</option>
<option value="too_small" class="goal-increase">Too Small</option>
</select>
<label for="shouldersRanking">Ranking</label>
<select name="importance_bother_shoulders" id="shouldersRanking" class="complaintOpt complaintRanking">
<option value="Null">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories