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();
});
Related
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
I'm making a simple list application and the items should be easy to edit (just clicking on them). It works fine, but I still have a problem at saving the changes to the database, for some reason it doesn't happen. I'm sure it's a code problem, but I haven't been able to find it.
List Page
<input type="hidden" id="hidden" id="hidden" value="">
<ul id="lista">
<?php
$IDllista = 1;
$selectitems = mysql_query ("SELECT * FROM items WHERE IDllista=".$IDllista." ORDER BY posicio ASC") or die (mysql_error());
while ($row = mysql_fetch_array($selectitems))
{
echo'<li class="item" id="';
echo $row['IDitem'];
echo '"><span class="edit" id="span-';
echo $row['IDitem'];
echo '" data="';
echo $row['Text'];
echo '">';
echo $row['Text'];
echo'</span></li>';
}
?>
</ul>
JavaScript
//Call the edit function
$(".edit").live("click", function () {
// Get the id name
var iditem = $(this).parent().attr("id");
var element = this;
var id = element.id;
//New text box with id and name according to position
var textboxs = '<input type="text" name="text' + id + '" id="text' + id + '" class="textbox" >'
//Place textbox in page to enter value
$('#'+id).html('').html(textboxs);
//Set value of hidden field
$('#hidden').val(id);
//Focus the newly created textbox
$('#text'+id).focus();
});
// Even to save the data - When user clicks out side of textbox
$('.edit').focusout(function () {
//Get the value of hidden field (Currently editing field)
var field = $('#hidden').val();
//get the value on text box (New value entred by user)
var value = $('#text'+field).val();
//Update if the value in not empty
if(value != '') {
//Post to a php file - To update at backend
//Set the data attribue with new value
$(this).html(value).attr('data', value);
$.ajax({
type: 'POST',
data: {id: iditem},
url: 'editartext.php'
});
}
// If user exits without making any changes
$(".edit").each(function () {
//set the default value
$(this).text($(this).attr('data'));
});
});
Edit Page
<?php
include_once "../connect.php";
$IDitem = $_POST['id'];
$noutext = "hola";
$actualitza = mysql_query ("UPDATE items SET Text = ".$noutext." WHERE IDitem = ".$IDitem." ");
?>
Quote problem i think. You can use query with single quote like;
"mysql_query("UPDATE items SET Text ='$noutext' WHERE IDitem ='$IDitem'");
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!
I have a page that generates forms depending on user choice. I want to know if there is a way to convert the form into plain text? Ex. The form has 4 fields, each has a label. I would like to take all the labels/fields and print them to the user as follows:
label1 field1
label2 field2
label3 field3
label4 field4
Is there a way to do so?
You can use jQuery to generate basic output, for example:
var texts = [];
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " - " + oInput.val());
});
var plainText = texts.join("<br />");
$("#Output").html(plainText);
This will iterate over all the form labels, then take the next element of each label which is the input.
Live test case.
If you don't mind an extra file, with PHP.
You'd need to make a small php file to echo all the form information like this:
<?php
$label1 = "label1";
$label2 = "label2"; //Set all labels here
$label3 = "label3";
$label4 = "label4";
echo $label1 . " " . $_POST['field1'] . "<br />"; //Change to get depending on your method.
echo $label2 . " " . $_POST['field2'] . "<br />";
echo $label3 . " " . $_POST['field3'] . "<br />";
echo $label4 . " " . $_POST['field4'] . "<br />";
echo "Done.";
?>
and put that in it's own file. Set the form's action attribute to that file and it will print out all the data.
One method, without a JavaSCript library, is:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
var labels = document.getElementsByTagName('label');
if (!document.getElementById('container')){
var container = document.createElement('ol');
container.id = 'container';
}
else {
var container = document.getElementById('container');
while (container.firstChild){
container.removeChild(container.firstChild);
}
}
for (var i=0,len=labels.length; i<len; i++){
if(document.getElementById(labels[i].getAttribute('for'))){
var newLi = document.createElement('li');
var iText = document.createElement('span');
newLi.innerHTML = labels[i].innerHTML;
iText.innerHTML = document.getElementById(labels[i].getAttribute('for')).value;
newLi.appendChild(iText);
container.appendChild(newLi);
}
}
document.getElementsByTagName('body')[0].appendChild(container);
return false;
};
JS Fiddle demo.
References:
node.appendChild()
document.createElement().
document.getElementById().
document.getElementsByTagName().
element.getAttribute().
element.innerHTML.
for () {...}.
node.firstChild.
node.removeChild().
while () {...}.
You may get the value for labels and fields in javascript using
var label1 = getElementById("id").name
Create a string formatted as you want to show the user and show all the values with
document.write(string);
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