Jquery - hide element after creating it - javascript

Function for creating elements:
function create_image(){
<?php if(isset($avatar)) : ?>
var brojac = 5;
<?php else: ?>
var brojac = 4;
<?php endif; ?>
var broj_slike = (5 - brojac) + 1,
slike;
for (var i = 0; i < brojac; i++) {
slike += '<label for="image'+ broj_slike +'">Slika ' + broj_slike + '</label><input type="file" name="userfile" id="image' + broj_slike + '" />';
broj_slike++;
};
return slike;
}
Function that inserts elements on the page:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length != 16 ) {
if ($('p[role=code_msg]').length != 0 ) $('p[role=code_msg]').remove() ;
code.after('<p role=code_msg>Pogrešan kod je unešen.</p>');
} else {
if ($('p[role=code_msg]').length != 0 ) $('p[role=code_msg]').remove() ;
$.post(url, {id : id, code : code_value}, function(data){
if($.trim(data) != 'TRUE'){
code.after('<p role=code_msg>Uneti kod je neispravan.</p>');
} else {
/*This part here put elements on the page*/
code.after('<p role=code_msg>Status malog oglasa je promenjen.</p>')
.after(create_image()).hide();
code.prev().remove();
code.remove();
}
});
}
});
How can I hide new elements?

I haven't seen the entire code but hiding an element is as simple as using the hide method.
$('<div/>').appendTo('#el').hide();
I'm creating and inserting the element into the dom before hiding it - an example that should resemble yours, if I understood correctly. (it is a bad practice, though, to insert an element in the dom to hide it immediately afterwards - it'd be better to insert it in the dom already hidden - it'd prevent an unnecessary reflow).

With this: $(jqueryelement).hide()

I would hide it before the element gets added to the DOM.
$('<div>').css({"display": "none"}).appendTo(elementInDOM);
OR
$(elementInDOM).append(
$('<div>').css({"display": "none"})
);
I'm sure there are plenty of other ways!

Related

Multiple sets of data insert at one call into separate divs by unique id AJAX

Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);

PHP - Onchange reload page with value of select

I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k

.load content when checkbox checked, remove when unchecked

I have a number of checkboxes which, when checked invoke the below script to show a chunk of html inside a form using .load:
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + article);
$('#form_' + id).toggle();
$('.submit').show();
});
The forms are dynamically created in the view like so:
<?php for($i = 1; $i <= 8; $i++){ ?>
<div id="form_<?php echo $i; ?>" class="hide">
</div>
<?php } ?>
However, I need the loaded html to be removed whenever the checkbox is unchecked, and that's where I get stuck. Using .toggle()the html is hidden, but it is being submitted anyway. Any idea how to achieve this?
Try this -
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
if(this.checked){
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + product);
}
else{
$('#form_' + id).empty();
}
$('.submit').show();
});
So add a check to see if it is checked. If it is not, empty its contents and hide it.
var bits = $(this).attr('id').split('_');
var id = bits[1];
if (this.checked) {
//...get content
} else {
$('#form_' + id).empty().hide();
}
Only load the content if the container is empty, and toggle the container based on wether or not the checkbox is checked :
$('input.article').on('change', function(){
var id = $(this).attr('id').split('_')[0],
article = 'article_' + id + '.html',
form = $('#form_' + id);
if (form.is(':empty'))
form.load('<?php echo base_url(); ?>assets/html/' + article);
form.toggle(this.checked);
$('.submit').show();
});

Javascript get title value from <li>

In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.

Jquery and get the eq value of my returned XML

Hi I have a simple ajax search that returns the results in a table. I can extract the XML and display it fine but what I cannot do is get the index number of the data (var Rows) .
When a user clicks the returned result I believe I would need this in order to retrieve all the data in order to use IE $("name:eq(1)",data).text();. Can anyone help me please and I hope this makes sense !!, thanks
My Jquery code is here
$(document).ready(function(){
$.ajax({
type: "GET",
url: "search_action.php?" + string ,
dataType: "xml",
success: disxml ,
});
})
}
function disxml(data){
dv = $('#crmbox')
$(data).find('list').each(function() {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
var rows = $(this).eq() ;
display = display + "(" + rows + ")" + " Name :" + name + " ID :" + cus_id + " <br>" ;
})
dv.html(r);
};
here is the php that generates my xml
echo '<results>' ;
while($row = mysql_fetch_array($result)) {
$name = $row['name'] ;
$major_id = $row['address1'] ;
echo '<list>' ;
echo '<name>';
echo $name;
echo '</name>';
echo '<mid>';
echo $major_id ;
echo '</mid>';
echo '</list>' ;
} ;
echo '</results>' ;
the extra tag is the close of an earlier function - no relevence to question
It sounds like you want the index you're currently at, in which case use the first parameter passed to the .each() callback, like this:
$(data).find('list').each(function(row) {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
//row is the index, starting at 0

Categories