Jquery if div doesn't exist - javascript

I'm using 1 js for 2 different pages. 1 page doesn't have a div which the other does. So when I submit the values, I get a $( js error
for
$('.description'+save_id+'').html(description_val).show(); //update category description
I suspect that I get the error because there is nothing to show(). Is there a short code I can use to detect if the div.description exists otherwise don't do the function?

jQuery will not error if it has nothing to perform on. The show() would not be a problem. To answer your question, though, you can check the length property on the jQuery object returned from $.

If the description_val variable is undefined, then the code will fail.
Try using an if() statement to only run the code if description_val is not undefined.
if(description_val) {
$('.description'+save_id+'').html(description_val).show();
}
Or if for some reason the value of description_val may be a value that would equate to false, then do this:
if(description_val !== undefined) {
$('.description'+save_id+'').html(description_val).show();
}

From what you posted I'd check to make sure the variables you're using are all defined at this stage. To check for existence you can do this:
if ($('.description' + save_id).size() > 0) {
// code here that operates on the div.
}
This is essentially just a syntactic alternative to checking the length property.

Related

Copy value from one text field to another when button clicked

I am trying to get one field to copy over to another field when a div is clicked on, and the code that I have currently is not working. It's showing '0' in field1, even though field2 is set to 1 by default.
$(document).on('click', '#button', function() {
$('#textfield1').val === "document.getElementById('#textfield2').value";
Try with:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val())
});
You're using an odd mix of JS and jQuery here.
Your main issue is that val() is a method, not a property. Therefore your code should look something like this:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val());
});
I'd strongly suggest you familiarise yourself with the jQuery documentation, specifically val() in this case.
It's showing '0' in field1, even though field2 is set to 1 by default.
You were assigning a string to $('#textfield1').val method which is why your code was not having any effect on textfield1's value.
Make it
$(document).on('click', '#button', function() {
$('#textfield1').val( $('#textfield2').val()); //use jquery val method
}
Generally speaking, JQuery offers only functions, and not properties (as #Craicerjack stated), hence remove that === and pass the new value as an argument, as follows:
$('#textfield1').val("yourText");
Also, you're passing a CSS selector rather than just an element ID to the Document.prototype.getElementById() function. Remove that # qualifier!
Moreover, you shoudln't be using a stringified JavaScript expression as a value, otherwise you'll get that exact JS expression as the input value. Rather, don't put those quotes around the expression, so that the interpreter will be evaluating it. Below is some working code.
$('#textfield1').val(document.getElementById('textfield2').value);
However, as #Rory McCrossan pointed out, you're using an odd mix of plain DOM and JQuery, and that makes no sense. It would be more consistent to also read the value of the other text field using JQuery, as follows:
$('#textfield1').val($('#textfield2').val());
Alternatively, you may do not need JQuery and opt for the standard DOM interfaces like in the example below:
document.getElementById('textfield1').value = document.getElementById('textfield2').value;

Default Value in drop down list not being selected

I have a drop down list [ Incident, Question, Problem, Task]. I have written a code when an end user logins in and has a tag called product the default value should be problem. However it does not seem to work. It still gives the user the option to select values from the list.
$j(document).ready(function() {
if(location.pathname == '/requests/new') {
var ct = currentUser.tags;
if(ct.indexOf("product") >= 0){
$j(document.getElementById("ticket_fields_75389").value = "Problem");
}
else {
$j(document.getElementById("ticket_fields_75389").value = "");
}
}
})
Note: This answer is incorrect. I will delete it once I know the OP read my comment.
It still gives the user the option to select values from the list.
Well, of course, setting value will only change the initially selected value. If you want "fix" the value of the select element, so that the user cannot change it, you have to make it read-only. Lets stick with jQuery (what you have is a weird mix of DOM API and jQuery †):
$j("#ticket_fields_75389").val("Problem").prop('readonly', true);
†: Let's have a close look at the line
$j(document.getElementById("ticket_fields_75389").value = "Problem");
What exactly is happening here? Obviously we have a function call ($j(...)) and we pass something to it. This "something" is the result of the expression
document.getElementById("ticket_fields_75389").value = "Problem"
This finds an element by ID and assigns the string "Problem" to the value property. This is an assignment expression. The result of an assignment expression is the assigned value, i.e. "Problem".
That is the value that is passed to $j(...), so we have $j("Problem");. Since $j refers to jQuery, this would search for all elements with tag name Problem, which does not exist in HTML. It would also return a jQuery object, but you are not doing anything with it.
Hence the wrapping in $j(...) is completely unnecessary or even wrong, even though it doesn't throw a syntax or runtime error.

Working with jQuery Collections

I'm trying to increase my understanding of jQuery. Please consider the following code.
if ($('.myClass').data('id') == '123') {
}
How does this work? It looks simple enough until you understand that $() returns a collection of elements. So what does the code above do exactly? How does it make sense to compare the value of the data-id attribute for a collection of elements like this?
(I understand I can use each() to explicitly test each element in the collection. My question is about what the code above does.)
.data('id') returns the value for the first item in the collection, but .data('id','xyz') will set the value for all items in the collection - much the same behaviour as other jQuery methods like .html(), .text(), etc.
It may not seem to make sense to just test the first in an if statement like that, but it makes more sense for cases where you know there will be exactly one element, for example when your selector is an id, or when you use $(this).data('id') inside an event handler or something.
If you are asking how to test whether all items in the collection have a particular data value you can do this:
var $col = $('.myClass');
if ($col.length === $col.filter(function(){return $(this).data('id') === '123';}).length) {
// do something
}
Or if you just want to know if at least one has that data value:
if ($('.myClass').filter(function(){return $(this).data('id') === '123';}).length > 0) {
// do something
}
I believe if you're trying to get a value through a jquery function, it returns the value from the first item in the collection. for example if you have:
<div class='1'></div>
<div class='2'></div>
<div class='3'></div>
and you run:
$('div').attr('class');
it will return "1". I don't know if this is uniform through all jQuery functions, but this is the expected behavior.
You can use jQuery .each() - http://api.jquery.com/jQuery.each/
Example in comments since stackoverflow doesn't like jsFiddle that much.

How do I find out whether an element with that ID exists or not?

I do a:
console.log($('#test'));
I know that test doesn't exist. If I do a console.log, it doesn't output undefined/null. Rather it ouputs something like an empty array and when I check that array it looks like it returns the jQuery object itself.
I also tried:
if ($('#test')){
//do something
}
But it still doesn't work. I want to know whether the ID I am selecting exists on page or not. How do I do that using jQuery?
It's something like 20x faster to do this:
if (document.getElementById("test"))
compared to the jQuery operation to just determine if a DOM object with that id exists in the page. jQuery can do a lot for you, but when its general selector engine and general object structure isn't needed, it's not the quickest way to do things.
As others have said, $("#test") is always a valid jQuery object, even if #testdoesn't exist. If the #test object doesn't exist, then $("#test") will be a jQuery object that has no DOM objects in it (the internal array will have a .length === 0), but it's still a valid object.
In JavaScript, objects are always truthy, so using it in that fashion will always pass the condition.
You need to check the length property. A response of 0 is falsy, and will work as expected.
if ($('#test').length) {
// ...
}
This is unlike document.getElementById(), which returns null if the element with that id attribute does not exist.
If this is confusing, you could always write a quick jQuery plugin.
$.fn.exists = function() {
return !!this.length;
};
You can then call exists() on a jQuery collection, to ensure that selector has matched at least one item.
Use '(' and ')' for 'if' statements, and check if the returned array has length greater than 0:
if ($('#test').length > 0){
//do something
}
use something like this
if ($('#test').length > 0){
alert('hi')
}else
{
alert('hello')
}
Live Demo ​
Use
if ($('#test').length > 0){
//do something
}
the length tells you how many items were selected if it is 0 no element has the id test.
best way for this is to check length of the selected element
if ($('#test').length > 0){
//do something
}
But if you want to create a exist function jQuery welcomes you just add the line in your script
jQuery.fn.exists = function(){return this.length>0;}
and now you can Check if element exist or not
if ($(selector).exists()) {
// Do something
}
console.log($('#test'));
This won't print the value because it represents the object found in the DOM with the id test.
If you want to get values, use $("#test").val(); or $("#test").html();
If you want to check existence, do the length test as suggested above.
Also, if you're testing for the existence of a generated element (something you added to the DOM), make sure you checkout .live (http://api.jquery.com/live/). This is need for all elements that are created after the page is loaded.

javascript if condition not executing all commands

I'm having one little iritating problem. I have simple if condition in javascript code.
It goes something like this:
if (istinito)
{
alert ('123');
document.getElementById('obavestavanje').value="Pobedi "+ime_igraca+"!!!";
kraj=true;
}
Alert apears when istinito=true, but element with id="obavestenje" never get its value, and variable kraj never is set to true. Variable kraj is global variable, and there are no conflicts with other parts of the JS code.
Any ideas why code stops after alert?
Looks like document.getElementById('obavestavanje') is returning null. You are trying to de-reference the null reference by using document.getElementById('obavestavanje').value which results in null pointer exception. If you look into the console, you should see some exception being raised. It is always a good idea to check if the document.getElementById() is returning a valid object before trying to dereference it.
e.g.
if (istinito)
{
alert ('123');
element = document.getElementById('obavestavanje')
if(element){
element.value="Pobedi "+ime_igraca+"!!!";
}
kraj=true;
}
First advice i could give you:
Use more console logging for debugging. Almost any modern browser got a console to debug and other things.
if (istinito) {
console.log("i am here");
}
from that same console you can also execute commands. Those dom manipulations are easily done from the console. just run them and see if it works.
the code:
document.getElementById('obavestavanje').value = "some value"
looks ok. nothing wrong with it. i guess you don't have an element with id "obavestavanje" ?
Looks like your code is okay. And you are sure you have an element by id 'obavestavanje'. Could you please tell what element is it? Is it a button, textbox or someting like that?
Also the String in the "Pobedi "+ime_igraca+"!!!" , what is 'ime_igraca'? Is it a variable and if it is have you defined this variable somewhere?
Or did you mean to give the value "Pobedi ime_igraca !!!" ??
Thanks
Ranis MK

Categories

Resources