If Element ID exists then Hide Other Element - javascript

I have an ecommerce website that has multiple prices for a given item. I am trying to set up a bit of script that will hide a price, if the lower price class is present on the page.
<table>
<tbody>
<tr>
<td>
<font>
<div class="product_listprice">199.99</div>
</font>
<font>
<div class="product_productprice">179.99</div>
</font>
<b>
<div class="product_saleprice">159.99</div>
</b>
<font>
<div class="product_discountprice">139.99</div>
</font>
</td>
</tr>
</tbody>
</table>
Essentially what I need is a script that will hide .product_productprice if .product_saleprice exists on the page, and will hide both .product_saleprice and .product_productprice if .product_discountprice exists.
Here's what I've come up with so far with some google digging.
<script type="text/javascript">
$(document).ready(function(){
if ( $(".product_discountprice").size() )
$(".product_saleprice, .product_productprice").hide();
});
});
</script>
However, it doesn't seem to be working. Any ideas? I'm a jquery novice, so I'm sure there is a better way to do this out there...

// Essentially what I need is a script that will hide .product_productprice
// if .product_saleprice exists on the page...
if ($('.product_saleprice').length) {
$('.product_productprice').hide();
}
// ...and will hide both .product_saleprice and .product_productprice
// if .product_discountprice exists.
if ($('.product_discountprice').length ) {
$('.product_saleprice, .product_productprice').hide();
}
Update that adds a new class name, instead of hiding:
if ($('.product_saleprice').length) {
$('.product_productprice').addClass('some-class');
}
if ($('.product_discountprice').length ) {
$('.product_saleprice, .product_productprice').addClass('some-class');
}

http://jsfiddle.net/3481uqa4/1/
if ($(".product_discountprice").length) {
$(".product_productprice, .product_saleprice").hide();
} else if ($(".product_saleprice").length) {
$(".product_productprice").hide();
}
Will hide both product price and sale price if product_discountprice exists, else if sale price exist hide product price. If neither of them exists, show the product price.

Try this one.. Not sure if it is correct.
<script type="text/javascript">
$(document).ready(function(){
if($(".product_discountprice").length()){
$('.product_saleprice').hide();
$('.product_productprice').hide();
});
});
</script>

Related

JS onClick event ignores first click, works for every subsequent click

Having a very weird issue with a simple div visibility toggle script.
I'm just using javascript to switch a div between 'display: block' and 'display: none' to toggle its visibility. Very routine stuff.
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
No error output on console.
Relevant HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="res/classes.js"></script>
<script type="text/javascript" src="res/util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
</tr>
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Relevant CSS:
div.ovr {
display: none;
}
...and finally in util_c.js:
// toggle visibility of public tables list
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
First click: nothing happens.
Second click: the DIV is shown
Third click: the DIV is re-hidden
etc..
If I put an alert(listContainer.style.display) into the joinPublistToggle function, the alert comes up empty with the first click, then shows 'none' with the second click.
But the CSS specifically sets the display style for that div as 'none' on load. And if I look at that div in the page inspector after a fresh page load the inspector specifically says the div's display property is set to none.
So the issue seems to be that javascript is reading that property as empty even though that property is set as 'none'.
Why would it do that?
style returns the inline style of the element, and your element doesn't have any, which is why listContainer.style.display returns an empty string and the condition fails.
It would work if you compared against 'block' instead but it's not really more reliable.
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'block') {
listContainer.style.display = 'none';
} else {
listContainer.style.display = 'block';
}
}
https://stackoverflow.com/questions/69213611/js-onclick-event-ignores-first-click-works-for-every-subsequent-click/69224191#
The other answers provide valid solutions, here is another using classes:
CSS:
div.hidden {
display: none;
}
HTML:
<div id="join_publist_container" class="ovr hidden">
(of course you can also just keep using ovr but I wasn't sure what that's for)
JS:
function joinPublistToggle() {
document.getElementById('join_publist_container').classList.toggle('hidden');
}
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
I am going to asume when you clicked the link, the checkbox and the table should go away. And when it is clicked again, the table and the checkbox should show. I modified your code and it works for me.
for your HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="classes.js"></script>
<script type="text/javascript" src="util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
<td>Starts</td> <!-- time left until game starts (or "started" if underway) -->
<td>Timer</td> <!-- time limit for turns (or "none") -->
<td>Min</td> <!-- min players to start the round (or '--' if already underway) -->
<td>Late</td> <!-- whether late joiners are allowed at the table -->
<td>AI</td> <!-- whether there are any AI players at the table (and if so, how many)
also colour denotes difficulty: green-easy / yellow-med / red-hard -->
</tr>
<!-- Generate list via js. Clicking any list entry joins -->
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Classes.js:
// ClientPrefs - client-side preferences
class ClientPrefs {
constructor() {
// JOIN GAME page settings
this.joinAlwaysShowPub = false;
}
joinAlwaysShowPub() { return joinAlwaysShowPub; }
joinAlwaysShowPubToggle() {
// toggle setting in memory
this.joinAlwaysShowPub = !this.joinAlwaysShowPub;
// update checkbox & label
document.getElementById('join_savePref').checked = this.joinAlwaysShowPub;
}
}
And finally your other script:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
Here are few reasons why your code might not work:
I think the problem is that you mistyped joinPublistToggle() to joinShowPubList.
Your div has a value of nothing for the display property. So, when JS looks at your div, well, the div is not set to none or block, I don't know how to handle it. After you clicked the link a second time, it sets the display in your JS code. So, it knows how to handle it.
Maybe add an display property to your a tag and set it to block so JS know what the property of the style is.
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()" style="display:block;">View Public Matches</a><br />
This doesn't really answer my question, but I've implemented a simple workaround by adding an OR statement into the JS function:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if ( (listContainer.style.display == 'none') ||
(listContainer.style.display == '' ) ) {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
This doesn't explain why it was behaving so odd, and it isn't a proper solution (as a proper solution would address the cause, not the symptom).
But it works.
I won't mark the post as solved just yet in case any wizards end up reading this and are able to explain why the problem occurred in the first place.

How can I create rows of data using jquery append()?

How can I make a new row of data using jquery? For example i have a div with an id "box" and I have two spans each with an id of "name" and "time".
How can I have jquery append to this box holding both name and time? I tried experimenting and tried this code, but didn't work.
$("#button").click(function(){
$("#box").append(
$("#name").text("username"),
$("#time").text("5:00pm")
);
)}
In this code, I expected the box to create a new row of data every time I click the button. So if I want 5 rows of data, I would just click the button 5 times.
IDs must be unique and you need new spans
$("#button").on("click",function() {
$("#box").append(
"<br><span>username</span> <span>5:00pm</span>"
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button type="button" id="button">Click</button>
<div id="box"></div>
With vars, you can use a template literal
var cnt=0,
data = [{ username: "John", time: "05:00pm" },
{ username: "Paul", time: "07:00pm" }];
$("#button").on("click", function() {
if (cnt < data.length) {
$("#box").append(
`<br><span class="user">${data[cnt].username}</span> <span class="time">${data[cnt++].time}</span>`
);
}
});
.user { color:green }
.time { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button type="button" id="button">Click</button>
<div id="box"></div>
this is how you must do :
$(document).ready(function() {
$('#button').click(function(){
$("#box").append('<br><span>username</span><span>5:00pm</span>')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
</div>
<a id="button">button</a>
Since ID must be unique as #mplungjan mentioned, assuming you have some css linked with them, i'll just give examples with a class instead of IDs
$("#button").click(function(){
$("#main").append(
$("<div>").addClass("box")
.append($("<span>").addClass("name").text("username"))
.append($("<span>").addClass("time").text("5:00PM"))
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
<button id="button">Click me</button>
As you can see, after using the syntax $("<div>") you can chain as you want like you would in jQuery. The main difference between this and what #mplungjan has shown is how dynamic you are planning to make these. If you are planning on expanding these divs and spans dynamically as you go you are better off using this. If not and you just want lesser syntax you could rather use his.

If HTML text equals value, onclick change

Okay, I have tried a few ways of doing this but nothing has worked. I am hoping someone here can tell me what I am doing wrong. Below is a step-by-step of what I am trying to achieve.
#info-NUMBER-btn displays Click to display more information.
#info-NUMBER CSS is set to display: none.
When #info-NUMBER-btn is clicked:
- Corresponding #info-NUMBER-btn displays Click to display less information.
- Corresponding #info-NUMBER CSS is set to display: inline-block.
/* Jquery */
$(document).ready(function() {
$("#info-1-btn").text("Click to display more information");
$("#info-2-btn").text("Click to display more information");
$("#info-3-btn").text("Click to display more information");
$("#info-4-btn").text("Click to display more information");
$("#info-5-btn").text("Click to display more information");
if($("#info-1-btn").text("Click to display more information")) {
$("#info-1-btn").click(function () {
$(this).text("Click to display less information");
$("#info-1").css("display", "inline-block");
});
} else if($("#info-1").text("Click to display less information")) {
$("#info-1-btn").click(function() {
$(this).text("Click to display more information");
$("#info-1").css("display", "none");
});
}
if($("#info-2-btn").text("Click to display more information")) {
$("#info-2-btn").click(function () {
$(this).text("Click to display less information");
$("#info-2").css("display", "inline-block");
});
} else {
$("#info-2-btn").click(function() {
$(this).text("Click to display more information");
$("#info-2").css("display", "none");
});
}
if($("#info-5-btn").text("Click to display more information")) {
$("#info-5-btn").click(function () {
$(this).text("Click to display less information");
$("#info-5").css("display", "inline-block");
});
} else {
$("#info-5-btn").click(function() {
$(this).text("Click to display more information");
$("#info-5").css("display", "none");
});
}
});
<!-- HTML -->
<div id="info-5" class="hire-equipment-more-information">
<table class="hire-equipment-more-information-table" cellpadding="15px">
<tr>
<th>Length:</th>
<th>Material:</th>
<th>HP:</th>
</tr>
<tr>
<td>7.5m</td>
<td>Aluminium</td>
<td>225</td>
</tr>
</table>
</div>
<br />
<a id="info-5-btn" class="hire-equipment-item-link"></a>
You could make it a lot more easy for yourself, by binding not to the element id's, but to use your class hire-equipment.
This way you don't have to bind to 5 different buttons that in essence do the same thing.
Once you hit the eventHandler, you can use the first argument of the function, to check from which button you are coming and take the appropriate action.
As an example, I just created the 5 elements, and 1 event handler.
The $(selector).click() will bind to all elements sharing the selector ( in my case hire-equipment), and then, it will check from which button it's coming, select the parent node (the div surrounding the button, title and description), search the description element, and toggle it's hidden class. The buttons text will then change depending on it's text.
It's not fully how your example is built, but it's an example of making your event handlers a bit more generic.
$('.hire-equipment').click(function(event) {
var sourceElement = $(event.target);
$(sourceElement).parent().find('.description').toggleClass('hidden');
if ($(sourceElement).text() === 'Show more information') {
$(sourceElement).text('Show less information');
} else {
$(sourceElement).text('Show more information');
}
});
.hidden {
display: none;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="title">Title of item</p>
<div class="description hidden">This is a description</div>
<button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
<p class="title">Title of item</p>
<div class="description hidden">This is a description</div>
<button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
<p class="title">Title of item</p>
<div class="description hidden">This is a description</div>
<button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
<p class="title">Title of item</p>
<div class="description hidden">This is a description</div>
<button type="button" class="hire-equipment">Show more information</button>
</div>
Lets examine this line of code
if($("#info-1-btn").text("Click to display more information")) {
This should be:
if($("#info-1-btn").text() === "Click to display more information")) {
The text function is an overloaded function. If you pass in no value, it will return you the text inside the element.
If you pass in a value, it will modify the text, and return the jQuery object again (which will be a truthy value).
Now lets look at your overall logic.
Your code is testing the state of the buttons once, when the document loads. It should be testing the state of the button as part of the click handler.
See this complete code example: http://plnkr.co/edit/HLsLcKrRY3OqK6w44bXp?p=preview
It might not match your requirements exactly, but it demonstrates how you test the state of the button inside a click handler.
It also demonstrates how you can use a custom attribute (in this case, data-target) to link a button to a div block.
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<button class="toggleButton" data-target="buttonOneInfo"></button>
<br />
<div class="toggleTarget" id="buttonOneInfo">
Here's some information about the first item
</div>
<button class="toggleButton" data-target="buttonTwoInfo"></button>
<br />
<div class="toggleTarget" id="buttonTwoInfo">
Here's some information about the second item
</div>
<button class="toggleButton" data-target="buttonThreeInfo"></button>
<br />
<div class="toggleTarget" id="buttonThreeInfo">
Here's some information about the third item
</div>
</body>
<script type="text/javascript">
$(function() {
$('.toggleTarget').hide();
$(".toggleButton")
.text("Click to display more information")
.click(function() {
var toggleTargetId = $(this).attr('data-target');
var toggleTarget = $(document.getElementById(toggleTargetId));
if ($(this).text() === 'Click to display more information') {
$(this).text('Click to display less information');
toggleTarget.show();
} else {
$(this).text('Click to display more information');
toggleTarget.hide();
}
});
});
</script>
</html>
Trimmed the fat off of OP's jQuery. The following procedure is roughly outlined here:
Primary method used is toggleClass()
At least 2 classes are required to indicate a state of .info-btn
The big advantage of using classes is that you can add more styles to each class that would enhance .info-btn's state. ex. color, background-color
Further details are commented in the source of the Snippet below:
SNIPPET
/* jQuery */
// Alternate styntax for $(document).ready(
$(function() {
// Click on ANYTHING with the class .info-btn
$(".info-btn").on("click", function(e) {
// Prevent .info-btn from jumping when clicked
e.preventDefault();
/* `this` or .info-btn will toggle between the
| classes of .more and .less
| See CSS for details of expected behavior of
| .info-btn in both states
*/
$(this).toggleClass('more less');
});
});
.info-btn {
cursor: pointer;
}
/* Both classes use the :after pseudo-selector
| The value of content will complete the
| string: "Click to display"...
*/
a.more:after {
content: ' more information';
}
a.less:after {
content: ' less information';
}
button.less:before {
content: 'less ';
}
button.less:after {
content: ' more';
}
button.more:before {
content: 'more ';
}
button.more:after {
content: ' less';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- HTML -->
<div id="info-5" class="rental-info">
<table class="rental-info-table" cellpadding="15px">
<tr>
<th>Length:</th>
<th>Material:</th>
<th>HP:</th>
</tr>
<tr>
<td>7.5m</td>
<td>Aluminium</td>
<td>225</td>
</tr>
</table>
</div>
<br />
<a class="info-btn rental-link more">Click to display</a>
<br/>
<button class='info-btn less'>is</button>
<br/>

iframe doesn't getting hidden using JQuery

In my page I have a div with another div and an iframe as shown below.
<div class="v_dissc_tab" id="tabs-1">
<div id="publicevent">
<div class="crtraone" style="margin-left:800px;">
<button onclick="addpublic()">Add New</button>
</div>
<div>
<table width="100%">
<tr>
<td><b>Programme</b></td>
<td><b>Scheduled Start Time</b></td>
<td><b>Scheduled End Time</b></td>
<td><b>Amount</b></td>
<td><b>Status</b></td>
<td></td>
</tr>
<tr>
<?php if($publicnum>0)
{
}
else
{ ?>
<td colspan=6>
<?php echo "No any public channel programmes";?>
</td>
<?php }?>
</tr>
</table>
</div>
</div>
<iframe id="calendarframe" style="width: 100%;height:600px;display:none;" src="<?php echo base_url()?>index.php/channel/viewbookings">
</iframe>
</div>
On page loading, the div with id publicevent will be shown and the iframe is hidden. When I click on Add New button, the iframe will be loaded. Inside iframe I am loading another page which contains a button
<button onclick="managepublic()">Manage Public Events</button>
On clicking this button, I want to show the div with id publicevent and want to hide the iframe (as when the page is firstly loaded). Shown below is managepublic().
function managepublic()
{
location.reload(); // not making any changes
//$('#publicevent').show(); Tried with this also
//$('#calendarframe').hide();
}
Can anyone help me to solve this. Thanks in advance.
dont' use location.reload ,use only following code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
function managepublic()
{
$('#publicevent').show();
$('#calendarframe').hide();
}
On clicking this button, I want to show the div with id publicevent
and want to hide the iframe (as when the page is firstly loaded).
Check if this helps.
$('iframe').attr( "src", "http://www.apple.com/");
$('iframe').load(function() {
$('iframe').show()
$('#loaded').hide();
});
$('#button').click(function() {
$('#loaded').show();
$('iframe').hide();
});
JSFiddle
Try the following code snippet.
You are referring elements of <iframe>'s parent.
function managepublic(){
$('#calendarframe', window.parent.document).hide(250, function() {
$('#publicevent', window.parent.document).show();
});
}
Or
function managepublic(){
window.parent.$('#calendarframe').hide(250, function() {
window.parent.$('#publicevent').show();
});
}
Or Change the order of the hide events.
function managepublic(){
window.parent.$('#publicevent').show();
window.parent.$('#calendarframe').hide();
}
Note :
For this to work, parent must have jQuery included.
It won't work if parent is in different domain.

jquery .attr("alt")=='name'

Can anybody help me letting me know what is wrong with the following code?
$(document).ready(function(){
$("img").attr("alt")=='minimize'.click(function(){
alert("he");
});
});
thanks.
Addition:
Sorry guys, I am trying to add an event to a image inside of a table, so when its clicked it collapse the div under need.
I am facing several problems here.
1.- all tables and div use the same class.
2.- it may be a minimum of two tables and divs.
3.- first table should no be click able, only its images (for show and hide div under)
4.- rest of tables should be click able the whole table to show and hide div under with slidetoggle.
5.- rest of tables also have two images for show with slideDown and slideUp.
What I have it works but not fully.
Once again.
Thanks.
so far this is what I have.
<script type="text/javascript">
$(document).ready(function(){
$(".heading:not(#Container1)").click(function(){
var c = $(this).next(".container");
c.slideToggle("slow");
});
});
$(document).ready(function(){
$("img[alt='min']").click(function(){
var c = $(this).next(".container");
c.slideToggle("slow");
});
$("img[alt='max']").click(function(){
var c = $(this).next(".container");
c.slideToggle("slow");
});
});
</script>
<html>
<head></head>
<body>
<table class="heading" id="container1">
<tr>
<td>heading1</td>
<td><img alt='min'/><img alt='max'/></td>
</tr>
</table>
<div class='container'>Container1</div>
<table class="heading">
<tr>
<td>heading2</td>
<td><img alt='min'/><img alt='max'/></td>
</tr>
</table>
<div class='container'>Container2</div>
<table class="heading">
<tr>
<td>heading3</td>
<td><img alt='min'/><img alt='max'/></td>
</tr>
</table>
<div class='container'>Container3</div>
</body>
</html>
You need to use the attribute selector not get the attribute and compare it.
$(document).ready(function(){
$("img[alt='minimize']").click(function(){
alert("he");
});
});
$(document).ready(function(){
$("img[alt='minimize']").click(function(){
alert("he");
});
});
EDIT
$(function() {
$('img[alt='min'], img[alt='max']').click(function() {
var container = $(this).parent('table').next('div.container');
if ( $(this).attr('alt') == 'min' )
container.slideUp('slow');
if ( $(this).attr('alt') == 'max' )
container.slideDown('slow');
return false;
});
$('table.heading:not(:first)').click(function() {
$(this).next('div.container').slideToggle('slow');
return false;
});
});
The alt attribute is not a way to filter your images. It is designed to put alternative content for when the image cannot be displayed (not found, unwanted by user, no screen, etc.)
You should instead use the class attribute to discriminate your images the way you want.
Your code then becomes:
HTML
<img src="..." class="minimize" alt="A beautiful image">
Javascript
$(document).ready(function(){
$("img.minimize").click(function(){
alert("he");
});
});
It is not syntactically correct. What are you trying to do? Maybe this?
$(document).ready(function(){
$("img[alt=minimize]").click(function(){
alert("he");
});
});

Categories