Jquery string replacement € - javascript

I use this Jquery code to hide the € symbol on my page.
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
but for some reason I'm unable to get it to work inside WordPress.
I know it has to be in the Document ready function because of the no-conflict mode.
So that is what I have done.
This code is in the same js file i use for other scripts loaded on the same page;
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
(function($){
jQuery(document).ready(function(){
console.log("ready to use!");
if(jQuery('.single-product').length > 0) {
var _sfm_brand = '';
var _sfm_model = '';
var _sfm_generation = '';
var _sfm_engine = '';
var _sfm_engine_ecu = '';
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
_sfm_brand = getUrlVars()["_sfm_brand"];
_sfm_model = getUrlVars()["_sfm_model"];
_sfm_generation = getUrlVars()["_sfm_generation"];
_sfm_engine = getUrlVars()["_sfm_engine"];
_sfm_engine_ecu = getUrlVars()["_sfm_engine_ecu"];
if(typeof _sfm_brand !== "undefined" && _sfm_brand != "") {
jQuery('input[name="tmcp_textfield_0"]').val(decodeURIComponent(_sfm_brand));
jQuery('input[name="tmcp_textfield_0"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_0"]').val('');
}
if(typeof _sfm_model !== "undefined" && _sfm_model != "") {
jQuery('input[name="tmcp_textfield_1"]').val(decodeURIComponent(_sfm_model));
jQuery('input[name="tmcp_textfield_1"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_1"]').val(decodeURIComponent(""));
}
if(typeof _sfm_generation !== "undefined" && _sfm_generation != "") {
jQuery('input[name="tmcp_textfield_2"]').val(decodeURIComponent(_sfm_generation));
jQuery('input[name="tmcp_textfield_2"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_2"]').val(decodeURIComponent(""));
}
if(typeof _sfm_engine !== "undefined" && _sfm_engine != "") {
jQuery('input[name="tmcp_textfield_3"]').val(decodeURIComponent(_sfm_engine));
jQuery('input[name="tmcp_textfield_3"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_3"]').val(decodeURIComponent(""));
}
if(typeof _sfm_engine_ecu !== "undefined" && _sfm_engine_ecu != "") {
jQuery('input[name="tmcp_textfield_4"]').val(decodeURIComponent(_sfm_engine_ecu));
jQuery('input[name="tmcp_textfield_4"]').prop('readonly',true);
} else {
jQuery('input[name="tmcp_textfield_4"]').val(decodeURIComponent(""));
}
}
});
})(jQuery);
And that code is working great. So I'm sure the file is loaded.
Also, what is strange is when loading the js file by the url I get it like this:
(function($){
jQuery(document).ready(function() {
jQuery(".amount:contains('€')").html(function(_, html) {
return html.replace(/(€ )/g, '');
});
});
})(jQuery);
I also tried to change the € symbol with € and u20ac but they are also not working.
Any one who can help me out?
Thank you :)
EDIT: in Jsfiddle it is working. And I allready did some other articles, but with no luck. So that is why I'm posting my own.

Wordpress had alot of javascript and php functions loaded, so may one of theme overide or conflict with your codes.
If what you want is hide € character, better add this into your theme's functions.php:
function replace_text($text) {
$text = str_replace('€', '', $text);
return $text;
}
add_filter('the_content', 'replace_text');
in case above method not working. Use this instead:
jQuery(document).ready(function(){
jQuery('body').hover(function() {
let search = '€';
if(jQuery('.amount:contains('+search+')').html()!=undefined){
var text =
jQuery('.amount:contains('+search+')').html().replace(search, '');
jQuery('.amount:contains('+search+')').html(text);
}else{
return false;
}
});
});

I also did try to change the currency symbol with an function. But It is not getting the page-template;
add_filter( 'woocommerce_currency_symbol', 'change_currency_symbol', 10, 2 );
function change_currency_symbol( $symbols, $currency ) {
if ( is_page_template( 'archive-chiptuning.php' ) && ( 'EUR' === $currency )) {
return '';
}
return $symbols;
}
Without is_page_template it is working, but since I use different products, with different currencys (€ and credit(s)) I'm not able to use it like that. Because it changes all the symbols.
EDIT: check for page template outside loop:
add_filter( 'woocommerce_currency_symbol', 'change_currency_symbol', 10, 2 );
function change_currency_symbol( $symbols, $currency ) {
global $template;
if ( basename( $template ) === 'archive-chiptuning.php' && ( 'EUR' === $currency )) {
return '';
}
return $symbols;
}
Use:
global $template;
if ( basename( $template ) === 'archive-chiptuning.php'
Thanks to this post: https://wordpress.stackexchange.com/questions/328384/is-page-template-not-working/375028#375028

Related

checking each div in page and change value according to the data in the div

i have buttons created via display suite(the buttons contain 'join' text i need to run the function check to see the value should be join or leave.
you can find my js code and my check function code. my problem is i think im calling the function the wrong way.
function init() {
$('div').each(function(){
$ajax('checkteam')
.then(function(){
if (res.data === true){
var button = $(this).find('.button.pulse');
$(button).text === 'Leave';
$(button).data('leave', true);
}
else {
}
}
)
})
}
'checkteam' => array(
'type' => MENU_CALLBACK,
'page callback' => 'card_generator_check_team_ajax',
'page arguments' => array(2),
'access arguments' => array('access content'),
),
function card_generator_check_team_ajax($term_name) {
global $user;
$term = reset(taxonomy_get_term_by_name($term_name));
$tid = $term->tid;
$user_fields = user_load($user->uid);
$arrlength = (sizeof(($user_fields->field_teams[und])));
for($x = 0; $x < $arrlength; $x++) {
$mytid = ($user_fields->field_teams[und])[$x]['tid'];
if ($tid == $mytid){
return true;
}
return false;
}
}
i need to get the data from checkteam function and if its true then the value should be leave.
here is my code right now but it has one issue which is always execute onetime and not for each (views-row). i will attach my layout in picture.
(function ($) {
Drupal.behaviors.card_generator = {
attach: function (context, settings) {
$('.views-row', context).each(function(){
var button = $(this).find('.button.pulse'),
termName = $(this).find('.field-name-title .field-item');
$.ajax({
url: Drupal.settings.setProject.ajaxUrlcheck + '/' +
$(termName).text(),
method: "GET",
})
.then(function(res){
if (res === 'true'){
$(button).text('Leave');
}
}
)
})
}
};
})(jQuery);
problem solved! the php function was wrong.
function card_generator_check_team_ajax($term_name)
{
global $user;
$term = reset(taxonomy_get_term_by_name($term_name));
$tid = $term->tid;
$user_fields = user_load($user->uid);
$arrlength = (sizeof(($user_fields->field_teams[und])));
for ($x = 0; $x < $arrlength; $x++) {
$mytid = ($user_fields->field_teams[und])[$x]['tid'];
if ($tid == $mytid) {
$arr = 'true';
continue;
}
}
drupal_json_output($arr);
}
Your post looks like a crazy mix of PHP and JavaScript. Here are some basic changes I might suggest.
$("div", context).each(function(i, el) {
var termName = $(".field-name-title .field-item", this).text().trim();
$.get(Drupal.settings.setProject.ajaxUrlcheck + "/" + termName,
function(res){
if (res === "false") {
$(".button.pulse", el).html("Leave");
}
}
);
});
.each() iterates each element, so you can get the index and element. You can use $(el).find('.button.pulse') or you can use $(".button.pulse", el) to select the proper elements in jQuery.

How to add validation so that the form does not accept blank spaces?

$scope.addTodo = function ()
{
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
};
try this:
$scope.addTodo = function () {
if ($scope.formTodoText.replace(/\s/g,'').length > 0) {
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
}
};
Remove all spaces in the value and check if there's anything left.
I would do like this:
`$('#MyForm input').blur(function()
{
if( !$(this).val() && $(this).val() != "" ) {
$(this).parents('p').addClass('warning');
}
});`

how to create an ajax request when server file(like php) doesnt exist?

i was developing sharetronix script but there is something realy odd about this script i can see in console network request goes for example for this address
http://localhost/ajax/postform-submit/ajaxtp:xml/r:0
but i cant find any folder with postform-submit name.i know this is possible with redirection using htaccess but i cant find anything in htaccess file.
this is part of js code where this request send
function postform_submit_step4()
{
var req = ajax_init(true);
if( ! req ) { return; }
var p = "post_temp_id="+encodeURIComponent(pf_data.temp_id)+"&message="+encodeURIComponent(pf_data.message);
if( pf_data.existing_post_id != "" ) {
p += "&editpost="+encodeURIComponent(pf_data.existing_post_id);
}
else if( pf_data.share_with_type == "user" ) {
p += "&username="+encodeURIComponent(pf_data.share_with_xtra);
}
else if( pf_data.share_with_type == "group" ) {
p += "&groupname="+encodeURIComponent(pf_data.share_with_xtra);
}
if( pf_data.at_link[0] ) {
p += "&at_link="+encodeURIComponent(pf_data.at_link[0]);
}
if( pf_data.at_image[0] ) {
p += "&at_image="+encodeURIComponent(pf_data.at_image[0]);
}
if( pf_data.at_file[0] ) {
p += "&at_file="+encodeURIComponent(pf_data.at_file[0]);
}
if( pf_data.at_videoembed[0] ) {
p += "&at_videoembed="+encodeURIComponent(pf_data.at_videoembed[0]);
}
req.onreadystatechange = function() {
if( req.readyState != 4 ) { return; }
if( ! req.responseXML ) { return; }
var data = req.responseXML.getElementsByTagName("result");
if( !data || !data[0] ) { return; }
data = data[0];
var status = data.getElementsByTagName("status");
var message = data.getElementsByTagName("message");
if( !status || !status[0] || !message || !message[0] ) {
return;
}
status = status[0].firstChild.nodeValue;
message = message[0].firstChild.nodeValue;
if( status != "OK" ) {
d.getElementById("pf_postederror_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postederror", 36);
postform_htmlobject_show("pf_mainpart", 114, function() { pf_open_state=1; pf_post_state=3; d.post_form.message.disabled=false; d.post_form.message.focus(); });
return;
}
d.getElementById("pf_postedok_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postedok", 36, function() { pf_open_state=0; pf_post_state=1; postform_statusmsg_setTimeout(); });
var btn = d.getElementById("postform_open_button");
if(btn) {
btn.style.display = "";
}
if( posts_synchronize ) {
posts_synchronize();
}
var pinf = pf_data.existing_post_id;
if( pinf != "" ) {
pinf = pinf.split("_");
var tmp = w.location.href.toString();
tmp = tmp.replace(/^http(s)?\:\/\//, "");
tmp = tmp.substr(tmp.indexOf("/"));
var mtch = "/view/"+(pinf[0]=="public"?"post":"priv")+":"+pinf[1];
if( tmp.substr(0,mtch.length)==mtch ) {
if( viewpost_synchronize ) {
viewpost_synchronize();
}
else {
w.location.href = w.location.href.toString();
}
}
}
}
req.open("POST", siteurl+"ajax/postform-submit/ajaxtp:xml/r:"+Math.round(Math.random()*1000), true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(p);
}
how is this possible when there is no redirection?
The script is not odd: the way an URL maps to a file not always is so straightforward.
Most web frameworks, for example, use a router/dispatcher to decide what to do/which file to serve given a specific URL.
For example, most MVC web frameworks by default would handle this URL:
http://www.example.com/users/edit/5
by calling the action/method "edit" of the controller "users" passing an argument 5.
Long story short, redirects are not the only way an URL can be mapped to a physical file on the webserver.
To find which file is served or which file contains the code that is executed to produce what you receive, you first need to know which application server/framework is used, and learn how it works.

Unexpected string error when dynamically injecting js script

I need to execute a insert and execute javaScript in the following way:
$("body").append("<script>//Some Code</script>");
I have tried following two encoding methods
Manually move everything to the same line and replace all double quotes with single quotes using search and replace
Fiddle:http://jsfiddle.net/benPearce/vaxo00eb/
String escape the javaScript using stringescape_tool
Both of these methods result in "Unexpected string" syntax errors. If anyone can help me out I'd be greatly appreciative!
The Script I need to inject
seal_gif_url="images/nortonseal.gif";
dn="www.mysite.com";
sap="getnortonsealimage.js";
splash_url="https://trustsealinfo.verisign.com";
tpt="transparent";
language="en";
u1=splash_url+"/splash?form_file=fdf/splash.fdf&dn="+dn+"&lang="+language;
function vrsn_splash() {
tbar = "location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500";
sw = window.open(u1,'VRSN_Splash',tbar);
sw.focus();
}
{
var ver=-1;
var v_ua=navigator.userAgent.toLowerCase();
var re=new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) != null)
ver = parseFloat( RegExp.$1 );
var v_old_ie=(v_ua.indexOf("msie")!=-1);
if (v_old_ie) {
v_old_ie = ver < 5;
}
function maction(e){
if (document.addEventListener) {
var seal=(e.target.name=="seal");
if (seal) { vrsn_splash(); return false; }
} else if(document.captureEvents) {
var tgt=e.target.toString();
var seal=(tgt.indexOf("splash")!=-1);
if (seal){ vrsn_splash(); return false; }
}
return true;
}
function mouseDown() {
if (event.button==1){
if (v_old_ie) { return true; } else { vrsn_splash(); return false; }
} else if (event.button==2) { vrsn_splash(); return false; }
}
document.write("<IMG NAME=\"seal\" BORDER=\"true\" SRC=\""+seal_gif_url+"\" oncontextmenu=\"return false;\">");
if((v_ua.indexOf("msie")!=-1) && (ver>=7)) {
var plat=-1;
var re=new RegExp("windows nt ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) != null)
plat = parseFloat( RegExp.$1 );
if (plat >= 5.1) {
document.write("<div style='display:none'>");
document.write("<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>");
document.write("</div>");
}
}
if (document.addEventListener){
document.addEventListener('mouseup', maction, true);
} else {
if (document.layers){
document.captureEvents(Event.MOUSEDOWN); document.onmousedown=maction;
}
}
function resized(){
if(pageWidth!=innerWidth || pageHeight!=innerHeight){
self.history.go(0);
}
}
if(document.layers){
pageWidth=innerWidth; pageHeight=innerHeight; window.onresize=resized;
}
}
Try escaping your slashes.
<\/script>
Also...You planning on declaring these vars anywhere? :P
seal_gif_url="images/nortonseal.gif";
dn="www.mysite.com";
sap="getnortonsealimage.js";
splash_url="https://trustsealinfo.verisign.com";
tpt="transparent";
language="en";
u1=splash_url+"/splash?form_file=fdf/splash.fdf&dn="+dn+"&lang="+language;
Try:
$("body").append($("<script>", {
text: "//Some code"
}));
The </script> in your string is being interpreted as the end of the Javascript that contains your jQuery code.
The problem is in the code in the script body. This line has quoting problems:
document.write('<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>');
it should be:
document.write('<img src=\\'https://extended-validation-ssl.verisign.com/dot_clear.gif\\'/>');
I think it's also necessary to double the backslashes in this line:
document.write('<a HREF=\''+u1+'\' tabindex=\'-1\' onmousedown=\'return mouseDown(); \' target=\'VRSN_Splash\'><IMG NAME=\'seal\' BORDER=\'true\' SRC=\''+seal_gif_url+'\' oncontextmenu=\'return false; \'></A>');
You need to escape all the slashes because this Javascript is inside a quoted string in the original script.
Not sure what the theory is behind this but there was an unnecessary set of parenthesis enclosing a block of code that was causing the error. See altered javaScript below.
seal_gif_url="images/nortonseal.gif";
dn="www.mysite.com";
sap="getnortonsealimage.js";
splash_url="https://trustsealinfo.verisign.com";
tpt="transparent";
language="en";
u1=splash_url+"/splash?form_file=fdf/splash.fdf&dn="+dn+"&lang="+language;
function vrsn_splash() {
tbar = "location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500";
sw = window.open(u1,'VRSN_Splash',tbar);
sw.focus();
}
var ver=-1;
var v_ua=navigator.userAgent.toLowerCase();
var re=new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) != null)
ver = parseFloat( RegExp.$1 );
var v_old_ie=(v_ua.indexOf("msie")!=-1);
if (v_old_ie) {
v_old_ie = ver < 5;
}
function maction(e){
if (document.addEventListener) {
var seal=(e.target.name=="seal");
if (seal) { vrsn_splash(); return false; }
} else if(document.captureEvents) {
var tgt=e.target.toString();
var seal=(tgt.indexOf("splash")!=-1);
if (seal){ vrsn_splash(); return false; }
}
return true;
}
function mouseDown() {
if (event.button==1){
if (v_old_ie) { return true; } else { vrsn_splash(); return false; }
} else if (event.button==2) { vrsn_splash(); return false; }
}
document.write("<IMG NAME=\"seal\" BORDER=\"true\" SRC=\""+seal_gif_url+"\" oncontextmenu=\"return false;\">");
if((v_ua.indexOf("msie")!=-1) && (ver>=7)) {
var plat=-1;
var re=new RegExp("windows nt ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) != null)
plat = parseFloat( RegExp.$1 );
if (plat >= 5.1) {
document.write("<div style='display:none'>");
document.write("<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>");
document.write("</div>");
}
}
if (document.addEventListener){
document.addEventListener('mouseup', maction, true);
} else {
if (document.layers){
document.captureEvents(Event.MOUSEDOWN); document.onmousedown=maction;
}
}
function resized(){
if(pageWidth!=innerWidth || pageHeight!=innerHeight){
self.history.go(0);
}
}
if(document.layers){
pageWidth=innerWidth; pageHeight=innerHeight; window.onresize=resized;
}

Returning false in Javascript/Jquery within an if statement

I've got this function to check my form:
function checkFrm() {
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
});
}
When the user submits this, it runs this code, and ideally if the criteria is met the form won't submit because of the 'return false;' bit.
However, for some reason it's completley ignoring this!
If I set a return variable at the start like 'var toreturn = true;' then set 'toreturn = false' when the trigger is hit, then 'return toreturn;' right at the end it stops the form submitting just fine... however that's not much use, as the alerts and checks I run in between are all triggered at once which would be completely overwhelming for the user.
Any suggestions please?
Cheers :)
Returning false from the each will not return false from the function.
You will need to set a var to return false from the function also. You can still break out of the each by using return false as soon as your condition fails.
function checkFrm() {
var retVal=true;
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
//set the var to return from the function
retval = false;
//exit out of the each
return false;
}
}
});
return retVal;
}
When you call return false; it refurns false for the function
function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
}
That is not work for you.
You better get an array of selects like this:
var selectsArray=document.getElementsByTagName("select");
and work with them in a loop.
for(var i=0; i< selectsArray.length;i++){
if( selectsArray[i].value === 'null') {
// do nothing
} else {
if(selectsArray[i].next('input').val().length < 1) {
return false;
}
}
}

Categories