If div text equals certain text do something? - javascript

Cannot for the life of me get this to work. Even when removing the AJAX POST function, it still doesn't work. There is no alert or anything. Here is the JSFiddle and code:
HTML
<div class="notification">
<div class="title gooddog">test</div>
<div class="reason helvetica"></div>
</div>
<script>
var interval = setInterval(function(){
var Winner = $(".notification .title gooddog").text();
if(Winner == "test") {
$.ajax({
url: "Won.php",
type: "POST",
data: { Winner : Winner }
})
.success(function(data) {
console.log('foo', data);
});
}
},1000);
</script>
It is meant to trigger/check the div text for changes every 1 seconds, but as you can see, it's doing nothing..

var Winner = $(".notification .title gooddog").text();
should be
var Winner = $(".notification .title.gooddog").text();
jsfiddle http://jsfiddle.net/abwp5u21/8/

You've got several issues...
You are using jQuery syntax but you are not including the jQuery plugin...at least not in the fiddle
Not an issue in this case, but if you want to get whatever is inside a div use the html function rather than the text function
As #Cattla pointed out in her answer to the proper "multi-class" selector is .title.gooddog
I wouldn't be surprised if you had more issues on the server-side as well. Here's an updated JS Fiddler

Related

In a pinch, stuck in a simple onclick text cycle

For a project, I'm trying to highlight the logical fallacy of circular reasoning and have precious few lines of code later to be inserted into a separate webpage.
I am trying to create a simple process of clicking the displayed text to switch back and forth between the two questions. I've tried buttons and it only complicates and make no progress. Half a day gone, still banging my head on desk, as the phrase goes.
I read elsewhere that creating a var tracker facilitates, though I see it only for images, rather than displayed text. It feels like approaching my wits end, but I lack the time to walk away and try again.
This is my code thus far:
<!doctype html>
<head>
<script>
function change() {
var paragraph = document.getElementById("whytrust");
paragraph.innerHTML="I am trustworthy, but how can you be sure?";
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
You need some place to hold the old message so you can put it back again after you toggle the contents.
<!doctype html>
<head>
<script>
var newMsg = "I am trustworthy, but how can you be sure?";
function change() {
var paragraph = document.getElementById("whytrust");
var oldMsg = paragraph.innerHTML;
paragraph.innerHTML = newMsg;
newMsg = oldMsg;
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
This a quick and dirty implementation of what you want. I added a data-textindex attribute to the html element. There I stored an index for the currently shown text. In the javascript I check the current value, update data-textindex and replace it with new text.
function change() {
let paragraph = document.getElementById("whytrust");
let currentlyshown = paragraph.getAttribute('data-textindex');
if(currentlyshown == 0){
paragraph.innerText="I am trustworthy, but how can you be sure?";
paragraph.setAttribute('data-textindex', '1');
}else if(currentlyshown == 1){
paragraph.innerText="You can trust me, but how can you be sure?";
paragraph.setAttribute('data-textindex', '0');
}
}
<p id="whytrust" data-textindex="0" onclick="change();">You can trust me, but how can you be sure?</p>
On a sidenote: You can improve this code a lot. Like storing your text in a json-object. Or maybe using the ternary operator if you are 100% sure there will always be 2 choices. maybe give the function some arguments so you can apply it in a more general scenario.
Try tracking some sort of 'state' for your paragraph -- be it on/off, active/inactive...
Each time the change() function gets called, it doesn't remember what the paragraph was or was supposed to be. So, by setting a state of some sort (in my example a data-state attribute assigned to the paragraph element) the code can know how to behave.
function change() {
var paragraph = document.getElementById("whytrust");
var output = '';
// data-* can be anything, but handy for referencing things
var state = paragraph.getAttribute('data-state');
// check if data-state even exists
if( !state ){
// set it to the default/original state
paragraph.setAttribute('data-state', 'inactive');
state = 'inactive';
}
// toggle the state
// and assign the new text
if( state === 'inactive' ){
paragraph.setAttribute('data-state', 'active' );
output = "I am trustworthy, but how can you be sure?";
}else{
paragraph.setAttribute('data-state', 'inactive');
output = "You can trust me, but how can you be sure?";
}
paragraph.innerHTML = output;
}
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
Another option, without tracking state could be hiding and showing the paragraph you want displayed. You don't really need to track state or save the alternating text...
// get the elements from the DOM that you want to hide/show
// you can get tricky and add alternative ways to track
// the paragraph elements, but this works nice for a demo
const whytrust = document.getElementById('whytrust'),
answer = document.getElementById('whytrust-answer');
function change( element ){
// the element parameter being passed is the paragraph tag
// that is present/visible
if( element.id === 'whytrust' ){
answer.className = ''; // clear the .hide class
whytrust.className = 'hide'; // add the .hide class
}else{
whytrust.className = ''; // clear the .hide class
answer.className = 'hide'; // add the .hide class
}
}
.hide{ display: none; }
<p id="whytrust" onclick="change(this);">I am trustworthy, but how can you be sure?"</p>
<p id="whytrust-answer" class="hide" onclick="change(this);">You can trust me, but how can you be sure?</p>
What I like about this solution is that it keeps the content in the HTML and the JavaScript just worries about what to hide/show.

Get the data-url correctly using javascript function

I am creating a delete comment function and
this are the pieces of html for a delete comment functionality.
<div id="comment-area">
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/12/6">
x
</small>
</div>
<div class="list-border">
<small class="mdl-button delete-comment js-delete-comment pull-right" data-url="http://myproject.com/comment_controller/delete_comment/13/6">
x
</small>
</div>
</div>
And this is the function for delete a comment, which is automatically loaded when document is ready,
function delete_comment () {
$('.delete-comment').click( function (e) {
var url = $('.delete-comment').attr('data-url');
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (data) {
$('#comment-area').html(data.comments);
delete_comment();
},
error: function () {
alert('error');
}
});
});
}
The problem with this function from the given html above, if I'm going to click on .delete-comment with
data-url="http://myproject.com/comment_controller/delete_comment/13/6" take note on this "13/6", the javascript function delete_comment(),
in this line
var url = $('.delete-comment').attr('data-url');
chose to get the data-url="http://myproject.com/comment_controller/delete_comment/12/6" take note also this "12/6", to see the difference, instead of the data-url of .delete-comment I clicked.
In short, this function always chose the first-child div small, whatever small.delete-comment I'm going to click.
What was the best solution for this?
Try
var url = $(this).attr('data-url');
You are getting the attribue value by className and multiple elements have same class so the attribute value for first element found in dom is being returned.
So you need to get the value of element which is clicked and you can use this to get the value of clicked element.
A more robust way to approach this would be to use the jQuery .data() function.
var url = $(this).data('url');
This will pick up any dynamically added/updated url that may have changed via JavaScript, but not updated in the DOM attribute.

How to show and hide an image properly in javascript?

I've been having issues trying to show and hide images inside of my ajax request function. In order to be clear of what I'm trying to do, I make a video less than 1 minute click here. If you see in the web console, there's a variable that is changing from "ocupado" to "libre" and that means if there's a free or busy parking space. So It kind of work because in the beginning my variable "data" = ocupado shows a car image, then when it changes to "data" = libre hide the car image. The problem starts when it changes again to "data" = ocupadobecause It doesn't show any car image.
Here's my code for ajax function
<script src="js/jQuery.js"></script>
<script type="text/javascript">
setInterval(function(){
$("img").error(function () {
$(this).unbind("error").attr("src", "");
});
$(function ()
{
$.ajax({
url: 'api.php',
data: "",
success: function(data)
{
console.log(data);
if (data === "libre"){
$("#slave1free").hide();
$("#slave1busy").hide();
}else{
$("slave1free").show();
$("slave1busy").show();
}
}
});
})
}, 1000);
<div class="chart">
<div class="chartimage"><img src="images/parkinglot.jpg"></div>
<div class="image" id = "esclavo1">
<div class "free" id = "slave1free"><img src="images/carfree.png"></div>qQ
<div class "busy" id = "slave1busy"><img src="images/carbusy.png"></div>
</div>
By the way, carfree.png and carbusy.png are those images that are shown in the video next to "estacionamiento libre" and "estacionamiento ocupado". I put one image in top of the other because I was planning to show and hide both images according to value of data ("libre" or "ocupado").
Edit: Yes, I'm hidding both and showing both on purpose because I wanted to see where's the problem. Despite that both are showing or hidding at the same time, It would appear both images(one in top of the other) when "data"=ocupado ?
note that you are hiding the two items, or showing them at the same time... shouldn't be one of each?
if (data === "libre") {
$("#slave1free").show();
$("#slave1busy").hide();
} else{
$("slave1free").hide();
$("slave1busy").show();
}
-edit-
Just realized that you are missing the id selector ( # ) on the else
if (data === "libre") {
$("#slave1free").show();
$("#slave1busy").hide();
} else{
$("#slave1free").hide();
$("#slave1busy").show();
}

jquery textarea does not updates its value

I have site with some columns on it and theese columns can be editet by a textarea, if the column you want to edit have some content, that old content will be put into the textarea. Then on the save button is stores the value of that text area into a variable, if i alert this variable it alerts the same value as the old content.
The idea is biscally this: FIDDLE
Where the textarea updates a div and when you hit save and get the content in the div when you hit edit. This simple works as it should, but I'm having trupple with my code, and i cant find the error. And there is no error in the console aswell.
The differense on the exmaple i made and the place of my problem is that i use an ajax call to get the old content.
First here is what happens on the edit click:
$('body').on('click', '.edit_column', function() {
column_to_edit = $(this).parent().parent().attr('id');
current_step = "edit";
$.ajax({
url: 'pageEditor_ajax.php',
dataType: 'json',
async: false,
type: 'post',
data: {
item_id: column_to_edit,
mode: "edit_item"
}, success:function(s) {
element_type = s.type;
old_content = s.content;
}, error:function(e) {
alert('Error!');
}
});
if(element_type == 'text') {
$('.input_type').html('<textarea class="dialog_editor element_content"></textarea>');
}
$('.element_content').val(old_content);
$('.column_tool_dialog').css('display', 'block');
$('#edit_column_dialog').css('display', 'block');
$('#edit_column_dialog').animate({
left: "-=300px",
opacity: "1"
},500);
});
First i find the id of the column i want to edit so I'm shure that im editing the right column i the database.
The current_step variable is only for the looks, have some different dialog boxes.
The i make my ajax call that returns with success.
Then i have an if statement to check what type of column it is, i have 3 types, the two others is image and headline, havn't startet on them yet because this is not working yet.
The if statement should just build the inputs need to edit that type of column.
After the input fields a build it put the old_content into the textarea, this works fine too. The last few line is just for the looks agen to animate to the next dialog box. So my edit step works (I think).
Then you see the textarea, and i have the old content in it. When you click the save button, this happens:
$('#element_edit_button').click(function(e) {
e.preventDefault();
new_content = $('.element_content').val();
alert(new_content);
$.ajax({
url: 'pageEditor_ajax.php',
dataType: 'json',
async: false,
type: 'post',
data: {
item_id: column_to_edit,
item_content: new_content,
col_type: element_type,
mode: "save_item",
item_attr_alt_tag: alt_tag,
item_attr_title_tag: title_tag
}, success:function(s) {
}, error:function(e) {
alert('Der skete en fejl!');
}
});
$('li#'+column_id+' .preview_content').html(new_content);
$('li#'+column_id+' > div > small').html(new_content);
});
In this step i have a lot of things just for the looks, so i have excluded them this time. But the problem is fairly simple to explain here, the new_content variable is identic with the old_content? So all the places where is use the new_content the stuff dont get updated.
EDIT
Here is the html where it all happens:
<div id=\"edit_column_dialog\" class=\"column_tool_dialog_box\">
<div class=\"close\">x</div>
<h3>Rediger dit element</h3>
<form method=\"post\" id=\"save_element\">
<p class=\"error_message\"></p>
<div class=\"input_type\"></div>
<input id=\"element_edit_button\" class=\"green dialog_button\" type=\"submit\" value=\"Gem element\" />
</form>
</div>
</div>
Sorry for the long post, hope someone have an awnser.
As others have said, your jquery and even html could use some cleaning up. With that said, assuming I understand your question correctly, I think you're just missing a line in your #element_edit_button click event:
$('.element_content').val(new_content);
That should do the trick.

Variables for images

im trying to make a switch wich will change two images. I once solved ths, but then i lost some important files, the one containing the final script being one.
The idea is that when the button is clicked, it will change image 1 for image 2 and will change its own image from on to off. Then, when clicked again it will change image 2 for image 1 and its own image from off to on.
I been trying something like this, buts not working, not sure why. I think i got the wrong declaration for the if which determines if the switch is on or off, but again not sure.
Before you read the code and realize its poorly done, consider i dont know a thing about javascript, i only have a vague idea of how it works.
<script type="text/javascript">
var vswitch = false;
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
function change(){
if (vswitch == true){
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
} else {
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
}
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif">
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif" onclick='change();'>
</div>
</script>
Thank you
/////////////////////EDIT///////////////////////////
Thanks a lot.
Having those two functions there was a result of the previous code, i dont understand how i didnt realize it until you pointed out, heh. (Sleepyness maybe?)
#renuka, that code worked perfectly. I only changed the calling div, from the div "toggle" you created to the div "container" since the button has to switch the images itself, but other than that was sweet. Thanks.
Thanks for the help!
There are a couple of problems here :)
First:
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif")
^ this assigns a variable
You want to change = to === so that a comparison is done
Second, you're creating functions changelamp and changeSwitch but you're never actually calling them. I think you want to get rid of the function declarations completely:
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
} else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
Finally, there are some minor syntax errors such as missing semi-colons
vswitch = true; // <- like this
Please check the updated code below:
<script type="text/javascript">
function change(){
var vswitch = false;
if (document.getElementById("switchh").src == "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
</script>
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif"/>
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif"/>
</div>
<div id="toggle">
<input type="button" value="On/Off" onclick='change();'/>
</div>
The '=' assigns the value to the "src" of the image. Replace it with '==' for comparison.
Additionally from what jasonscript says, you are never switching the vswitch variable to the opposite state, so you'd need to add
vswitch = !vswitch;
after the if in the change() function, that way, the next time you click in the switch, it takes the "other" path through the if
Another point is that if you have the code layout as you have it in your post (script first and then the HTML code) the first if will actually not find the #switchh img, so you need to either move the if inside the change() function or move your script after the HTML
Major problem is that you are unnecessarily creating functions inside script which are never called.
No need for
changelamp() and changeSwitch()
You can directly post the code after the if condition check.
<script> tags should be closed. = assigns and === does comparison, and you need to change the value of vswitch.
Here is a fiddle that accomplishes what you're after with some random images

Categories