Add class or style if text in div appears - javascript

i have this order form which i'm making.
Right now when someone put a coupon code I want to apply to the div of the old price a style or class (line-through) and i though I had it right...here is what i'm doing.....any suggestion why it might not be working? WARNING: I am really new to javascript....i've been working with CSS HTML but javascript is another story. Thanks!
if ($('#grand_amount_value').length > 1){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
}

Here is an example I threw together to show something like that working:
https://jsfiddle.net/pj6xwhcy/3/
function strikeOldAmt() {
var gav = $("#grand_amount_value");
if (gav.length > 0 && gav.text() != "" ){
// There is a GAV element and it is not empty, strike out the old amount!
$("#Total_Amount_old_val").css("text-decoration", "line-through");
}
}
Note: Using the "style" attribute would also wipe out any other custom styling you may have added. Using the css() function will not interfere if the style attribute is already set.

Assuming the page isn't reloading you could use a setInterval to check if the element exists.
var checkInterval = setInterval(function(){
if ($('#grand_amount_value').length){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
clearInterval(checkInterval);
}
},200);

Simplest clean way
$(document).on('change','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
or if you need continuous check
$(document).on('keypress','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
Here a jsfiddle

Related

Read more or read less, needs to be clicked twice to work [duplicate]

I want the visitor to be able to expand/collapse some sections, and am using:
<input onclick="return toggleDiv('xx')"
type="button"
class="button"
value="click here to expand/collapse"/>
and in the I have the function:
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
The first time a button is clicked it doesn't work, subsequent clicks (on any of the buttons) work OK.
There is related conversation here:
Button needs to be clicked twice to trigger function
but I don't understand the answer (too technical;-),
could someone help explain it please?
The initial style on your 'xx' div may be causing some trouble...
Explanation
Say you have a stylesheet rule configured to make your divs initially hidden. Something like:
div { display: none }
(...where of course the selector (div) will probably be a little bit less broad)
This would appear to work correctly, in that the page will load with all of your div elements hidden ("collapsed"). However, there's no actual value for the style.display property on the elements themselves - they're merely inheriting the value from the stylesheet. So in your code, the test you're using to check if the element is hidden:
if(e.style.display=="none"){
...will fail, incorrectly identifying the target as being visible, and causing the style.display property to be set to "none" (which has no visible effect, since the element had already been hidden by the stylesheet). Then the next time the button is clicked, the value you set the last time around will cause the text to succeed, and your routine will set style.display to "block".
The easy way to correct for this is to simply reverse your test and check for "block":
if(e.style.display=="block"){
e.style.display="none"
} else {
e.style.display="block"
}
...however, this will fall apart if you have some elements configured to be initially visible: you'll just run into the same problem in reverse, with the first button click failing to have any visible effect. For a more robust behavior, you'll need to test the style that's actually active on the element:
function getStyle(el, name)
{
// the way of the DOM
if ( document.defaultView && document.defaultView.getComputedStyle )
{
var style = document.defaultView.getComputedStyle(el, null);
if ( style )
return style[name];
}
// IE-specific
else if ( el.currentStyle )
return el.currentStyle[name];
return null;
}
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(getStyle(e, "display") == "none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
Here we use a helper function, getStyle(), to retrieve the active value in a cross-platform manner. See also: getComputedStyle(), currentStyle
more easy implémentation some how
var a=1;
function toggleDiv(xx){
var e=document.getElementById(xx);
if(a==1){
e.style.display="block";a=0;
} else {
e.style.display="none";
a=1;
}
}
To save all the extra Javascript code to get the style etc, a simple fix for this would be to add the hide CSS to the element itself.
<div class="yourclass" style="display:none;">content</div>
edit
I decided to explain my answer a little better. I'm assuming you didn't hide the div you wanted to toggle by default, so it was visible, however when calling e.style.display the result would not be none neither would it be block because the style hasn't been set yet.
Instead, you were retrieving an empty string which means the first time you clicked it, your else statement was firing; the div display was being set to none on first click, that way the next click would retrieve the value as none so of course would then change it to block.
The simple answer you're looking for is to add the display:none; to the inline style. This way, when you look at
if (x.style.display == 'none')
it will return true!
I know this is an old thread, but for the sake of being somewhat useful (for a change), you could always call the current display within the function. alternatively you could define on-load, but given the button might not be clicked, I would prefer to do via a addEventListener().
document.getElementById("someID1").addEventListener("click", hideOpen);
function hideOpen() {
var x = document.getElementById("someID2");
x.style.display = window.getComputedStyle(document.getElementById("someID2")).display;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Effectively you load the JS, then when an element is clicked (someID1), the function will define varible X, assign the current computed style.display and then test the if it's block or none.
Something like this might work for you. But put it in the head of the document. the window onload function is important because the DOM needs to be loaded before you can mess around with the input field
<input id="divOpener" rel="xx" type="button" class="button" value="click here to expand/collapse"/>
and this
window.onload = function(){
// get input field from html
var myInput = document.getElementById('divOpener');
// add onclick handler
myInput.onclick = function(){
// if you really need to say which div in the document body, you can
// add it to the rel or ref etc. attributes then get the value with
// get attribute
var myDiv = document.getElementById(this.getAttribute('rel'));
if(!myDiv) return;
if(myDiv.style.display=="none"){
myDiv.style.display="block";
} else {
myDiv.style.display="none";
}
}
}
Shog9's answer saved me from an evening's frustration. Thanks.
However there's a much simpler solution than the one he presents. The secret is simply to switch around the order of the conditional. i.e.
if(e.style.display == "block"){
e.style.display="none"
} else {
e.style.display="block"
}
The insight here is simply that the condition can fail for two different reasons: if the value is unobtainable it will do the right thing anyway.

load jquery function before content

i made this function:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
This hide a element if are empty.
But on page load, #tab-upsell_tab appear for 1 second (if need to be hide) and i don't like it.
There is a way to load this function before this element? Or something similiar.
Edit: i accept a css solution, but how?
You should set .upsell_tab_tab and #tab-upsell_tab to display: none in your CSS. Change your JavaScript to this also:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
jq111(".upsell_tab_tab").show();
jq111("#tab-upsell_tab").show();
}
This way your elements are hidden by default, and you must imperatively show them based on your logic.
Try using $.holdReady() , .ready()
$(window).load(function() {
var jq111 = jQuery.noConflict();
jq111.holdReady(true);
if (jq111("#tab-upsell_tab").find("div").length > 0) {
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
jq111.holdReady(false);
jq111(document).ready(function() {
// do stuff
})
})
div .length within "#tab-upsell_tab" not greater than 0
http://plnkr.co/edit/Xp2RbPe65BaFeobtTVOL?p=preview
div .length within "#tab-upsell_tab" greater than 0
http://plnkr.co/edit/ekSUelSinlM8baKQe74Y?p=preview
The DOM renders HTML, CSS, then JS. So if you want your HTML elements hidden then hide them with your CSS or you could create using a template system like mustache or in your JS code. I prefer creating them in your JS code. It makes your code cleaner and it lighter on the DOM.

Javascript Forms Select Selectedindex

Having problems with the following - Not working as expected, getting JS doc errors as well.
JSFiddle Nota Worka.
try this fiddle: http://jsfiddle.net/maniator/egjF4/6/
and change the if line to:
if (document.forms['myform'].selectbox1.selectedIndex == 2)
you need the == to check values
UPDATE
Based on your comments below here is the jQuery for the same thing:
$(function(){
$('#selectbox1').change(function(){
if(this.selectedIndex == 2){
$('#input1, #input2, #asterisk').css('visibility', 'visible');
$('#input2').addClass('required');
}
else {
$('input, #asterisk').css('visibility', 'hidden');
$('#input2').removeClass('required');
}
})
})
you could also do this, http://jsfiddle.net/edelman/egjF4/10/
var form = document.getElementById('myform');
if (form.selectbox1.selectedIndex == 2)
this way you're caching the form in case you want to reference it later, preventing another element lookup and speeding up your code.
I believe jsfiddle runs in it's own little protective XPC bubble, so showhidebtime will not be seen as defined via an inline javascript call. Best practice is to always add events in the javascript file, not inline with the elements.
Also you need to change your form to show name="myform" in order for document.myform to work.
Try this fiddle: http://jsfiddle.net/garreh/qb6fw/

Why does my button need to be clicked twice for the event handler to work the first time, but thereafter just once?

I want the visitor to be able to expand/collapse some sections, and am using:
<input onclick="return toggleDiv('xx')"
type="button"
class="button"
value="click here to expand/collapse"/>
and in the I have the function:
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
The first time a button is clicked it doesn't work, subsequent clicks (on any of the buttons) work OK.
There is related conversation here:
Button needs to be clicked twice to trigger function
but I don't understand the answer (too technical;-),
could someone help explain it please?
The initial style on your 'xx' div may be causing some trouble...
Explanation
Say you have a stylesheet rule configured to make your divs initially hidden. Something like:
div { display: none }
(...where of course the selector (div) will probably be a little bit less broad)
This would appear to work correctly, in that the page will load with all of your div elements hidden ("collapsed"). However, there's no actual value for the style.display property on the elements themselves - they're merely inheriting the value from the stylesheet. So in your code, the test you're using to check if the element is hidden:
if(e.style.display=="none"){
...will fail, incorrectly identifying the target as being visible, and causing the style.display property to be set to "none" (which has no visible effect, since the element had already been hidden by the stylesheet). Then the next time the button is clicked, the value you set the last time around will cause the text to succeed, and your routine will set style.display to "block".
The easy way to correct for this is to simply reverse your test and check for "block":
if(e.style.display=="block"){
e.style.display="none"
} else {
e.style.display="block"
}
...however, this will fall apart if you have some elements configured to be initially visible: you'll just run into the same problem in reverse, with the first button click failing to have any visible effect. For a more robust behavior, you'll need to test the style that's actually active on the element:
function getStyle(el, name)
{
// the way of the DOM
if ( document.defaultView && document.defaultView.getComputedStyle )
{
var style = document.defaultView.getComputedStyle(el, null);
if ( style )
return style[name];
}
// IE-specific
else if ( el.currentStyle )
return el.currentStyle[name];
return null;
}
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(getStyle(e, "display") == "none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
Here we use a helper function, getStyle(), to retrieve the active value in a cross-platform manner. See also: getComputedStyle(), currentStyle
more easy implémentation some how
var a=1;
function toggleDiv(xx){
var e=document.getElementById(xx);
if(a==1){
e.style.display="block";a=0;
} else {
e.style.display="none";
a=1;
}
}
To save all the extra Javascript code to get the style etc, a simple fix for this would be to add the hide CSS to the element itself.
<div class="yourclass" style="display:none;">content</div>
edit
I decided to explain my answer a little better. I'm assuming you didn't hide the div you wanted to toggle by default, so it was visible, however when calling e.style.display the result would not be none neither would it be block because the style hasn't been set yet.
Instead, you were retrieving an empty string which means the first time you clicked it, your else statement was firing; the div display was being set to none on first click, that way the next click would retrieve the value as none so of course would then change it to block.
The simple answer you're looking for is to add the display:none; to the inline style. This way, when you look at
if (x.style.display == 'none')
it will return true!
I know this is an old thread, but for the sake of being somewhat useful (for a change), you could always call the current display within the function. alternatively you could define on-load, but given the button might not be clicked, I would prefer to do via a addEventListener().
document.getElementById("someID1").addEventListener("click", hideOpen);
function hideOpen() {
var x = document.getElementById("someID2");
x.style.display = window.getComputedStyle(document.getElementById("someID2")).display;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Effectively you load the JS, then when an element is clicked (someID1), the function will define varible X, assign the current computed style.display and then test the if it's block or none.
Something like this might work for you. But put it in the head of the document. the window onload function is important because the DOM needs to be loaded before you can mess around with the input field
<input id="divOpener" rel="xx" type="button" class="button" value="click here to expand/collapse"/>
and this
window.onload = function(){
// get input field from html
var myInput = document.getElementById('divOpener');
// add onclick handler
myInput.onclick = function(){
// if you really need to say which div in the document body, you can
// add it to the rel or ref etc. attributes then get the value with
// get attribute
var myDiv = document.getElementById(this.getAttribute('rel'));
if(!myDiv) return;
if(myDiv.style.display=="none"){
myDiv.style.display="block";
} else {
myDiv.style.display="none";
}
}
}
Shog9's answer saved me from an evening's frustration. Thanks.
However there's a much simpler solution than the one he presents. The secret is simply to switch around the order of the conditional. i.e.
if(e.style.display == "block"){
e.style.display="none"
} else {
e.style.display="block"
}
The insight here is simply that the condition can fail for two different reasons: if the value is unobtainable it will do the right thing anyway.

Using Jquery to slowly hide a div

I'm trying to make some code which finds if a div exists, and if it does then have it fade away slowly. I have this to determine whether or not the div exists
if($('#error').length != 0)
{
$('#error').hide(500);
}
And that does work but only on a refresh, I've been attempting to put it in a timer like this:
var refreshId = setInterval(function()
{
if($('#error').length != 0)
{
$('#error').hide(500);
}
}, 500);
But its not getting rid of the innerHTML! I have some code which on hover alters the innerHTML of the error div so I can fill it up, but for some reason this isn't working, any advice would help!
Thank you!
$("#error").fadeOut(500);
Update:
If you are looking to check for existence:
var msg = $("#error");
if(msg.length) {
msg.fadeOut(500);
}
If you want to empty it:
$("#error").empty();
If you just want to delay 500ms then fade out, do this:
$("#error").delay(500).fadeOut();
To also empty the element, provide a callback to .fadeOut() like this:
$("#error").delay(500).fadeOut(function() {
$(this).html('');
});
There's no need to check .length, if an element that matches the selector isn't present, nothing happens :)
The div you're trying to hide likely hasn't loaded by the time your script runs. Try this; it will defer execution until the DOM is loaded:
$(document).ready(function() {
// put your code here
});
This is a good practice when using jQuery anyway.
Reference: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Categories

Resources