document.getElementById('').src == ??? (is equal to FAIL) - javascript

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.

Related

Hide element using JavaScript

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()

Jquery script not working to alter CSS on change

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/

Is it possible to hide two divs from two different .php pages with a unique Javascript function?

I have a button in my index.php that shows a menu and hides the content of the page. However it's suppose to work for two different templates. My function basically looks like this :
function show_menu();
{
document.getElementById('menu').style.display="block";
document.getElementById('content1').style.display="none";
document.getElementById('content2').style.display="none";
}
If I only put one of the content, hide it works. However if I put both contents it doesn't. What's going on? Is that impossible or am I doing something wrong?
I am not sure if I got your issue correctly, but if I do, the problem is, that you cannot set the style of elements that do not exist on your page. You have to check for null values:
function show_menu()
{
document.getElementById('menu').style.display="block";
var content1 = document.getElementById('content1'),
content2 = document.getElementById('content2');
if (content1) {
content1.style.display="none";
}
if (content2) {
content2.style.display="none";
}
}
function show_menu() //Removed the semicolon, could be the culprit causing the problem
{
document.getElementById('menu').style.display="block";
document.getElementById('content1').style.display="none";
document.getElementById('content2').style.display="none";
}
I guess that there is no element with content1 id in one of your templates. Then your code will fail when accessing the style property of a not existing element, halting your script execution and not hiding the content2.
Three possible solutions come to my mind:
Use the same ids in all templates. If both contain a content with the same functional purpose, you should name them the same. Your script will work then with all these templates.
Use different scripts or a variable indicating which template is used so the script can determine the correct ids.
Check for the element's existence dynamically (you always should do):
function show_menu() {
var menu = document.getElementById('menu'),
content1 = document.getElementById('content1'),
content2 = document.getElementById('content2');
if (menu)
menu.style.display="block";
if (content1)
content1.style.display="none";
if (content2)
content2.style.display="none";
}

jQuery load issue. Don't know how to approach this AJAX call

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

Unable to get a Hidden element in ASP.NET 4 from Javascript

I need help to find a hidden button in Javascript. I am using ASP.NET 4.
I can find a "visible = True" but when i try to find a hidden element it says object not found
<script type="text/javascript">
function ShowAge()
{
var elem = document.getElementById('MainContent_chbFilter');
if (elem != null)
alert("Found 1");
else
alert("Not Found 1");
var elemc = document.getElementById('MainContent_txtMSISDN');
if (elemc != null)
alert("Found 4");
else
alert("Not Found 4");
}
</script>
I am using asp:content
Please help
In ASP.NET when you hide an element it is not rendered in the HTML at all. This is in contrast to using the hidden property in CSS, where the element is still there, just visually hidden. If you want to "hide" it server-side, but still make it available in the DOM, you should add style="display:none;" in your ASPX.
If an element has been hidden serverside (I'm assuming this is what you've done), this means that it won't get rendered onto the page, which is why Javascript won't find it in the DOM.
What you want is to assign it a CSS class (.hidden, for example) with display:none. You can then revert it back to display:block through Javascript.
If you're setting Visible=False to an element in the server-side code than it won't render to the page, so the JavaScript won't be able to access it.

Categories