How can I find an #[ID]
using jQuery?
I have a handler that checks some info, I'm checking with jQuery if there is found a ID... But it always give back "Nothing" and it gives me the errors so it mean that there are errors!
I do it on this way...
jQuery:
posting.done(function(data){
var warnings = $(data).find('.warnings');
$('form#gastenboek').append(data);
if (warnings.length > 0) {
alert("errors")
} else {
alert("Nothing");
}
});
Handler:
if (!empty($warning) && isset($warning))
{
foreach($warning as $warning)
{
echo "<span id='warnings' style='color:orange;' class='glyphicon glyphicon-flag'></span><a style='color:orange;'>" . $warning . "</a><br>";
}
}
You need to use find()
var warnings = $(data).find('#warnings');
Note : Id
should be unique , use class
instead
PHP:
if (!empty($warning) && isset($warning))
{
foreach($warning as $warning)
{
echo "<span style='color:orange;' class='glyphicon glyphicon-flag warnings'></span><a style='color:orange;'>" . $warning . "</a><br>";
// --^-- adding class
}
}
jQuery :
posting.done(function(data){
var warnings = $(data).find('.warnings');
$('form#gastenboek').append(data);
if (warnings.length > 0) {
// --^-- getting count of elements
alert("warnings")
} else {
alert("Nothing");
}
});
First of all you are using the attr()
method in the wrong place as it should contain an attribute as the first argument. And since there is no element which has an attribute #warnings
, you'll be getting null
.
Secondly, there can be only one element in the DOM with a particular id
, unless you specify it as an array by providing []
with the id. So searching the DOM with .find()
will return only the first matched element.
Hence, you should implement a class
warnings on the elements that your data
returns. Then use jQuery's .find()
which searches for elements having that particular warnings class:
var warnings = $(data).find('.warnings');
if(warnings.length > 0){
alert("warnings");
} else {
alert("nothing");
}