Get script on option select with this value - javascript

I am using a select box to pull some data that is built into the site. However there are a few modules that run a script , and using the select option , that script is not firing when its selected. Do i have to run the full script within my option function , or can it be called to execute again when its selected.
Here is my script and html. Option Value "MESSAGE12" - needs a script to run when selected.
if(unescape(location.href).indexOf("http://football")!=-1||unescape(location.href).indexOf("http://6")!=-1) {
var currentServer=baseURLDynamic;
xmlBaseURL = baseURLDynamic + '/fflnetdynamic' + year + '/';
} else {
var currentServer=baseURLStatic;
}
function getHomePageModule(thisSelection) {
if(thisSelection=="")
document.getElementById("homePageModule").innerHTML = "Your selected module will appear here!";
else {
var url = currentServer + "/" + year + "/home/" + league_id + "?MODULE=" + thisSelection.toUpperCase();
$.get(url, function(data){
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
});
}
}
<select onchange="getHomePageModule(this.value)">
<option value="default">Select A Module</option>
<option value="MESSAGE12" >Get HPM#12</option>
<option value="LIVESCORING" >Link To Live Scoring</option>
<option value="LIVESCORING_SUMMARY" >Live Scoring Summary</option>
</select>
<div id="homePageModule">Your selected module will appear here!</div>
Here is a link to my demo select box - http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE11
And a link to the MESSAGE12 content i'm wanting to fire up in the select box
http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE12
Any advice appreciated

Instead of using innerHTML (which doesn't evaluate <scripts>), you could try using jQuery's .append() method.
Change:
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
to:
$("#homePageModule").append($(data).find('#pageContent').html());
(This also replaces the call to getElementById with a jQuery selector.)
If that doesn't work, you might need to take a look at the content returned by the call to $(data).find('#pageContent').html() and make sure your scripts are there, and/or move the scripts into a function that can be called after the .append() finishes.

Related

JQuery Selector not working, where looping does. Why?

I have two jquery selectors that I used which did not find the desired option where the third "brute force" method did. I am at a complete loss as to why. Each looked like they should of and I validated the document was fully loaded when the selector ran. I tried each with value and text in the selector and got the same result in my page. The html is dynamically loaded using the jquery load method below (where theType is a value coming from a html select control) as well as the associated javascript:
var theType = $('#TicketType option:selected').val();
var theId = $("#Id").val();
var url = '/SystemBuildSiteConfigs/' + theType + '/' + theId;
$('#ticketDiv').html("");
$("#ticketDiv").load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error loading the " + theType + " form");
}
else {
$.getScript("/Scripts/SiteConfig" + theType + ".js", function () {
});
}
});
The html select in question:
<select name="SupportOrganization" class="form-control" id="SupportOrganization">
<option value="">- Please Select -</option>
<option>Auxiliary IT</option>
<option>Business Intelligence</option>
<option>Change Management</option>
<option>Engineering RnD</option>
<option>Enterprise Business Solutions</option>
<option>Enterprise Solutions</option>
<option selected="selected">Hosting</option>
<option>Infrastructure and Operations</option>
<option>Manufacturing</option>
<option>Professional</option>
<option>Support</option>
</select>
First selector statement:
$("#SupportOrganization").find('option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
Second selector statement:
$('#SupportOrganization option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
What worked:
$('#SupportOrganization option').each(function (idx, ele) {
if ($(ele).val() == jsonObj.SupportOrganization)
$(ele).attr("selected", true);
});
The page segment loads correctly and all the other javascript that fires to load html controls with content are executing as expected. Another page type loads and fires correctly performing similar functions. Using jsfiddle, both selectors show they work correctly. What I found through testing was
The variable did have the expected value.
The text selector did not work correctly on my page
The value selector did select an object. However I was unable to determine what the object was and the attr() method did not set the target attribute value.
I can go with what I found that will work, just wanted to find out why this wouldn't work. Guessing it has something to do with the dynamically loaded html and javascript?
The jQuery .val() function uses a "hook" for <option> elements to return the text content of the element if the "value" attribute is missing. Your <option> elements don't have "value" attributes, so the selector does not match.
You should select option by using the select .val(string) function, it will find the option with matched string if available in options having value attribute.
So, Your options should be containing the value attribute which is missing in your case e.g:
$(function(){
$("#userEducationDegree").val('A');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree">
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
To continue with what #Pointy said above, you should try :contains instead.
$('#SupportOrganization option:contains("' + jsonObj.SupportOrganization + '")').attr("selected", true);

Using jquery append to add option values into a select element not working

I'm looking to dynamically populate a select element with names of items that are stored into an array.
For some reason it's not working and I'm not sure why.
HTML:
<div class="col-md-4 col-md-offset-4">
<select class="select1">
</select>
and
<select class="select2">
</select>
</div>
Note that I'm using bootstrap for layout.
Here's the jquery I'm using to try and populate ".select1"
JQUERY:
select: function() {
$.each(state.greens, function(index, value) {
$(".select1").append("<option value =' " + index + " '>" + state.greens[index].name + "</option>");
});
}
Note that the function 'select' is stored within an object called 'display'.
state.greens is the name of the array I'm trying to access.
So at the end of my html page I call display.select(); to call the function.
No error messages are showing up in the console.
Also, I saw this question: Appending options to select using jQuery doesn't work
but was looking for a jquery centric answer and this seems like it ought to work.
You can do in that way:
$.each(state.greens, function(index, value) {
$('.select1').append($('<option>', {
value: index ,
text: state.greens[index].name
}));
});
When you append you are basically adding to the .innerHTML value of a container. This works for most elements except for <select>. You'll have to add elements properly for the DOM to pick it up:
var select=document.getElementById('select1');
var option=document.createElement('option');
option.setAttribute('value','option1');
option.innerHTML='Option 1';
select.appendChild(option);

Reload page after user clicks on combobox (with some rules)

I'm new in javascript and need I to reload the current page after user clicks on the options of combobox, but I have some rules.
The two comboboxes:
<select onChange="Refresh(this.value)" name="comboA">
<option value="0">0</option>
<option value="1">1</option>
</select>
<select onChange="Refresh2(this.value)" name="comboB">
<option value="2">2</option>
<option value="3">3</option>
</select>
Rules:
user clicks on "0" in the first combobox, reload to comboA=0.
user clicks on "1" in the first combobox, replaces "0" to "1" and reload to comboA=1
user clicks on "2" in the second combobox, concatenate and reload to comboA=1 & comboB=2
user clicks on "3" in the second combobox, replaces "2" to "3" and reload to comboA=1 comboB=3
The steps above need to be done in sequence.
How the functions "Refresh" and "Refresh2" should be?
Thanks.
I won't give you the code directly, but I can help you research your answer so that you can learn JavaScript as you go along.
You can use jQuery so help you out but specifically .change() function to detect if the combo box is changed: http://api.jquery.com/change/
To actually refresh the page, or change to another page, you can use the window.location function to direct the user to a page. Window.location.href and Window.open () methods in JavaScript
To actually change elements on the page, without reloading the page, you can use jQuery ajax to post changes to PHP if you need to. http://api.jquery.com/jquery.ajax/
I hope this helps you out in your quest to learn more JavaScript
The first function would simply have to navigate to a the same url followed by ?comboA= then the first argument, like this:
function Refresh(value) {
URL = window.location.href.split("?")[0];
window.location.replace(URL + "?comboA=" + value);
}
The second function would have to keep the ?comboA=value part so it would split after the first & instead:
function Refresh2(value) {
URL = window.location.href.split("&")[0];
window.location.replace(URL + "&comboB=" + value);
}
Try below code in javascript
function Refresh()
{
var e = document.getElementById("comboA");
var selectedOption = e.options[e.selectedIndex].value;
if(selectedOption == "0")
{
// your logic goes here
}
else if (selectedOption == "1")
{
// your logic goes here
}
}
Write same function for other combo box.
I hope these will help you out!!
Let me know if you have any question
you can do it like following:
var url = "http://www.mypage.com?"
$("select[name=comboA]").on("change",function(){
window.location.href = url + $(this).attr("name") + "=" + $(this).val();
});
and for second select
var url2 = "http://www.mypage.com?comboA=1&"
$("select[name=comboB]").on("change",function(){
window.location.href = url2 + $(this).attr("name") + "=" + $(this).val();
});

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

Microsoft translator AJAX API, dropdown to change languageTo and languageFrom?

I am trying to write a translator box for my website. So far, I've been able to get working code from a tutorial:
<input id="ori" type="text" />
<button onclick="translate();">Translate</button>
<div id="trans"></div>
<script>
var languageFrom = "en";
var languageTo = "fr";
function translate() {
document.getElementById('trans').innerHTML="Translating... please wait";
var text= document.getElementById('ori').value;
window.mycallback = function(response) {
document.getElementById('trans').innerHTML=response;
}
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=<MY-APP-ID>&from=" + languageFrom + "&to=" + languageTo + "&text=" + text;
document.getElementsByTagName("head")[0].appendChild(s);
}
</script>
(Script it from here: http://wizardsoweb.com/microsoftbing-translator-ajax-example/2011/05/?wpmp_switcher=desktop)
Basically, once I fill in my APPID, it will translate the text in the ori text box to French. Of course, this all works fine, but here's what I'm trying to do:
I want there to be two drop down menus. One will populate the languageFrom variable with a specified language, and another drop down menu which will populate the languageTo variable with a specified language.
I've already posted about this matter in a different post: Update script var's with value from drop down?. That way, when you select a value from the drop down menu, it populates the variable. I have a working example of this on jsFiddle:
http://jsfiddle.net/charlescarver/hk2bJ/1/
(I included my API key so it's easier to work on)
SO, I think the problem with this is that the script which controls the translation is loaded when the variables are empty, and then doesn't update when a drop down option is selected.
I think this can be fixed by calling the script when the button is clicked, instead of when the page is loaded. How can this be accomplished? The Microsoft support is poorly documented and I can't find a solution there or on google. Here's a link to the API documentation: http://msdn.microsoft.com/en-us/library/ff512385.aspx
You're trying to attach event handlers to objects (select1 & select 2) that essentially don't exist yet (looking at your jsfiddle example) - which breaks the rest of your script, since you're actually failing to attach anything.
So you'll need to do something like this (not the greatest of conventions, but it demonstrates the point)
window.onload = function()
{
document.getElementById("select1").onchange = function() {
languageFrom = this.value;
}
document.getElementById("select2").onchange = function() {
languageTo = this.value;
}
}
(Which means you'll only attach the events once everything is loaded & available)
Something you can also do inline with your html elements, like seen below:
From: <select id="select1" onchange="languageFrom=this.value">
<option value="en">En</option>
<option value="fr">Fr</option>
</select>
To: <select id="select2" onchange="languageTo=this.value">
<option value="en">En</option>
<option value="fr">Fr</option>
</select>
Or Alternatively do everything inside your translate function (which means you don't need to attach anything to your dropdowns nor define any global variable)
function translate() {
document.getElementById('trans').innerHTML="";
var text= document.getElementById('ori').value;
window.mycallback = function(response) {
document.getElementById('trans').innerHTML=response;
}
var languageFrom = document.getElementById("select1").value;
var languageTo = document.getElementById("select2").value;
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=8B841CA7C1A03443682C52AD07B7775A7BD5B3AA&from=" + languageFrom + "&to=" + languageTo + "&text=" + text;
document.getElementsByTagName("head")[0].appendChild(s);
}

Categories

Resources