alerts in else statements - javascript

Why won't this code work correctly? If someone selects something with an id of of '1599' then an alert will show "$1,599.00". If the id does not match, then the alert should show "$1,499.00". But it doesn't. Could someone help me figure this out?
thanks
<html>
<script type="text/javascript">
function showPrice(){
var a = document.getElementById();
if (a == "1599"){
alert("$1,599.00");
}
else {
alert("$1,499.00");
}
}
<body>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice()" />
<p class="price" id="1599">$1,599.00</p>
</div>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice()" />
<p class="price" id="1499">$1,499.00</p>
</div>
</div>
</body>
</html>

You need to let showPrice know which element you want to show the alert for. Right now, you're not actually selecting anything with the document.getElementById (a will be either null or undefined at this point).
There are a bunch of different ways to go about doing this, but to keep it close to your current implementation, I might do something like this:
HTML
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice(1599)" />
<p class="price" id="1599">$1,599.00</p>
</div>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice(1499)" />
<p class="price" id="1499">$1,499.00</p>
</div>
</div>
Javascript
function showPrice(a){
if (a == "1599"){
alert("$1,599.00");
}
else {
alert("$1,499.00");
}
return false;
}
Fiddle here

I think you will see the issue if you add an
alert(a);
before the if(...) -- My guess is that you aren't getting the value you expect in there.

The document.getElementById() method takes a parameter of the ID to look for. Something like:
document.getElementById("1599")
and will return the document element that has that ID. Not sure what it will return when no parameter is passed.

Related

Javascript, GetElementById element is not defined? [duplicate]

This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 1 year ago.
For some reasons, I can't display #coupon with javascript, when i try to get elementById it displays the error message elementById undefined,
HTML
<html>
<head>
<title>Exercise</title>
<link rel="stylesheet" href="stylesheet.css">
<script src="javascript.js"></script>
</head>
<body>
<div class="inputi">
<p class="input-text">Une Jam?</p> <input placeholder="Sheno emrin..." type="text" id="inputId">
//checks input value
<button type="button" onclick="getInputValue()">Vazhdo</button>
// shows error message if it doesn't match the array
<p id="message"></p>
</div>
// i want to display this with javascript, after the login
<h1 id="coupon">You won giftcard </strong></h1>
<button id="coupon">abas</button>
</body>
</html>
JS ( the problem )
**
the problem getElementById is undefined, I want to display:block after the successful login attempt.
**
var zzz = getElementById("coupon")
if(zzz === "none") {
display:block; }
// document.writeln("<h1>Keni fituar kupon 50% ne <strong> Green & Protein </strong> </h1>");
// document.writeln('<input class="giftcode" placeholder="' +finalcode+'" type="text" id="inputId">');
display_image(images[z], 400, 400, 'Javascript');
document.write('<br>' + user[i]);
}
}
}
Two things:
getElementById should be document.getElementById
you need to move your script tag to the bottom of the body tag to ensure that the element is in the DOM when you select it
Use:
<html>
<head>
<title>Exercise</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<div class="inputi">
<p class="input-text">Une Jam?</p>
<input placeholder="Sheno emrin..." type="text" id="inputId">
//checks input value
<button type="button" onclick="getInputValue()">Vazhdo</button>
// shows error message if it doesn't match the array
<p id="message"></p>
</div>
// i want to display this with javascript, after the login
<h1 id="coupon">You won giftcard </h1>
<button id="coupon">abas</button>
<script src="javascript.js"></script>
</body>
</html>
From your code above it shows that you're trying to call a method getElementById() which you have not yet defined.
2ndly, you can only assign only 1 id in a document else it will not work.
you can do something like this
// i want to display this with javascript, after the login
<span id="coupon" style="display: none">
<h1>You won giftcard </strong></h1>
<button>abas</button>
</span>
what you meant to call is document.getElementById("coupon"); which is the right function to do.
so try this;
var zzz = document.getElementById("coupon");
i don't really know what your criteria is for a successful login but this show help
let say you set a variable as var success = "yes" on successful login
if(success === "yes"){
zzz.style.display = "block";
}
Call document.getElementById instead. Docs - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Try: document.getElementById
Instead of : getElementById
Because getElementById is a document method

How to show a new Button after Button was clicked?

Here is my problem. I want to create a questionnaire.
How are you? A)Button "Good" B)Button "Bad"
i.e. user click button B.)
Alert Window is shown and notifying user about his/her last choice.
New Question and Buttons appear on the same page. Essentially, users will go through the set of questions on the same page.
Why are you Bad? A)Button "Some Txt" B.)Button "Some Txt"
How can I show new question and new buttons on the same page. The concept should follow some kind of decision tree logic.
Solutions, advises or "where-to-check hints" appreciated. Please, help me!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
<script type="text/javascript">
function buttonclickgood() {
alert('you have clicked Good');
}
</script>
<script type="text/javascript">
function buttonclickbad() {
alert('you have clicked Bad');
}
</script>
</head>
<p>How are you?</p>
<input type="button" value="Good!" onclick="buttonclickgood()"/>
<input type="button" value="Bad!" onclick="buttonclickbad()"/>
<body>
</body>
</html>
You might want to explore JQuery a bit.
Particularly something around the .click() API
https://api.jquery.com/click/
Are you intending to do this just on the client side? I would recommend doing this through a client/server model thou e.g. Angular(Client) -> NodeJS(Server)
That is, having the question generation logic in node and let the client consume the questions however it is not impossible to do everything on the client.
So you code will be something like
<script src="../script/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
<!-- maybe let say define your data (questions) here -->
var data =
[
{
<!--example ... -->
}
]
$("#btn_1").click(function() {
<!-- do some logic with the data above. Process it then print the new question by update your text -->
$('#TxtArea').val(data);
});
</script>
You will need to use some javascript to hide/show your different steps. With JQuery for example you can do something like that:
<script type="text/javascript">
$(document).ready(function() {
$(".step").hide();
$(".step-1").show();
});
function buttonclick(nextStep)
{
$(".step").hide();
$(".step-"+nextStep).show();
}
</script>
<div class="step step-1">
<p> Question 1 </p>
<input type="button" class="button" value="Good!" onclick="buttonclick(2)"/>
<input type="button" class="button" value="Bad!" onclick="buttonclick(2)"/>
</div>
<div class="step step-2">
<p> Question 2 </p>
<input type="button" class="button" value="Good!" onclick="buttonclick(3)"/>
<input type="button" class="button" value="Bad!" onclick="buttonclick(3)"/>
</div>
<div class="step step-3">
<p> Question 3 </p>
<input type="button" class="button" value="Good!" onclick="buttonclick(1)"/>
<input type="button" class="button" value="Bad!" onclick="buttonclick(1)"/>
</div>
Don't forget to add the JQuery library to make it work. The function can also be replaced by .click from JQuery.
I hope this will help.
WORKING CODE FOR YOU . I have added 2 level question only ... you can add more questions.
Click for working demo
<div id="first">
<p id ="text">How are you?</p>
</div>
<input type="button" id="b1" value="Good!" />
<input type="button" id="b2" value="Bad!"/>
<script>
$("#b1").click(function(){
if($("#b1").val()=="Good!")
{
$("#text").text("Good To hear that ! Do you want to spread a smile ?");
$("#b1").val("Yes");
$("#b2").val("No");
}
});
$("#b2").click(function(){
if($("#b2").val()=="Bad!")
{
$("#text").text("Ohh Sad ! Do you want my help ?");
$("#b1").val("Yes");
$("#b2").val("No");
}
}); </script>
Click for working demo
I have done question changes for both button of question 1 only... rest you can add . Include the jquery file
In my solution buttons' texts are changed. A decision tree of object is followed.
<input type="button" id="left" value="good" onclick="buttonclick(this.value)"/>
<input type="button" id="right" value="bad" onclick="buttonclick(this.value)"/>
<script type="text/javascript">
decision_tree = {
'bad': {
'some A': 'done',
' some B' : 'done'
},
'good': {
'yes': {
'like':'done',
'dont like':'done'
},
'no':'done'
}
};
left = document.getElementById("left");
right = document.getElementById("right");
st = decision_tree;
function buttonclick(v) {
alert('you have clicked ' + v);
if(st[v] == 'done'){
alert('you are done with questionnaire');
left.style.visibility = 'hidden';
right.style.visibility = 'hidden';
} else{
console.log(st[v]);
left.setAttribute("value",Object.keys(st[v])[0]);
right.setAttribute("value",Object.keys(st[v])[1]);
st = st[v];
}
}
</script>

Hiding div that contains specific string

I've been trying to hide divs that contain particular string using the other solutions suggested on this site, however none worked (most likely due to my inexperience with jQuery)
I'd like to completely hide all divs that (in this example) contain the string 'zynthesized'
<div class="photos-wrapper" id="detailPhoto-977355202965894535_11842652">
<div class="pseudo">
zynthesized
</div>
<div class="image-wrapper">
<img src="https://scontent.cdninstagram.com/hphotos-xfp1/t51.2885-15/s150x150/e15/11195725_518243828313545_1133319712_n.jpg"></div>
<div class="activites">
<span class="popular_picto ss-star "></span>
<div class="album-relative detail-photo-album-977355202965894535_11842652" style="display: none;">
<input type="hidden" class="apalbumsPhoto" value="977355202965894535_11842652">
<input type="hidden" class="apalbumsPhoto-977355202965894535_11842652" value="">
</div>
<span class="nb_comment_score">0</span>
<span class="comment_picto ss-chat"></span>
<span class="nb_like_score">4</span>
</div>
<div class="nouveau-commentaire">
<textarea id="comment-977355202965894535_11842652" class="textareaCommentaire" placeholder="Your comment"></textarea>
<img src="http://static.iconosquare.com/images/loading.gif" class="commentLoading">
</div>
</div>
From what I've seen something like
$('.photos-wrapper:contains("zynthesized")').hide()
Should be closest to what I need, but I've had no luck with it.
Any help would be amazing!
Thanks for the help guys! Turns out that the script was working however as the page loaded new divs automatically when scrolling, the script had to be run after the page loaded them.
The final script looks like
$(window).load(function(){
$(".photos-wrapper:contains('zynthesized')").hide();
});
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150;
if(y_scroll_pos > scroll_pos_test) {
$(".photos-wrapper:contains('zynthesized')").hide();
}
});
Hopefully this helps anyone looking to do something similar!
You can simply use a regex.
<script>
var ptrn = /zynthesized/g;
$( "div" ).each(function( index ) {
if(ptrn.test($( this ).text())){
$( this ).hide();
}
});
</script>
Here is simple snippet : jsfiddle.net/dariubs/hgbm3doa

Jquery add class if a element exists within div

I want Jquery to add a class .pointer to .staff-container if <a href=""> exists within .staff-picture.
My Jquery:
if($('.staff-container').find('.staff-picture').closest('a').length) {
$(this).addClass('pointer');
}
No class is being added with the above jquery, what am I doing wrong?
My Css:
.pointer {
cursor:pointer !important;
}
My HTML:
<div class="teachers">
<div class="span12">
<div class="scroll transparent">
<div class="staff-outer-container">
<div class="staff-container">
<div class="staff">
<div class="staff-picture">
<img src="img/people/teachers/ahmed.png" />
</div>
<p><span class="bold">Mr. Ahmed</span><br />
Ext. 13417<br />
Room 417/323<br />
Ahmed#wcskids.net</p>
</div>
</div>
<div class="staff-container">
<div class="staff">
<div class="staff-picture">
<img src="img/people/teachers/aiello.png" />
</div>
<p><span class="bold">Mr. Aiello</span><br />
Ext. 13328<br />
Room 328/323<br />
ASusan#wcskids.net</p>
</div>
</div>
<div class="staff-container">
<div class="staff">
<div class="staff-picture">
<img src="img/people/teachers/aiosa.png" />
</div>
<p><span class="bold">Mr. Aiosa</span><br />
Ext. 13419<br />
Room 419/323<br />
BAiosa#wcskids.net</p>
</div>
</div>
</div>
</div>
</div>
</div>
You can do this :
$('.staff-picture a').closest('.staff-container').addClass('pointer');
I hope the logic is obvious from the code.
I would first iterate through the .staff-container divs, then use a conditional to determine which ones have an a tag using the this object as context:
//Goes through all the .staff-picture divs
$('.staff-container').each(function(){
//If the a tag exists within the current .staff-picture (returned object isn't undefined)
if($('a', this).html() != undefined){
//Add the class if a exists
$(this).addClass('pointer');
}
});
http://jsfiddle.net/y9ZKG/
EDIT
Sorry, I meant staff-container, not staff-picture. But, either will work.
2nd EDIT
Also, if you are curious why your original methodology wasn't working, it is because the conditional you use (the first if) does not instantiate the this object. That is, this does not exist inside your function.
Try this:
var $selector = $('.staff-container');
if($selector.find('.staff-picture').has('a')) {
$selector.addClass('pointer');
}
$.closest() traverses up not down the tree, therefore you are not finding anything. see the jQuery API
I like to approach these types of problems with "reverse" logic:
$('.staff-picture a').parent().parent().parent().addClass('pointer);
There's probably a way to "choose" your staff-container parent, but if the DOM structure doesn't change, this works great.
This starts by selecting all the a-links and then ONLY applies those up which uses jQuery's powerful selection code. It doesn't rely on tests with if-statements.

resize two elements simultaneously using jquery/js

i have been trying to resize two windows simultaneously but for some reason it doesnt work.
i tried to catch errors but nothing.
Note: i dont want to use jquery resize since it doesnt have a fast inteval for checking resizes
JAVASCRIPT:
function _u(e){
try {
e.parent('.boss').find('.first').width( e.width() ); //tried with parent('.boss').next('.first') or directy with prev('.first')
} catch(err){alert(err);}
}
$(document).ready(function(){
$(".data").each(function(){
var resizerint;
$(this).mousedown(function(){
try {
var eee = $(this);
var resizerint = setInterval(function(){
try {
_u( eee );
} catch(err){alert(err);}
},10); // i need it 10ms
} catch(err){alert(err);}
$('.test').html('<font style="position:absolute;top:0;right:0;color:red;"> mouse DOWN </font>');
}).mouseup(function(){
try{
clearInterval(resizerint);
} catch(err){alert(err);}
$('.test').html('<font style="position:absolute;top:0;right:0;color:green;"> mouse UP </font>');
});
});
});
and HTML:
<div class="boss">
<div class="first">
<table>
<tr>
<td>
<div class="title">ONEEEEE</div>
</td>
</tr>
</table>
</div>
<div class="second">
<textarea class="data" > ONEEE TEXTY TESTY NJAMMM! </textarea>
</div>
</div>
<div class="boss">
<div class="first">
<table>
<tr>
<td>
<div class="title">TWOOOOOO</div>
</td>
</tr>
</table>
</div>
<div class="second">
<textarea class="data" > TWOOO TEXTY TESTY NJAMMM! </textarea>
</div>
</div>
<div class="text"></div>
Thank you in advance for any help you can provide.
JSFIDDLE (IF YOU SEE , THE BLUE DOESNT RESIZE WHEN MOUSEDOWN at the TEXTAREA )
http://jsfiddle.net/2sfFW/
My first answer was that there was a missing "$" but it didn't fix the problem.
Got it working to some extent, but you have to click into the text field first before it will initialize. I used your blue version as a visualizer.
The proper jquery traversal is
e.parent().parent('.boss').find('.first')
or
e.parents('.boss').find('.first')
You have to use the plural version because there are two parent divs above it. Using parent().parent() is more specific but probably not necessary in this case.
http://jsfiddle.net/aQKVD/1/
If you remove the mouseup/mousedown handlers it will initialize at document.ready instead, which I think might be what you want. You don't necessarily need to do the clearing of the variable unless you have some other need for it, since .each() creates a separate instance of the function tied to the specific div in question. Here's a version like that:
http://jsfiddle.net/aQKVD/2/
Doesn't fix it in JSfiddle, but for starters you've left off a "$". I've set up a JSfiddle link so other people can try it. http://jsfiddle.net/aQKVD/
function _u(e){
try {
e.parent('.boss').find('.first').width( e.width() ); //tried with parent('.boss').next('.first') or directly with prev('.first')
} catch(err){alert(err);}
}
$(document).ready(function(){
(".data").each(function(){
last line should be
$(".data").each(function(){

Categories