JQuery converting "option:contains" into an exact string value - javascript

Right now I am getting a select option's value (literal value attribute) from JQuery, the problem is that it takes the first value it finds that simply "contains" that keyword.
For example, if I had a select with two options: Silver Division (value=1) and Silver (value=2), if I called the following line of code it would return (value=1) rather than (value=2)
var ranking = "Silver"; // hard-coded for example
var setIndex = $("#userElo" +" > option:contains(" + ranking + ")").val();
Q: I have been trying to search, with no success, for something like option:equals so that it only looks for exact string matches. I have tried various test-and-guess things like the following.
var setIndex = $("#userElo" + ID + " > option:contains" + ranking).val();
var setIndex = $("#userElo" + ID + " > option[text=" + ranking + "]").val();
var setIndex = $("#userElo" + ID + " > option[text=" + ranking).val();
Here is a JSFiddle Demo on a simple scale showing the Silver Division and Silver issue.
I am running out of ideas though, so if anyone know of some syntax for this solution that'd be awesome!
Thanks!

You'll need to select all of the options that may potentially match, then use the filter() function to narrow them down to those that do actually match the text you want. This should do it:
var ranking = "Silver";
var setIndex = $("#userElo > option").filter(function() {
return $(this).text() === ranking;
}).val();

Related

How to mix string with variables in an input needing mutiple values in js? (In this case, the coord attribute of the area tag)

So what the problem I have been facing so far is that I am currently trying to use javascript so that the coords attribute of my area tag is set according to some variables(what it is doesn't really matter). However, the coords require 4 inputs (x1,y1,x2,y2) and I have some values that I am not going to use the variable for. Which means that I have to mix string and variables in the input which I have no idea on how to do.
To give you a better sense on what I am doing, here is a summary:
var p = some random value
var q = some random value
var a1 = document.getElementById(areaID);
a1.setAttribute("coords", "0,0, p,q")
Of course this didn't work as the "" made it think that p,q are strings instead of variables. So I tried some other where it all failed(some desperate attempts).
a1.setAttribute("coords", 0,0,p,q);
a1.setAttribute("coords", "0,0," + p + "," + q);
document.getElementById(areaID).coords = 0,0, p,q;
const list = ["0","0", p,q];
a1.setAttribute("coords", list);
So does anyone know how could I possibly do this?
The second option you tried should work. In your example, is areaID a variable or the actual id of the element? If it is the latter, then you need to put it in quotes: document.getElementById("areaID")
var p = "val1"
var q = 23
var a1 = document.getElementById("areaID");
a1.setAttribute("coords", "0,0," + p + "," + q)
console.log(a1);
<div id="areaID"></div>

jQuery if condition doesn't return expected result

I am confused why the if condition not producing the result
Return result of fxresult value = " Call for price " this is not code and just for reference of variable result.
var fxresult = $(".price").html();
var fxRate = fxresult.replace(/ /g,"");
if (fxRate == 'Callforprice'){
alert("found")
}
may you use this regexp instead of yours.
var fxRate = fxresult.replace(/\s/g,"");
yours will work to but i think this one is a lil bit better because you avoid typos like one whitespace or two.
and you have a typo here
var fxresult value = " Call for price "
//---------------------------------------^
missing a ;
but your major problem in this line is
var fxresult value = " Call for price "
//----------^
you have a problem with the var declaration (variable names can't contain spaces)
see working FIDDLE

In Qualtrics surveys, how can you use JavaScript to dynamically set the range of a slider?

I was making a survey in Qualtrics, and needed to have my items show different values of the slider depending on a variable, in my case, the value from a loop and merge. That didn't seem like a thing that you could do with piped text, so I had to figure out how to do it in Javascript.
I'm just posting this as an opportunity to provide the answer I found on my own. As usual with Qualtrics, your mileage may vary, and this may need to be modified for your specific situation. In particular, the question IDs and postTags change depending on whether it is in a loop/merge, and perhaps on other factors.
Put the following code into the javascript section of the question:
// Set the slider range
// First define the function to do it
setSliderRange = function (theQuestionInfo, maxValue) {
var postTag = theQuestionInfo.postTag
var QID=theQuestionInfo.QuestionID
// QID should be like "QID421"
// but postTag might be something like "5_QID421" sometimes
// or, it might not exist, so play around a bit.
var sliderName='CS_' + postTag
window[sliderName].maxValue=maxValue
// now do the ticks. first get the number of ticks by counting the table that contains them
var numTicks = document.getElementsByClassName('LabelDescriptionsContainer')[0].colSpan
// do the ticks one at a time
for (var i=1; i<=numTicks; i++) {
var tickHeader='header~' + QID + '~G' + i
// the first item of the table contains the minimum value, and also the first tick.
// so we do some tricks to separate them out in that case.
var tickSpanArray = $(tickHeader).down("span.TickContainer").children
var tickSpanArrayLength=tickSpanArray.length
var lastTickIndex=tickSpanArrayLength - 1
var currentTickValue = tickSpanArray[lastTickIndex].innerHTML
currentTickValue=currentTickValue.replace(/^\s+|\s+$/g,'')
console.log('Tick value ' + i + ' is ' + currentTickValue)
// now get the new value for the tick
console.log('maxValue: ' + maxValue + ' numTicks: ' + numTicks + ' i: ' + i)
var newTickValue = maxValue * i / numTicks //the total number of ticks
tickSpanArray[lastTickIndex].innerHTML=newTickValue.toString()
console.log('Changed tick value to ' + newTickValue)
}
}
var currentQuestionInfo = this.getQuestionInfo()
var currentQuestionID = currentQuestionInfo.QuestionID
// Now call the function
setSliderRange(currentQuestionInfo, theMaxValueYouWant)
If you find my answers helpful, help raise my reputation enough to add "qualtrics" as a valid tag!! Or, if someone else with reputation over 1500 is willing to do it that would be very helpful!

How can I get these array values to all print into an html form?

I have a small piece of code that generates an array with values based on a triangle. I will post the array below.
var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
i++;
}
This array will have anywhere between 2 to 100 indexes. I want the code to write all of the values separated by breaks into a <textarea> with the id="test83".
If I run the code as it is set up above it will only write the value in array [1] not [0] or any of the others. How can I get it to write all of them so that they come out looking like this...
4 - 140 this is the value of array position [0]
4 - 126
4 - 116 and so on?
You keep replacing the value
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
You would need to append to the value
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
better yet, build up the values and set the value once
var endwallPanelLengths = [totalHeightInches],
i = 0,
output = [];
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
output.push("4 - " + endwallPanelLengths[i]);
i++;
}
document.getElementById("test83").value = output.join("\n");
If I'm understanding you correctly, that you want the array displayed with one item per line in your textarea, then you should be able to ditch your loop completely, and just do it in one shot.
document.getElementById("test83").value = endwallPanelLengths.join('\n');
Although it also looks like you're prepending '4 -' to each value. If that's the case, then you could just add one extra step to get those fours added:
var arr = endwallPanelLengths.map(function(item){ return '4 - ' + item; });
document.getElementById("test83").value = arr.join('\n');
Just be sure to grab the shim for Array.prototype.map from here if you need to support IE8
HTML:
<div id="holder"></div>
JavaScript:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
var holder = document.getElementById("holder");
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
var e = document.createElement('div');
e.innerHTML = "4 - " + endwallPanelLengths[i] + "<br />";
holder.appendChild(e.firstChild);
i++;
}
Hopefully that does for you what you want. In your example, in your loop, you're setting the newest value to the same element, thus overwriting any previous values.

Javascript: Which of these implementations is more efficient/better?

I have an icon that when clicked will increase the value of a number input.
I initially wrote it as:
$('.icon-chevron-up').click(function(){
var input = $(this).next();
var value = eval(input.val());
input.val((value+1).toString());
$(this).next.val(value+1);
});
I then rewrote it as:
$('.icon-chevron-up').click(function(){
$(this).next().val((eval($(this).next().val()) + 1).toString());
});
Is there a preferred way of doing this? And if so, why?
None of those would be the best for efficiency. eval is not needed and if you want performance you should cache your selectors. There are a couple ways you could make it more efficient but I would do it like this:
$('.icon-chevron-up').click(function() {
var $this = $(this),
val = $this.next().val();
$this.next().val( ++val + '' );
});
++ casts val to a number and adds 1. + '' casts the previous number to a string.
If you want something less terse (more readable I guess):
$this.next().val( (parseInt( val,10 ) + 1).toString() );
What do you mean by input? should it be text input or just a html tag?
<button class="icon-chevron-up">Increase</button>
<div id="numinput">12</div>
var input = $('#numinput').html();
$('.icon-chevron-up').click(function(){
input++;
$('#numinput').html(input);
});

Categories