Updating a variable in jQuery script - php

I am currently building a dynamic form, using a bit of HTML, PHP and jQuery. This form contains a drop down select field (with the tag name) and two input boxes named tag_text_color and tag_background_color.
When you select a tag in the select field, a bit of jQuery will fill the boxes tag_text_color and tag_background_color with the current database value.
Before that, I have a form which allow the user to add a tag in the database. My problem occurs when I right before adding a tag in the database.
Here is the code for adding a tag :
<form id="form_addtag" method="post" name="form_addtag" action="add_tag.php">
<legend>Add a tag</legend>
<input type="text" name="tag_name" id="tag_name" class="text" size="30" placeholder="Tag Name" />
<input type="text" name="tag_text_color" id="tag_text_color" class="text" size="6" placeholder="#ffffff"/>
<input type="text" name="tag_bg_color" id="tag_bg_color" class="text" size="6" placeholder="#000000" />
<button type="submit" id="button_save_tag">Add</button>
</form>
and the jQuery corresponding function :
$( document ).ready(function() {
$("#form_addtag").submit(function(e) {
e.preventDefault();
var url = "add_tag.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_addtag").serialize(), // serializes the form's elements.
});
$('#form_addtag')[0].reset();
$("#form_edittag").load("demo.php #form_edittag")
});
Adding a tag works fine, and it reloads perfectly the form to edit a tag. However if in this block I am selecting the new tag, it is not loaded yet by jQuery
HTML to edit a tag :
<form id="form_edittag" method="post" name="form_edittag" action="edit_tag.php">
<legend>Edit a tag</legend>
<select id="select_edittag">
<?php
$tags = get_tags();
$numberOfTags = sizeof($tags);
var_dump($numberOfTags);
var_dump($tags);
foreach ($tags as $line)
{
echo("<option value='".$line["name"]."''>".$line["name"]."</option>");
}
//print("<option value='". $tags[ $j ]["name"]."'>".$tags[ $j ]["name"]."</option>");
?>
</select>
<input type="text" name="tag_text_color_edit" id="tag_text_color_edit" class="text" size="6" />
<input type="text" name="tag_bg_color_edit" id="tag_bg_color_edit" class="text" size="6" />
<button type="submit" id="button_edit_tag">Edit</button>
<button type="submit" id="button_delete_tag">Delete</button>
</form>
Corresponding jQuery :
$( document ).ready(function() {
$( document ).on( "change", "select#select_edittag", function()
{
var name = $("#select_edittag").val();
var tags = <?php echo json_encode(get_tags()); ?>;
$("#tag_text_color_edit").val(tags[name]["text_color"]);
$("#tag_bg_color_edit").val(tags[name]["background_color"]);
});
});
The function get_tags() will return an array with all the tags in the database.
I was thinking that each time I select a new item in my select "select_edittag" it would run the script, and update the tags variable with the lastest content from the function get_tags(). It does not sadly.
Any idea ? If you want a live demo I can host something like that

No.
PHP is running once, when loading the page. You must repopulate 'tags' via ajax. Check: getJSON

Related

After showing output using jQuery ajax the value doesn't pass using PHP post method

Hi I try to sum two data using AJAX and display it into hidden text input after that, I will pass the variable using PHP post method.
There are no problems in my jQuery AJAX code but the problem is after I submit the button, the value I retrieve from textbox total_rec[] is blank.
Here's my code below.
HTML:
<form method="post" action="<?php echo base_url() ?>user/recitem_insert">
<table>
<thead>
<tr><th>Test</th></tr></thead>
<tbody>
<tr><td>
<input type="hidden" name="last_item_rec[]" value="<?php echo $row->rec_qty; ?>">
<input type="text" name="item_rec[]" id="txt" disabled="">
<input type="hidden" name="total_rec[]" value="">
</td><tr>
</tbody>
</table>
</form>
JQUERY AJAX:
<script>
$(document).ready(function(){
$("input[name=item_rec\\[\\]]").on('keyup',function(){
var one = $(this).parents('tr').find('input[name=last_item_rec\\[\\]]').val();
var two = $(this).parents('tr').find('input[name=item_rec\\[\\]]').val();
sum = parseInt(one) + parseInt(two);
$(this).parents('tr').find('input[name=total_rec\\[\\]]').val(sum);
});
});
<script>
PHP CODE: (recitem_insert.php)
$total_rec = $_POST['total_rec'];
for($i=0;$i<sizeof($check);$i++){
for($j=0;$j<sizeof($total_rec);$j++){
$query=mysqli_query($con,"UPDATE tblstock
SET
rec_qty='$total_rec[$j]'
WHERE id = '$check[$i]'
")or die(mysqli_error($con));
}
}
As you told that the item contain 2 or more value. So you can use class instead of name.
HTML
<input type="hidden" class="last_item_rec" name="last_item_rec[]" value="23" />
<input type="text" class="item_rec" name="item_rec[]" id="txt" />
<input type="hidden" class="total_rec" name="total_rec[]" value="" />
jQuery
$(function(){
$(".item_rec").on('keyup',function(){
var one = $(this).parents('tr').find('.last_item_rec').val();
var two = $(this).parents('tr').find('.item_rec').val();
sum = parseInt(one) + parseInt(two);
console.log(sum);
$(this).parents('tr').find('.total_rec').val(sum);
});
});

How to check a select element change when the element name is an array

What I am trying to achieve:
My form consists of four fields of #item, #unit, #price, and #total.
A user can input multiple lines of #item and #unit. For this, if the user clicks on "Add new line', there will appear a new line to receive user input for item and unit (quantity). If the user clicks on "-" on an already existing line, the line will be removed.
Which item is selected is identified on real-time using javascript change().
The price of the selected item is dynamically retrieved using ajax and the price data is appended into the #price element and #total element is also filled up by calculating #unit x #price.
To achieve this, here's what I did.
First, my HTML form as below.
<form id="form">
<input type="submit" name="create" value="Create" />
<!-- dynamically add more lines -->
<div class="form-group table-row hide" id="template">
<!-- remove button-->
<div class="table-cell" style="width: 45px;">
<a class="btn btn-default removeButton">
<span class="glyphicon glyphicon-minus">
</span>
</a>
</div>
<!-- user input: item -->
<div class="table-cell">
<select id="item" class="form-control">
<option value=""></option>
<option value="item-1">Item 1</option>
<option value="item-2">Item 2</option>
<option value="item-3">Item 3</option>
</select>
</div>
<!-- user input: quantity -->
<div class="table-cell">
<input id="unit" min="1" step="1" value="1" type="number" class="form-control" />
</div>
<!-- price is dynamically filled up using ajax -->
<div class="table-cell">
<input id="price" type="text" class="form-control" />
</div>
<!-- total is dynamically calculated -->
<div class="table-cell">
<input id="total" type="text" class="form-control" />
</div>
</div>
<button type="button" class="btn btn-default addButton">Add new line</button>
</form>
And javascript code to implement dynamic add/remove of input forms.
<script>
jQuery(document).ready(function($) {
var idx = new Number( 0 );
$('#form')
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#template'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
// assign name attributes with proper array name and index
$clone.find('#item').attr('name', 'lines[' + idx + '][item]').attr('required', 'required').val('');
$clone.find('#unit').attr('name', 'lines[' + idx + '][unit]').attr('required', 'required').val('');
$clone.find('#price').attr('name', 'lines[' + idx + '][price]').attr('required', 'required').val('');
$clone.find('#total').attr('name', 'lines[' + idx + '][total]').val('');
idx = idx + 1;
})
// Remove button click handler
.on('click', '.removeButton', function() {
if (confirm("<?php _e( 'Are you sure you wish to remove this line? This cannot be undone.', 'doumi' ); ?>")) {
var $row = $(this).parents('.form-group');
// Remove element containing the option
$row.remove();
idx = idx - 1;
}
});
});
</script>
Lastly, jQuery to call ajax.
<script>
/* Get Item Price */
jQuery('#item').change(function(){
var $item_id=$('#item').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// call ajax
jQuery("#price").empty();
jQuery.ajax({
url: ajaxurl,
/* ******************************************************************** */
/* ajax_get_item_price is a function that returns the price of the item */
/* ******************************************************************** */
data:' action=ajax_get_item_price&item_id='+$item_id,
type:'GET',
success:function(results) {
jQuery("#price").append(results);
}
});
});
</script>
I have no problem dynamically adding and removing lines for the input form.
The problem is that form elements in each line is given a name as an array like below;
<select id="item" name="lines[0][item]"></select>
<input id="unit" name="lines[0][unit]" />
<input id="price" name="lines[0][price]" />
<input id="total" name="lines[0][total]" />
<select id="item" name="lines[1][item]"></select>
<input id="unit" name="lines[1][unit]" />
<input id="price" name="lines[1][price]" />
<input id="total" name="lines[1][total]" />
<select id="item" name="lines[2][item]"></select>
<input id="unit" name="lines[2][unit]" />
<input id="price" name="lines[2][price]" />
<input id="total" name="lines[2][total]" />
...
...
...
<select id="item" name="lines[n][item]"></select>
<input id="unit" name="lines[n][unit]" />
<input id="price" name="lines[n][price]" />
<input id="total" name="lines[n][total]" />
I guess that since there are multiple #items with varying names, jQuery does not know which #item it needs to pay attention to. However, I have no idea, either, as to how to properly call ajax with the concerned #item.
Any advice is highly appreciated.
Ok, as I said, ids should be unique for a page, so for similar items you should use classes:
....
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
....
So, for change event use something like
jQuery('.item').change(function(){
// to narrow the items, use this
var this$ = $( this );
// this$ contain exactly one item, which is currently changing
// do stuff
});
No quite get what exactly wrong is happening, but I think you have too many items with price is and thus issuing prblems.
So this line does next: gets all #price elements and appends results to each of them.
success:function(results) {
jQuery("#price").append(results);
}
You should clarify which #price item you exactly need.
First, as I already mentioned - use classes for multiple similar fields jQuery(".price")
Second, add some clarification what field exactly should be updated.
There can be many ways, I show two
One way, use next function.
success:function(results) {
this$.next('.price').eq(0).append(results);
// here we refer to this$ - we try to find all `.price` element
// which come after our `select`
// as there can be a lot of them we take only the first one
}
Another way, Use kind of context, ie some div, in bounds of which your elements are grouped.
I suggest changing your html like this
<div class="item-wrapper">
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
</div>
So, every block of your fields will be wrapped in a div.
After that we can tell jQUery to find .price element only in a div in which changed select is located
success:function(results) {
var parent$ = this$.parent();
// again we refer to this$ getting its parent which is div
parent$.find('.price').append(results);
// here we try to find `.price` element located in a parent$ div.
// As it is definitely only one, we don't need to use any other code.
}
So, this is all that I can say)

How to save the generated HTML from wysihtml5 or pass it to PHP page

I am using bootstrap-wysihtml5 to implement WYSIHTML Editor in my bootstrap site. But I dont get hoow can I pass the HTML content to a php page in order to save the content in database. Though I have used ID(content) for the textarea but the php page is not getting data. The URL by "Get" shows "?_wysihtml5_mode=1" at the end instead of something like "?content=..."
<form action="save.php" method="get">
<textarea class="textarea" id="content" placeholder="Enter text ..."></textarea>
<input type="submit" class="btn btn-primary" />
</form>
<script>$('#content').wysihtml5(); </script>
EDIT: You need to add a name attribute to your textarea for it to be posted to your PHP. I completely forgot this. So forget every other modifications I did, just do this to your textarea in your original code :
<textarea class="textarea" id="content" name="content" placeholder="Enter text ..."></textarea>
You should also send the values through a POST request because sending the html in the URL arguments is not a good idea.
Old Answer:
You need to also post the html when submitting the form. There are multiple ways to do this but as an example you can add an hidden input field in which you will store the html before sending it to php.
First I changed a bit your html, the form is now sent through a POST request which is better than through the URL arguments if you want to send HTML:
<form id="myform" action="save.php" method="POST">
<textarea class="textarea" id="content" placeholder="Enter text ..."></textarea>
<input type="submit" class="btn btn-primary" />
<input type="hidden" id="html" />
</form>
Add the javascript event to change the hidden field value before submitting the value:
$("#myform").submit(function() {
// Retrieve the HTML from the plugin
var html = $('#content').val();
// Put this in the hidden field
$("#html").val(html);
});
<script>
$('#content').wysihtml5();
$(document).ready(function() {
$('.btn btn-primary').click(function() {
var content = $('#content').html();
$.ajax({
url: 'update.php',
type: 'POST',
data: {
content: content
}
});
});
});
</script>
<form>
<textarea class="textarea" id="content" placeholder="Enter text ..."></textarea>
<input type="submit" class="btn btn-primary" />
</form>
update.php
<?php
DATABASE_CONNECTION
$GET_THE_CONTENT_HERE = $_POST[content];
INSERT TO DATABASE
?>

Appendchild not posting form data in firefox

I have an appendchild-function that adds form elements. In IE, everything works fine; the process.php is able to $_POST it. But in firefox, it doesnt send the data.
Here is my code.
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work" /><input type="file"
class="fileupload" size="80" name="file' + (num) +'" onclick="addElement()"/> <a
class="removelink" onclick=\'removeElement('+divIdName+')\'>Remove This File</
a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</td>
Solved the problem...
Basically, I had this..
<div>
<form>
</div>
</form>
And changed to this..
<form>
<div>
</div>
</form>
Seems firefox doesnt like invalid html.
You can use PHP's field name array functionality to get around having to keep track of your field names. Simply name the field like this:
<input type="file" name="files[]" ... />
^^--- array notation
and PHP will handle each file box as a separate member in the $_FILES array after the form's submitted. This frees you up from all the extra overhead of keeping track of how many boxes there are and hidden form fields to store the value.
You may want to reconsider having the file element's onclick be the thing that adds a new file input. What happens if someone clicks on the "browse" button to add a file? They'll get a new file input box, even though they may only have wanted one. If they choose the wrong file or change their minds later and click browse again to change the file selection, they'll get yet another input box.
Consider having a dedicated "add another box" button instead.
Just want to ask where your form tag is located? Before or after table tag? I had similar problem and my form tag was inside table. When I put form tag outside of table everything worked fine.
Site doesn't work anymore.
Here is working example. I used your code. Only two thing I changed is
<input type="text" name="work[]" /> instead of <input type="text" name="work" />
and you was missing one </div> closing div tag
here is code (tested on IE7, IE8, FF and google chrome)
<?php
if (!empty($_POST['btnProsledi'])){
print_r($_POST);
echo "<br />";
print_r($_FILES);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work[]" /><input type="file" class="fileupload" size="80" name="file' + (num) + '" onclick="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td>
<input name="proba" type="text" id="proba" value="" />
</td>
</tr>
<tr>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</div>
</td>
</tr>
<tr>
<td>
<input name="btnProsledi" type="submit" id="btnProsledi" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>

how to count all check boxes in a form (Javascript)

I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW: As others have noted, the id attribute in any HTML tag should be unique within the document. I've omitted your id="1" attributes in my sample HTML above.
Update:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
In Plain JavaScript:
var myForm = document.forms[nameOrIndex];
var inputs = myForm.getElementsByTagName('input');
var checkboxes = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].getAttribute('type').toLowerCase() == 'checkbox'){
checkboxes.push(inputs[i]);
}
}
alert(checkboxes.length);
I would go with:
alert(document.querySelectorAll("input[type=checkbox]").length);
If you wanted a particular form you would need to select the form and use that as a base for your call to querySelectorAll instead of document or change the selector to include the form.
<form id="aForm">
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
<form id="bForm">
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
Then use:
alert(document.querySelectorAll("#aForm > input[type=checkbox]").length); //shows 2
alert(document.querySelectorAll("#bForm > input[type=checkbox]").length); //shows 3
Note: The Selectors API is only available in newer browsers starting with: Internet Explorer 8, Firefox 3.5, Safari 3.1, Chrome 1, and Opera 10.
alert( $("form input[type='checkbox']").length );
Will give you all the checkboxes in a form, using jQuery.
As you tagged your question with php and you seem to use some sort of numbering already for the form fields, you can also just echo that php counter to a javascript variable:
<?php
//
?>
<script language="javascript" type="text/javascript">
var checkbox_counter = <?php echo $your_counter_in_php; ?>
</script>
<?php
//
?>
By the way, in html you can only have one id on a page and it canĀ“t start with a number.
you could use jquery
var len = $('input:checkbox').length;
alert(len);
WORKING DEMO
if you have jQuery you could do something like
alert ($(':checkbox').length ());
If not then you'll have to document.getElementsByTagName ('input'), iterate over the collection you get back and increment a counter every time you encounter one with its type attribute set to checkbox.

Categories