What I want is to hide certain element using Javascript. Specifically, I want this element showed only if the URL contains the text 'cli'. I tried that using next code
var regex = window.location.href;
if(regex.indexOf('cli')>-1){
$(window).load(function() {
$("[routerlinkactive]")[1].remove();
});
}
The routerlnkactive parts works separatedly. That is, if no if statement is written, it is always removed. But I want that to work only with that URL. How could I do that?
Doesn't seem to be working neither with xxx.html or with xxx.html?cli=30
Thank you.
try using the indexOf() function. So something like
var regex = window.location.href;
if(regex.indexOf('cli')>-1){ //if cli is there
$("[routerlinkactive]")[1].hide(); //hide
}
It will return -1 if not found, and will return the string position number if found (starting at 0).
Also, you should use .hide() to hide, not remove.
UPDATE:
since you are saying its still not working, i have just checked, and this works:
var regex = "xxxxxx.com?cli=50";
if(regex.indexOf('cli')>-1){
alert(true);
}else{
alert(false);
}
So replace alert() with the hide() function and make sure the html is correctly referenced (even though you said that was working okay?). And the value of regex should be window.location.href.
Try adding and removing 'cli' and youll see the difference.
Remove() is not the right choice, that will remove the element from the DOM.
Use hide() and show().
$(document).ready(function(){
//Hide your element by default on page load
$("[routerlinkactive]")[1].hide();
if(window.location.href.indexOf("cli") > -1) {
//If URL has "cli" then show that element.
$("[routerlinkactive]")[1].show();
}
});
Reference of indexOf()
Related
I want to get all "a" tags from page, get its "href" attribute and check if in this href is text ".pdf". So I get all a tags into tags variable, then with each() function I check every "a" (as a tag). But code:
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
is not working. Why? Why I can't use indexOf on href? I tried with search() function, but it's also not working.
So I thought - ok, there's something wrong with this href. Lets take it as a text.
But code:
var text = $(tag).text();
console.log(text);
is also not working. Can anybody tell me why?
Code snippet has errors intentionally - to show with what I have a problem.
Thank you in advance.
(function($){
var tags = $('a');
$(tags).each(function() {
var tag = $(this).attr('href')
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
var text = $(tag).text();
console.log(text);
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
Link with ".pdf"
Link without ".pdf"
</html>
No need to for the additional $(tag) when calling indexOf. tag is a string at that point and you don't need to make it a jQuery object. simply call tag.indexOf('.pdf') > 0. For strings you can also use tag.includes('.pdf') or you go for tag.substr(tag.length - 4, 4) === '.pdf' to make it even more precise.
I've added some custom elements to be included with my WooCommerce account page to be seen with the order history. Unfortunately the page is setup with tabs to only display the information pertaining to the active tab.
I'm not very familiar with jquery, but I thought it would be simple enough to use Jquery to hide the divs I added when the order history has a display of none.
I added the following script to my theme's main.js file:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
When the class .my_account_orders has a display of none it should change the div I added (.paging-nav) to have a display of none. But it just doesn't work.
Is there something wrong with this script or do I need to do something special to initiate it? Since it's in my theme's main.js file and I used $(document).ready(function() I figured it would just load with the page.
Any help with this would be greatly appreciated.
Instead of using:
var display = $('.my_account_orders');
Implement it into the if statement like this:
if($('.my_account_orders').css("display") == "none") {
Because originally it is trying to find a variable called $display, so it would return a syntax error of undefined.
You've got an errant $ in your if statement. This should work instead:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
Also keep in mind that your var display is only going to match the first element that has a class of my_account_orders, so if there are multiple elements with that class, and they don't all have the same display, you could get unexpected results.
Try this:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
I believe it's a very lame way to check for a css property such as display to determine if an element is hidden or not. With jquery, you can make use of :hidden selector which determines whether an element is hidden and return a bool value.
$(document).ready(function(){
if($('.my_account_orders').eq(0).is(":hidden")) // eq(0) is optional - it basically targets the 1st occurring element with class 'my_account_orders'
{
$('.paging-nav').css("display","none");
}
});
Example : https://jsfiddle.net/DinoMyte/sgcrupm8/2/
I have a page that can have one of three possible elements. I would like to assign whatever element exists to a var and then check if the var is clicked.
I tried using the add(), but it has confused me:
var testingVar = $('#element-one').find('.object').add('#element-two').find('.object').add('#element-three').find('.object');
$(testingVar ).click(function() {
alert('works');
});
It seems to me that the add() overwrites the previous add()? if I am on a page that has #element-three, it works, if on a page with element-one or element-two, it doesn't. If I change the var to
var testingVar = $('#element-one').find('.object');
Then a page with element-one works.
Can someone help me understand how to use the add() properly in this case?
Thanks
I think what you're looking for is this:
$('#element-one .object').add('#element-two .object').add('#element-three .object');
.find() returns a new jquery object.
However, I think this would be easier in this case:
$('#element-one .object, #element-two .object, #element-three .object');
Or even easier, if you can change markup, is to give each element you're currently selecting by id a common class, and do this:
$('.common-class .object')
Does anyone know how to do replace multiple text by clicking a button with jQuery?
I've built a website that displays some text/data eg; "£100.00", but I what I need is to be able to 'replace' those monetary values with "£XXX.XX" with a 'Hide' button like you get on some banking websites. For example one web page has:
£100.00, £200.00, £130.00 etc etc..
...so when a user presses the Hide button, all of the numbers on the page turn to £XXX.XX. Ideally, the button should then display "Show" instead of "Hide" and switch back when toggled.
This is for a static dummy site, so no data base.
I suspect this is best handled with jQuery?
Thanks for your time,
D.
Case 1: Controlled Input
Assuming you can at least wrap all monetary values with something like this:
<span class="money-value">£200.00</span>
<span class="money-value">£300.50</span>
And that you can add button declared with:
<button id="secret-button">hide</button>
Then you could have some jQuery code doing this:
/**
* Simple search and replace version.
*/
$(function() {
$("#secret-button").click(function() {
$(".money-value").html($(".money-value").html().replace(/[0-9]/g,"X"));
});
});
or a more advanced one with:
/**
* Complet version.
*
* 1) on button click, if asking to hide:
* 1.1) iterate over all entries, save their text, and replace it with markers
* 1.2) toggle the button's text to "show"
* 2) on button click, if asking to show:
* 2.1) iterate over all entries, restore previous text
* 2.2) clear the hidden store
* 2.3) toggle the button's text to "hide"
*/
$(function() {
var hiddenStore = [];
$("#secret-button").click(function() {
if ($(this).html() == "hide") {
$(".money-value").each(function () {
var text = $(this).html();
hiddenStore.push(text);
$(this).html(text.replace(/[0-9]/g,"X"));
});
$(this).html("show");
} else {
$(".money-value").each(function (i) {
var text = hiddenStore[i];
$(this).html(text);
});
hiddenStore = [];
$(this).html("hide");
}
});
});
Complete solution is here: See here: http://jsfiddle.net/u79FV/
Notes:
this won't work for input field values
this assumes your text entries have been marked as shown above
Does what you want with the button's changing state.
Saves the values and puts them back.
Meant to work even if new fields are added dynamically.
Shankar Sangoli's answer uses a different way of saving the stored data, which you could as well consider (using the jQuery .data() method).
you may want to switch the button to an <input type="button" /> tag, in which case you'd use .val() instead of .html() to toggle its text.
Case 2: Uncontrolled Input
Assuming you don't have control over where the values may show up, then you need to do something a bit more complicated, which is to look in the whole page for something that would look like a currency format. I'd advise against it.
But, the jQuery Highlight plugin could be something to look at, as its code does something similar (in that it searches for pieces of code to modify), and you could then reuse some of solution 1 to make it fit your purpose.
That would be harder to design in a fool-proof fashion though.
You could use a regular expression:
var expression = /\d{1}/g;
var newString = myString.replace(expression,"X");
Then just dump newString into whatever control you need it to appear in.
Edit:
A jQuery idea for something like this would be to give all of the controls that have these numbers a common class identifier to make them easy to grab with the selector:
$(".numbers").each(function() {
$(this).text($(this).text().replace(/\d{1}/g, "X"));
}
... more readable ...
$(".numbers").each(function() {
var text = $(this).text();
var newText = text.replace(/\d{1}/g, "X");
$(this).text(newText);
}
If your markup is something like this you can try this.
<span>£1000.00</span><span class="showhide">Hide</span>
JS
$('.showhide').click(function(){
var $this = $(this);
var $prev = $this.prev();
if(!$prev.data('originalvalue')){
$prev.data('originalvalue', $prev.text());
}
if($this.text() == 'Hide'){
$this.prev().text($prev.data('originalvalue').replace(/\d{1}/g,"X"));
$this.text('Show');
}
else{
$prev.text($prev.data('originalvalue'));
$this.text('Hide');
}
});
In the above code I am basically storing the original value using jQuery data method within the span element itself which is used to display the actual value.
Once you click on Hide, get the previous span using prev() method and set its text with original value replacing all the numbers in it by X. Then change the link text from Hide to Show.
Next when you click on Show get the previous span using prev() method and set its text with the original value and change the link text from Show to Hide.
References: .prev(), .data()
$('#yourButton').click(function(){
var saveText = $('body').text();
$(this).data('oldText', saveText);
if ($(this).text() == "Hide"){
$('body').text($('body').text().replace(/\d{1}/, "X"));
$(this).text('Show');
}
else{
$('body').text($(this).data('oldText'));
$(this).text('Hide');
}
});
This is kind of a complicated problem actually. You will need to be able to save the state of the text when its in number form so you will be able to toggle back and forth. The above code is untested but hopefully it will give you an idea what you need to do.
function toggleMoney() {
$('.money').each(function() {
var $$ = $(this), t = $$.text();
$$.text($$.data('t') || t.replace(/\d/g, 'X')).data('t', t);
});
$('#toggleButton').text($('.money').text().match(/\d/) ? 'hide' : 'show');
}
http://jsfiddle.net/DF88B/2/
My javascript is
function changeImage(imgID) {
var baseurl = "media/images/";
if (document.getElementById(imgID).src == baseurl+"selection-off.png") {
alert('Success');
document.getElementById(imgID).src = baseurl+"selection-no.png"; }
else {
alert('Fail'); } }
and my HTML is
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage('mustard-img')" /></div>
I always get Fail when clicking the image. I must be missing something really elementary.
Some browsers convert the img src to the full url (including http://www....)
try alerting it to make sure..
You could use the
document.getElementById(imgID).src.indexOf( baseurl+"selection-off.png" ) >= 0
which checks if one string is contained in the other..
Alert string document.getElementById(imgID).src. It might be taking complete path i.e. including host name while the string you are comparing with has relative path.
I tried your code on my own server.
Result:
document.getElementById(mustard-img).src is
'http://localhost/webfiles/media/images/selection-off.png'
baseurl+"selection-off.png" is 'media/images/selection-off.png'
baseurl seems to show the relative url only.
So that is the reason why "Fail" gets alerted.
Try with the following code:
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage(this)" /></div>
<script>
function changeImage(img) {
if (img.src.indexOf('selection-off.png')) {
alert('Success');
img.src.replace(/selection-off.png/, 'selection-no.png');
}else{
alert('Fail');
}
}
</script>
The differences with your code:
passing the img reference: this instead of the id in the onclick function
use indexOf instead of ==, for relative paths
Are you sure the DOM is built when the script is loaded ?
It's because the src attribute is changed by the browser. Don't do it that way, the proper way to check and change the css class or style attribute instead.
Image-based checkboxes are quite common, but here is the full solution.
1) Render actual checkboxes first. These work for 100% of browsers.
2) When the page loads, place your "image checkbox" next to the checkbox and hide the checkbox
3) When the image is clicked, toggle the checkbox and use the hidden checkbox to ascertain the state of the image.
When the form is POST-ed, the checkboxes will act like normal checkboxes. If JavaScript is disabled or otherwise not available the form is still usable.