Can't access JavaScript variable inside function - javascript

I'm making an extension for selected text search in different search engines. One of the menu items changes if the selected string is a particular one. I have this done so far and it does what I want, except I can not make the "title" of the menu change. How do I give value to the variable "myTitle" in if statement inside the function?
Thanks in advance.
var myTitle; // if I give value here it does work, but I need the value based on the if statement bellow.
function myFunction(selectedText) {
if(selectedText.match (/someString|SomeOtherString/)) {
var myURL1 = 'https://someURL' + selectedText;
chrome.tabs.create({url: myURL1});
myTitle = "title1"; //I can not make the variable to get this value here
}else{
var myURL2 = 'https://someOtherURL' + selectedText;
chrome.tabs.create({url: topicCall});
myTitle = "title2"; //I can not make the variable to get this value here
}
}
chrome.contextMenus.create({
**"title": myTitle,** // this should change based on the selection
contexts:["selection"],
onclick: function (info)myFunction(info.selectionText);}
});

You have "cause and effect" mixed up. When chrome.contextMenus.create is called, myFunction has not executed yet and the value of myTitle has not been assigned.

Perhaps, you can use chrome.contextMenus.update, after the page is loaded. You could create the menu, with default titles, but with unique IDs. Then use the above method, based on whatever the "selectedText" is, and use the IDs to replace the titles.

Related

Is there a way to 'reset' a jQuery function each time it is triggered?

I have an eCommerce website product page for a product with color options.
I'm trying to copy the selected color attribute value and append it to the product title, and I'm using any change to the value of #pa_finish as a trigger, to ensure the title is updated with the current selection.
Here is the code I'm presently using:
$( '#pa_finish' ).change(function(){
var var_name = $('#pa_finish :selected').text();
var original = $('h1.product_title.entry-title').text();
$('h1.product_title.entry-title').html(original + ' ' + var_name);
});
The issue I'm having is that, instead of the title refreshing with each trigger, the var_name variable is being iterated alongside the previous value, so the product title ends up simply increasing in length!
Ideally, the pre-existing text value from var_name is cleared, and replaced with the new selection each time a change is made.
Is there a means by which I can 'reset' the function each time it is triggered? Thank you in advance for any help or insight anyone might be able to provide.
Thank you all for your input - I've realised that, as pointed out in the comments, I hadn't established a baseline value for my title.
I have a working example now:
var title = $('h1.product_title.entry-title').text();
$( '#pa_finish' ).change(function() {
var var_name = $('#pa_finish :selected').text();
$('h1.product_title.entry-title').html(title + ' ' + var_name);
});
I've established a value for the original title in a 'title' variable (outside of the function), so that when the function executes it replaces the HTML of:
$('h1.product_title.entry-title')
...with a combination of the original title and the var_name variable, on each change.
Before, it was simply loading the selector again and again, and tagging on the result of var_name, which is why I saw the repitition.
I hope this can help someone in the future.

jQuery - Choosing a variable based on the ID of the element that was clicked

I'm probably overlooking a more obvious way to do what I want, but...
I have a list of JS variables with names that are identical to the ID's of some elements on my page. When I click one of the elmeents, I want to be able to use the clicked element's ID to determine which variable should be used in my function. My variable names correspond to my element ID's - there must be some way to take the value of my clicked element's ID using $(this).id and then find the variable that matches that string? Just to be clear, the content of the variables is not at all related to the variable names or element ID's - the variables are set when the page loads and I'd like to avoid setting them every time the function is run! And I know I could probably use onclick for this, but I'm trying to avoid that because apparently it's inferior now?!
Thanks!
I recommend you to make an array with al of your ids names
thisArray = {
uniqueID1: 'Your value for uniqueID1',
uniqueID2: 'Your value for uniqueID2'
};
you can call an element by a class for example
HTML:
<div id="uniqueID1" class="elements_class"> Div Content </div>
<div id="uniqueID2" class="elements_class"> Div Content </div>
jQuery:
$('div.elements_class').click(function(){
var now_id = $(this).attr('id');
alert(thisArray[now_id]);
});
It seems like what you want is to use .data():
$(el).data('myobject', {
x: 123,
y: 456
});
Then to retrieve:
$(el).on('click', function() {
var obj = $(this).data('myobject');
});
Did you think of storing them in an object?
Example :
var obj = {
'id1' : value1,
'id2' : value 2,
//...
}
Then you can acces them like that
obj[this.id]
If you use an object to store the variables you are talking about with key/value pairings, you can just call variableObject[this.id] to get that variable.

Switching HTML menu value before submit?

So I have a menu with a list of every country and its abbreviation. I want to send the full name (the text of the menu option) instead of the value. So I tried to make a function, switchval(), to do this but it did not switch the values. Any ideas?
function switchval(){
var countries = document.getElementById('countries');
countries = countries.options[countries.selectedIndex].text;
document.getElementById('countries').value = countries;
}
Set the value of the option element. I changed the variable names so they make more sense. Please consider your coding style and use good variable names, and don't use a variable twice for a different datatype (that is insane). Also, setting the value of the option element is just plain wrong, I felt dirty typing this.
function switchval(){
var selectEl = document.getElementById('countries');
var optionEl = selectEl.options[selectEl.selectedIndex];
var country = optionEl.text;
optionEl.value = country;
}
I'll second what buddhabrot showed and said - changing the value property is wrong and might not be supported in all browsers.
I would use a hidden element and set the text property into that, changing the name of the select element to something like "countries-select" and making the hidden element "countries".
That way when your form posts, it will have the proper "name" for the form processor, plus you'll have a reliable method in your code.

Javascript dropdownlist

How can I get the previous selected index on change event of dropdown list using Javascript.
No, it is not possible, but you can use a variable inside onchange event that tracks the previous selection
Example:
var previousSelected;
function track(d){
if(typeof previousSelected != 'undefined'){
alert("Previous selected value " + previousSelected );
}
previousSelected = d.selectedIndex;
alert("selected value " + d.selectedIndex);
}
Place a meta variable in the ul or ol object that is the index of the last selected item so that when you goto the item again you can just ask for that property again and, presto, you know the index of the last selected item.
A common way of placing a meta variable inside an object is by adding a class to the last item that was selected with javascript and then finding the list item with that class when you want to see which one was selected. I see JQuery users doing this alot (btw you should be using JQuery to help with all of your javascript).
For example, to mark the last item as selected:
$('ul li:last').addClass('selected');
Then to find it again:
$('ul li.selected')
Its actually a pretty easy way of tracking this kind of code.
You could have a javascript global variable which will track this value. So when the change event is trigerred you would have the new value and the old one. Then you would update the global variable with the new value.
Here's an example pseudo code:
var selectedValue = '';
document.getElementById('someId').onchange = function() {
var newValue = this.value;
// TODO: compare with the old value
selectedValue = newValue;
};

how to capture the mouseover element?

i am developing an autocomplete feature.but i am facing one problem there...
when i click on the suggestion box one of the results will not enter into the suggest html box...
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
position = oTr.id.substring(2, oTr.id.length);
updateKeywordValue(position);
}
can you plz tell the solution
thanks
function updateKeywordValue(oTr)
{
var oKeyword = document.getElementById("keyword");
var strKeyword="";
var crtLink = document.getElementById("a" +oTr.id.substring(2,oTr.id.length)).toString();
crtLink = crtLink.replace("-", "_");
crtLink = crtLink.substring(0, crtLink.length);
oKeyword.value=unescape(crtLink.substring(googleurl.length, crtLink.length));
strKeyword=oKeyword.value.toString();
if (oTr.id.substring(2,oTr.id.length)==0)
{
oKeyword.value=strKeyword.substring(3,strKeyword.length);
}
selectedKeyword=oKeyword.value;
}
you should get rid of the second parameter in the substring() method. Since you just want the remainder of the string, I'm guessing, that is the default if you don't set a second value.
position = oTr.id.substring(2);
My guess is that you are getting the value of the keyword from the id, and pushing that into the input box, right? If that's the case, we'll need to see more of your code. Specifically, I'd like to see the updateKeywordValue function and I'd also like to know if the text that they are hovering over is the text you are trying to send the input box. If so, you could probably simplify the whole thing and go with something like:
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
keywordbox.value = oTr.innerHTML;
}
But this is based on the assumption that the only data inside the hovered row is the text, and no other html. And I had to make up a name for your input box.
But if this way off, this is because we need more information to see the real problem.

Categories