I am creating a social media website and am trying to make a comment textarea appear when users click on a status.
Here is what I have so far:
$(".status").click(function (){
//Check if status div they clicked on contains a textarea already
if($(this).closest('div').innerHTML.indexOf("<textarea name='status_body'>") == -1) {
//Append with textarea
var textarea = "<textarea name='status_body'></textarea>";
$(this).closest('div').append(textarea);
}
});
This was working before I put the if statement in. Of course without the if statement a textarea will be added everytime the user clicks. I would only like for a textarea to appear if there is not one aready.
Another method I tried and failed with is:
if(!$(this).closest('div:contains("<textarea")').length > 0)
You're close, just check for the existence with .length
if ($(this).closest("div").find("textarea").length > 0) {
//contains a text area!
} else {
//Doesnt!
}
Do not search for it as text. You should threat the textarea for what it is, a DOM element.
if($(this).closest('div').find("textarea[name='status_body']").length == 0) {
/*...*/
}
Related
I want to hide a drop-down on the basis of a selected user input.
So far I have done
var getText = document.getElementById('issuemeters-issuance_type').value;
Then in if else condition
if(getText == 'HESCO/OEM')
{
$('.field-issuemeters-issuer').hide();// the drop-down which i want to hide
$('#issuemeters-issuer').val('');// setting the text value to null
}
else
{
$('.field-issuemeters-issuer').show();
}
It will work when getText is equal to HESCO/OEM. I have also checked the value in console but I don't know why it's not working.
Any help would be highly appreciated.
try with a listener on "issuemeters-issuance_type" change:
$('#issuemeters-issuance_type').on('change',function(){
if($(this).val() === 'HESCO/OEM')
{
$('.field-issuemeters-issuer').hide();// the drop-down which i want to hide
$('#issuemeters-issuer').val('');// setting the text value to null
}
else
{
$('.field-issuemeters-issuer').show();
}
});
assuming that "issuemeters-issuance_type"
If #ccs-inline has content then I want to hide #inpage otherwise I want to show #inpage.
The issue I have is that if the first div has no content but second div does then it doesn't display the content of second div.
$(document).ready(function(){
if ($('#ccs-inline:not(:empty)')){
$('#inpage').hide();
} else {
$('#inpage').show();
}
});
Use .length, to confirm there is no empty div. Since the jQuery returns a jQuery object hence your if condition will always be true.
Example code:
$(document).ready(function() {
if ($('#ccs-inline:not(:empty)').length > 0) {
$('#inpage').hide();
} else {
$('#inpage').show();
}
});
I need to add a dropdown where options can be filtered on the fly when on starts to type some word (exactly what Chosen does) AND where a span is always displayed before each option, similar to the Google Drive search bar:
(in this example icons are displayed, but I just need to display a span tag)
"always displayed" in the sense that the span tag should be displayed at the initial display of the dropdown, but also when the list of options starts being filtered, or when an option is selected.
With Chosen I've tried to do this this way:
$select.on("chosen:showing_dropdown", function() {
$(".chosen-results").find('li').each(function(index) {
if(index !== 0) { // ignore the "prompt" li
var courseName = $(this).html();
$(this).html("<span style='color: red'>foo</span> " + courseName);
}
});
});
It works when the dropdown is first displayed by Chosen, but as soon as I start typing something the filtered list of results loses my span tags. I can't find a chosen event that is triggered when the list starts being filtered.
Is there a way to achieve what I need with Chosen, or with any other similar plugin?
If I understood your question correctly then in the <li> element you want to put your span ? Try below:
$select.on("chosen:showing_dropdown", function() {
$(".chosen-results").find('li').each(function(index) {
if(index !== 0) { // ignore the "prompt" li
var courseName = $(this).html();
$(this).prepend("<span style='color: red'>foo</span> " + courseName);
}
});
});
I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?
If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div> into the document.
One options is to use a custom event as a pub/sub.
$(document).on('document_change', function () {
if (document.getElementById('liveGraph_id')) {
// do what you need here
}
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
$(this).trigger('document_change');
});
If it is added dinamically, you have to test again. Let's say, a click event
$("#element").click(function()
{
if($("#liveGraph_id").length)
alert("HHH");
});
How you inserting your dynamic generated div?
It works if you do it in following way:
var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
alert('exists'); //wont give alert because it doesn't exist.
}
jsfiddle.
Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):
var allDivs = document.getElementsByTagName('div');
Any div with an id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
// div with someId exists
}
If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:
<button onclick="
alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
var div = document.createElement('div');
div.id = 'newDiv';
document.body.appendChild(div);
">Add div</button>
Click the Check for div button and you'll get false. Add the div by clicking the Add div button and check again—you'll get true.
is very simple as that
if(document.getElementById("idname")){
//div exists
}
or
if(!document.getElementById("idname")){
// don't exists
}
Below is part of a script I have which dynamically adds html input text boxes. Each one of these input boxes should be an autofil text box. This is the code I'm using - http://www.nodstrum.com/2007/09/19/autocompleter/. Demo is here - http://res.nodstrum.com/autoComplete/.
For the above example it is only one input box but my code allows for dynamic input text boxes (i.e. the user clicks on a button and more pop up).
The problem I have is I don't know how to fix the jquery so that it's dynamic for the input text box id. How do I make it dynamic so that fill() outputs data to foo01, foo11, foo21 etc. not just foo11?
<script src="jquery-1.2.1.pack.js" type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<script type="text/javascript">
var x = 1;
function add() {
var fooId = "foo";
for (i=1; i<=2; i++)) {
var element = document.createElement("input");
element.setAttribute("type", fooId+x+i);
element.setAttribute("name", fooId+x+i);
element.setAttribute("id", fooId+x+i);
if(i==1){
element.setAttribute("onkeyup", "lookup(this.value);");
element.setAttribute("onblur","fill();");
element.setAttribute("value", "First name");
}
if(i==2){
element.setAttribute("value", "Last name");
}
var foo = document.getElementById("fooBar");
foo.appendChild(element);
}
x++;
}
</script>
rpc.php
<?php
include_once("includes/config.php");
$conn = new mysqli("$localhost", "$dbusername", "$dbpass", "$db", "3306"))
if(!$conn) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $conn->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE '$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $queryString = 'Uni';
// Returned data = 'United States, United Kindom';
$query = $conn->query("SELECT name FROM cities WHERE name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
****************EDIT*****************
It needs to be filled individually. It looks like this:
Text Box (foo00) Text Box
Add
If you click on Add you get
Text Box (foo00) Text Box
Text Box (foo10) Text Box
Add
If I was to click on text box (0,0) and started typing "Lo" a text box would pop up with London, Logon etc. Then if you click on "London", only (0,0) will be updated and will now be "London" i.e.
London Text Box
Text Box Text Box
Add
Now I click on the text box below London (foo10) and start typing "Ro" and a text box would pop up with Rome, Romania etc. I click on Rome and only foo10 should be updated and will look like this:
London Text Box
Rome Text Box
Add
Hopefully that helps with the questions below.
I've never used jquery before this example. I'm using jQuery 1.2.1 because that's what the example said. I'll need to look into a newer version of JQuery.
************** EDIT 2 **********************
I didn't realise that the file rpc.php called fill(), which is where I believe the issue to be. I've updated the code above to include rpc.php and the jquery which calls it.
In the following function, you have hard coded the id foo11
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
Instead, you can use this operator to access the specific textbox that called the fill() method.
function fill(this) {
$(this).val(thisValue); // will access the current element but not sure where you are getting the value
setTimeout("$('#suggestions').hide();", 200);
}
and change the onblur like this
element.setAttribute("onblur","fill(this);");
After reading your updated question, I tried to make a sample application but unfortunately I can't make it to work without changing too much. The problem is, the method you are using to create auto complete works in a way that it is difficult to make it work with dynamically added HTML. So here are my 2 alternatives.
Make some changes in the rpc.php code and only emit values as array and create HTML on the client.
Since you are already using jQuery, try jQuery autocomplete
You can find info about autocomplete here and here
I already made a sample for you using jQuery autocomplete. Check this fiddle