How can I translate my jquery to javascript? - javascript

I have
$('#hidden-data').find('#' + $(this).attr('id')).html(currdata);
var hiddata = $('#hidden-data').find('#' + $(this).attr('id')).html();
I want to translate this to javascript but my brain is melted.
Please help ;p

The simplest version, given that IDs should be unique:
var hiddata = this.innerHTML = currdata;
The shortened jQuery version accounting for ID uniqueness makes this a bit more apparent:
$(this).html(currdata);
var hiddata = $(this).html();
Since you're taking the id attribute from this and no other element should have that ID, just use this, no need to find anything else in the DOM...you should already have the element.

var o = document.getElementById(thisid);
o.innerHTML = currdata;
var hiddata = o.innerHTML;

Related

Javascript ID Extracted From String Not Working

Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.

Add Javascript to replace Span tags

I have an online store that has limited access to make any correct edits to code.
I am trying to implement proper Price Schema as they have:
<span itemprop="price">$57.00</span>
This is incorrect.
It needs to be set up like this
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price">57.00</span>
Is there something in JavaScript or jQuery that can manipulate this by separating the Currency Symbol and Price?
Thanks
You get the ELEMENT text:
var value = $("span[itemprop='price'").text();
Then you could generate the html using regex like:
var html = '$57.00'.replace(/([^\d])(\d+)/,
function(all, group1, group2){
return 'some html here =' + group1 + '= more hear =' + group2 });
Might not be 100% bug-free, but it should get you started:
<script type="text/javascript">
var n = document.getElementsByTagName('*')
for(var i=0;i<n.length;i++)
{
if(n[i].hasAttribute('itemprop')) //get elements with itemprop attribute
{
var p = n[i].parentNode
var ih = n[i].innerHTML //grab the innerHTML
var num = parseFloat(ih) //get numeric part of the innerHTML - effectively strips out the $-sign
n[i].innerHTML = num
//create new span & insert it before the old one
var new_span = document.createElement('span')
new_span.innerHTML = '$'
new_span.setAttribute('itemprop', 'priceCurrency')
new_span.setAttribute('currency', 'USD')
p.insertBefore(new_span, n[i])
}
}
</script>
Somthing along the lines of
// find all span's with itemprop price
document.querySelectorAll("span[itemprop='price']").forEach(function(sp){
// grab currency (first char)
var currency = sp.innerText.substr(0,1);
// remove first char from price val
sp.innerText = sp.innerText.substr(1);
// create new element (our price-currency span)
var currencySpan = document.createElement("span");
currencySpan.innerText = currency;
currencySpan.setAttribute("itemprop", "priceCurrency");
currencySpan.setAttribute("content", "USD");
// Append it before the old price span
sp.parentNode.insertBefore(currencySpan, sp);
});
Should do what your after.
See demo at: https://jsfiddle.net/dfufq40p/1/ (updated to make effect more obvious)
This should work -- querySelectorAll should be a bit faster, and the regex will work with more than just USD, I believe.
function fixItemPropSpan() {
var n = document.querySelectorAll('[itemprop]');
for (var i = 0; i < n.length; i++) {
var p = n[i].parentNode;
var ih = n[i].innerHTML;
var num = Number(ih.replace(/[^0-9\.]+/g, ""));
n[i].innerHTML = num;
//create new span & insert it before the old one
var new_span = document.createElement('span');
new_span.innerHTML = '$';
new_span.setAttribute('itemprop', 'priceCurrency');
new_span.setAttribute('currency', 'USD');
p.insertBefore(new_span, n[i]);
}
}
Here is a suggestion of how you can make this work, though i would not suggest doing it like this (too many cases for content="").
Example of the logic you could use to transform the incorrect format to the correct one.
Hope you find it useful. :]

Manipulation data on javascript

I have some codes like this
var f = document.frmR5B075;
var str = f.cbo_BilServProvCodeHidden.value;
var afterDash = str.substr(str.indexOf("-") + 1);
And i want put afterDash value back to f.cbo_BilServProvCodeHidden.value. I tried use f.cbo_BilServProvCodeHidden.value = afterDash; seems not working / cannot get the value. Any Solution ? Thanks
f.cbo_BilServProvCodeHidden.value = afterDash seems to work for me.
Here is the demo

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);
});

javascript elements not working

I was not able to get part of this javascript code working for unknown reason and display as undefined. How do I merge vote[1] into the formObj which is document.forms[0] Any other alternate solution?
var elements2 = formObj.elements['vote[' + pollId + ']';
There is a basic syntax error:
var elements2 = formObj.elements['vote[' + pollId + ']';
Should be
var elements2 = formObj.elements['vote[' + pollId + ']'];
Could it be that you want:
var elements2 = formObj.vote[pollId];
(Assuming "vote" is the name of several form elements)
You might want to read about how to handle forms in JavaScript.
I'm not a javascript programmer really, but from what I can see above in the code you are missing a "]" at the end of elements.
It looks like your setting elements2 to formObject.elements[i] where you using vote[pollId] as the index. So vote[pollId] should return an integer in this scenario.
I'm not sure if I understand the question
Javascript Arrays
var formObj = document.forms[0];
var i = formObj.length + 1;
formObj[i] = vote[1];

Categories