well this is my first post :)
I have a mysql DB and a form where you chose what you want to order. I have to say, that for input fields it works, but I have a problem when it comes to dynamic dropdowns. This is what I have (the two queries):
<?php
// Getting the data from mySQL table for first list box
$quer1="SELECT DISTINCT kategorija FROM artikli order by kategorija";
// for second dropdown list we will check if category is selected else we will display all the subcategories
if(isset($kategorija) and strlen($kategorija) > 0) {
$quer2="SELECT artikel FROM artikli where kategorija='$kategorija' order by artikel";
}
else {
$quer2="SELECT artikel FROM artikli order by artikel";
}
?>
<form id="forma_narocilo" action="naroci.php" method="POST">
<div class="input_fields_wrap">
<div>
<select name="kategorija" id="kategorija" ><option value="">Izberi kategorijo</option>
<?php
foreach ($dbo->query($quer1) as $row2) {
if($row2['kategorija']==$kategorija) {
echo "<option id='izbirna_kategorija' selected value='$row2[kategorija]' onchange='self.location=self.location+'?kategorija='+this.options[this.selectedIndex].value'>$row2[kategorija]</option>"."<br />";
}
else {
echo "<option id='izbirna_kategorija' value='$row2[kategorija]'>$row2[kategorija]</option>";
}
}
echo "</select>";
echo "<select name='artikel[]'><option value=''>Izberi artikel</option>";
foreach ($dbo->query($quer2) as $row) {
echo "<option value='$row[artikel]'>$row[artikel]</option>";
}
echo "</select>";
?>
<input type="number" name="kolicina[]"/><button class="add_field_button">Add line</button>
</div>
</div>
<input type="submit" id="shrani" value="Save" >
</form>
and this works just fine and it is updating the fields according to my needs, but now I need an "add" button which will insert another line with all three fields (category, item, nrPcs). For normal html inputs I used this:
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+x+'<input type="text" name="artikel[]"/><input type="text" name="kolicina[]"/>X</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
this will add a and 2 inputs inside. for the reload I use this:
function reload(){
var form = document.getElementById("forma_narocilo");
var val = form.kategorija.options[form.kategorija.options.selectedIndex].value;
self.location='?kategorija=' + val ;
}
function init(){
document.getElementById("kategorija").onchange = reload;
}
window.onload = init;
Now, my question is, how can I insert dropdowns when clicking the add button? Of course it should work as the first one e.g. it has to be independent...
thanks, erik
I'm using codeigniter 3.0.4 and now stuck on a basic problem. I have an <input type='text'> with a default value generated using Jquery.
My Question, how do I check whether the value has been changed or not when I submit a form?
If the value now is different from default given value, it'll do a callback validation (it's actually to check email availability). Otherwise if the value is still the same as the default given value it will skip the callback validation.
This is my modal
<div class="modal-body" id="myModalBody">
<form id="contactform" role="form" method="POST" action='<?php echo base_url('administrator/kategori/editcategory');?>' >
<div class="form-group">
<label for="kategori"> Nama Kategori </label>
<input type="hidden" name="id" class='id' id='id'>
<input type="text" class="form-control edit-category" name='edit-category' id="edit-category" required autofocus>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success confirm-edit"> Edit Data </button>
</form>
</div>
as you can see, that form above submits the data to administrator/kategori/editkategori
and this is my editkategori() function
public function editcategory(){
if($this->input->post()){
$this->form_validation->set_rules('kategori', 'Kategori Baru', 'required|callback_correctcategory');
if($this->form_validation->run() == FALSE){
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"id" => $this->input->post('id'),
"kb" => $this->input->post('kategori')
);
$result = $this->admincrud->editcategory($tobesent);
if($result){
$this->session->set_flashdata('result', 'Kategori Sukses Diubah');
redirect('administrator/kategori');
}
}
} else {
redirect('administrator/kategori');
}
}
This is the JQuery function to automatically give values to corresponding text when the modal above is shown
$('.toggle-edit-modal').click(function(){
var id = $(this).closest('tr').find('td:eq(0)').text();
var categoryname = $(this).closest('tr').find('td:eq(1)').text();
$('.id').val(id);
$('.edit-categoryname').val(categoryname);
})
in the set of validation rules, I put the callback correctcategory(), and this is the correctcategory() function :
public function correctcategory($str){
$sterilizedkey = strtoupper(trim(str_replace(" ", "", $str)));
$tobeshown = ucfirst(strtolower($sterilizedkey));
$this->CI->db->select("upper(trim(REPLACE(`CategoryName`, ' ',''))) as `CategoryName`");
$this->CI->db->from('category');
$result = $this->CI->db->get()->result_array();
$data = array();
foreach ($result as $key => $value) {
$data[] = $value['CategoryName'];
}
if(in_array($sterilizedkey, $data)){
$this->set_message('correctcategory', 'The faculty has been registered before');
return false;
} else {
return true;
}
}
With the code above, the system will evaluate every value submitted through the form.
The problem comes when I open the modal, and a textbox with default given value appears. How can I skip the correctcategory validation if I directly submit the form but without changing the value of the textbox, or when the new value and the old given one are exactly the same ?
you have to store the original value in a hidden text box. and check it with the text box which has values.
for eg:
<input type="text" id="orig" value="your email">
<input type="hidden" id="hid" value="your email">
then in jquery on submit check like the following
var original = $('#orig').val();
var static = $('#hid').val();
if(original == static){
alert("not changed");
}else{
alert("changed");
}
Note: this code is only for example as you did'nt shared any of your code
If the value being set by Jquery is known by you, then the controller should as well be aware( guess this is the category database value)
Based on the assumption that default value is known.
To solve this, the controller function needs to be aware of the default value you are setting for the input.
class Categories extends CI_Controller {
public function edit()
{
// form submited?
If ( $this->input->post())
{
$this->load->model('category_model');
$error = null;
$success = false ;
$id = $this->input->post('id');
// now you were looking for 'kategori' instead of 'edit-category'
$posted_cat_name = $this->input->post('edit-category');
// get the db record
$category = $this->category_model->fetch( array('id' => $id ));
if( !$category->id)
{
$error = 'Category not exist' ;
// set flash and redirect
redirect('categories/admin_list');
}
// category remain the same
If( $posted_cat_name == $category->name)
{
$error = "No changes made" ;
}
else if( $this->category_model->update($id , $posted_cat_name) == false)
{
$error = 'Error occured updating category' ;
// get the error and log_message() for debuging
}
else
{
$success = true ;
// set flash data and redirect
}
}
// do you need this remaining code? aren't you suppose to redirect back to admin list where the form was posted ?
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
}
}
Here is my code:
<html>
<head>
<script type="text/javascript">
function Change(radio)
{
if(radio.value)
{
setvalue = "Yes";
radiovalue = radio.value;
value = setvalue;
ChangeValue(radiovalue,value)
}
}
function ChangeValue(radiovalue, value)
{
alert(radiovalue+"=>"+value);
}
</script>
</head>
<body>
<?php
for($i = 1; $i <= 3; $i++)
{
?>
<input type="radio" name="choice" value="<?php echo $i;?>" onchange="Change(this);" /><br />
<?php
}
?>
</body>
</html>
There are 3 radio buttons in the web page.
From the above code, when I click the first radio button, it will show alert message for the radio button that I choosen (i.e 1 => Yes).
Yes means that I choose the radio button.
No means that I didn't choose the radio button.
Now my questions is if I choose the first radio button, it will show alert message for each radio button (i.e. 1 => Yes, 2 => No, 3 => No). How should I modify?
In your example, radio.value will be the string "1", "2", or "3". All of these are truthy, so the if block will always run. You need to compare the actual value using a comparison opperator such as == in your if statement.
Example:
if(radio.value == "1")
I cut and pasted your example into a web app and it worked just the way you'd expect - both IE and chrome - so don't know why you're getting strange results. The if(radio.value) simply checks for the existence of a value (javascript thing) and is coded correctly. You might try onchange="return Change(this)" as some browsers may not like the open call.
Plese try this
<html>
<head>
<script type="text/javascript">
function Change(radio) {
for (var i = 1; i < 4; i++) {
var ele = document.getElementById("choice_"+i);
if(ele.checked) {
setvalue = "Yes";
radiovalue = ele.value;
value = setvalue;
ChangeValue(radiovalue,value)
} else {
setvalue = "No";
radiovalue = ele.value;
value = setvalue;
ChangeValue(radiovalue,value)
}
}
}
function ChangeValue(radiovalue, value) {
alert(radiovalue+"=>"+value);
}
</script>
</head>
<body>
<?php
for($i = 1; $i <= 3; $i++) {
?>
<input type="radio" name="choice" id="choice_<?php echo $i;?>" value="<?php echo $i;?>" onchange="Change(this);" /><br />
<?php
}
?>
</body>
</html>
I have a MySQL database of orders that each have various activities associated with them. My PHP/HTML page pulls down the activities when you click an order and allows the user to change attributes of the activities with a form. On submit another PHP file loops through activities in the table and runs an update query on the database. Works great!
I have recently added a JavaScript function that will add activities to the list (appendChild, createElement...). I then added to my PHP file an INSERT query for the new activities.
The problem is that when I run the update PHP file it is not looping through the newly added records that were added with JavaScript. I checked it by using <?php print $size = count($_POST['FcastID']) ?> and the value doesn't change when records have been added.
The records look fine when added to the table and the id and name convention match the other records. It seems like the page needs to be refreshed before the PHP file runs.
PHP file with dynamically created html form
<div id="submit"><form method="post" action="Up_Forecast.php"><input type="submit" value="Submit"></div>
....
<table id="fcast">
<?
$i=0;
while($row = mysqli_fetch_array($res_fcast))
{
echo "<tr id='fcastRow[$i]'>";
echo "<td class='medium'><input type='text' id='qtyJan[$i]' name='qtyJan[$i]' value='".$row[Jan]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyFeb[$i]' name='qtyFeb[$i]' value='".$row[Feb]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMar[$i]' name='qtyMar[$i]' value='".$row[Mar]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyApr[$i]' name='qtyApr[$i]' value='".$row[Apr]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMay[$i]' name='qtyMay[$i]' value='".$row[May]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJun[$i]' name='qtyJun[$i]' value='".$row[Jun]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJul[$i]' name='qtyJul[$i]' value='".$row[Jul]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyAug[$i]' name='qtyAug[$i]' value='".$row[Aug]."'/></td>";
echo "<td class='medium'><input type='text' id='qtySep[$i]' name='qtySep[$i]' value='".$row[Sep]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyOct[$i]' name='qtyOct[$i]' value='".$row[Oct]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyNov[$i]' name='qtyNov[$i]' value='".$row[Nov]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyDec[$i]' name='qtyDec[$i]' value='".$row[Dec]."'/></td>";
echo "<td class='medium'><input type='text' id='Totalqty[$i]' name='Totalqty[$i]' value='".$row[Total]."' disabled/></td>";
echo "</tr>";
++$i;
}
?>
<tr><td class="blank"></td><td class="mini"><input type="button" onclick="addRowYear(this)" value="Add"/></td></tr>
</table>
</form>
</div>
Javascript function to add row
function addRowYear(lastRow){
var rowNo = lastRow.parentNode.parentNode.rowIndex;
var newRow = document.getElementById("fcast").insertRow(rowNo);
newRow.setAttribute("id","fcastRow["+rowNo+"]");
var cell0 = newRow.insertCell(0);
cell0.setAttribute("class","mini");
var input0 = document.createElement("input");
input0.setAttribute("type","text");
input0.setAttribute("name","FcastID["+rowNo+"]");
input0.setAttribute("value","new");
cell0.appendChild(input0);
var cell1 = newRow.insertCell(1);
cell1.setAttribute("class","mini");
var input1 = document.createElement("input");
input1.setAttribute("type","text");
input1.setAttribute("name","Fcast_ActID["+rowNo+"]");
input1.setAttribute("id","Fcast_ActID["+rowNo+"]");
cell1.appendChild(input1);
var curAct = document.getElementById("selAct").innerHTML;
document.getElementById("Fcast_ActID["+rowNo+"]").value = curAct;
var cell2 = newRow.insertCell(2);
cell2.setAttribute("class","mini");
var input2 = document.createElement("input");
input2.setAttribute("type","text");
input2.setAttribute("name","Year["+rowNo+"]");
cell2.appendChild(input2);
var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
for (var i = 0; i < month.length; i++) {
//alert(month[i]);
x=3;
var cell = newRow.insertCell(x);
cell.setAttribute("class","medium");
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("class","numbers");
input.setAttribute("name","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("id","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("onkeyup","findTotal()");
cell.appendChild(input);
x=x+1;
}
var cell15 = newRow.insertCell(15);
cell15.setAttribute("class","medium");
var input15 = document.createElement("input");
input15.setAttribute("type","text");
input15.setAttribute("class","numbers");
input15.setAttribute("name","Totalqty["+rowNo+"]");
input15.setAttribute("id","Totalqty["+rowNo+"]");
cell15.appendChild(input15);
PHP Update - Called on Submit of form
$size = count($_POST['FcastID']);
$i = 0
while ($i < $size) {
$FcastID = $_POST['FcastID'][$i];
$ActID = $_POST['Fcast_ActID'][$i];
$Year = $_POST['Year'][$i];
$Jan = $_POST['qtyJan'][$i];
$Feb = $_POST['qtyFeb'][$i];
$Mar = $_POST['qtyMar'][$i];
$Apr = $_POST['qtyApr'][$i];
$May = $_POST['qtyMay'][$i];
$Jun = $_POST['qtyJun'][$i];
$Jul = $_POST['qtyJul'][$i];
$Aug = $_POST['qtyAug'][$i];
$Sep = $_POST['qtySep'][$i];
$Oct = $_POST['qtyOct'][$i];
$Nov = $_POST['qtyNov'][$i];
$Dec = $_POST['qtyDec'][$i];
$Total = $_POST['Totalqty'][$i];
$update = "UPDATE FCAST SET
Year='$Year',
Jan=replace('$Jan',',',''),
Feb=replace('$Feb',',',''),
Mar=replace('$Mar',',',''),
Apr=replace('$Apr',',',''),
May=replace('$May',',',''),
Jun=replace('$Jun',',',''),
Jul=replace('$Jul',',',''),
Aug=replace('$Aug',',',''),
Sep=replace('$Sep',',',''),
Oct=replace('$Oct',',',''),
Nov=replace('$Nov',',',''),
`Dec`=replace('$Dec',',',''),
Total=replace('$Total',',','')
WHERE
FcastID='$FcastID'";
mysqli_query($link, $update);
Without seeing your code, it is difficult to say. Something I have used in the past that works well is the following:
PHP:
foreach($_POST as $key => $value) {
//... $key is name of field, $value is the value
}
This goes through each individual field in the submitted form and reads the value in each. I've used this exact script for dynamically-created forms, and it works great. You have to be careful, though, if you use the same name for different fields, the values will be stored as arrays.
EDIT
HTML:
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
JavaScript:
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
It isn't all that important to know how the JavaScript code works. All you need to know is that clicking on the "Add" button will duplicate the field and clicking on "Remove" will remove the most recently added field. Try it out at the link provided.
PHP:
This is where the magic happens…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
Looks easy enough, right?
This PHP code is within the same file as the form, so first we check to see if the form has been submitted by checking for the name of the submit button if(isset($_POST['submit'])){…}.
If the form has been submitted, go through each submitted item foreach($_POST as $name => $item){…}.
The submit button counts as one of the fields submitted, but we aren't interested in storing that value, so check to make sure the value you are reading in is not from the submit button if($name != 'submit'){…}.
Finally, all the fields within this form have the same name field_name[]. The square brackets are used for multiple items that share the same name. They are then stored in an array. Read through each item within that array for the length of the array for($m=0; $m < sizeof($item); $m++){…} and then do what you'd like with each value. In this case, I've just printed them to the screen echo ($name.' '.$item[$m].'<br>');
Below are a couple screen-shots of the page…
Before submitting the form:
After submitting the form:
You can go to the page and view the code (right click -> View Source), but the PHP will not show up in the source. I assure you that all the PHP used for this is shown above - just the few lines.
If each item has a completely unique name (which you can achieve via JavaScript when adding fields), then you will not need to loop through the array of values (i.e. will not need for($m=0; $m < sizeof($item); $m++){…} block). Instead, you'll likely read the value using simply $item. If you name your fields with the square brackets (i.e. field_name[]), but only have one of that field, then reading a singular value may require $item or $item[0]. In that case you'll just have to test it and see. Some field types behave differently than others (i.e. input, text area, radio buttons, etc).
The Whole Thing
Here is the entire code for index.php - you can just copy and paste it and run it on your own server. Just make sure to change the name of the file in the action attribute <form> tag…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="../scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
<script>
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
</script>
</html>
I made a number of html forms containing only radio buttons and a submit button. However, I cannot get them to validate properly--independently of each other. Here is my code:
PHP/HTML code for the form:
<table>
<?php
for($i=0; $i<count($array1); $i++)
{
$number = $i + 1;
echo "<TR><TD>;
echo "<form name='move' action='listChange_controller.php' method='POST'>Title:<br/>
<input type='radio' name='change".$number."' value = 'val1' />Thing1
<input type='radio' name='change".$number."' value = 'val2'/>Thing2
<input type='radio' name='change".$number."' value = 'val3'/>Thing3
<input type='button' name='submit' value='submit' onClick='validate(".$number.");'/>";
echo "</form>";
echo "</TD></TR>";
}
?>
</table>
Here is the javascript/jquery I have been trying, but has not worked:
function validate(number)
{
var name_var = 'change'+number;
if($('input:radio[name=name_var]:checked').length > 0)
{
$.post('file.php',{ name_var:$('input:radio[name=name_var]:checked').val()});
}
else
{
alert('You must choose');
return false;
}
}
When I do this, it always thinks I have not chosen a radio button before pressing submit; it always carries out the 'else' part of my javascript function.
Please let me know why it is not working, and what would work. Any help and suggestions appreciated.
This line...
if($('input:radio[name=name_var]:checked').length > 0)
should read
if($('input:radio[name=' + name_var + ']:checked').length > 0)
Change...
if($('input:radio[name=name_var]:checked').length > 0)
to...
if ($('input[name=' + name_var + ']').is(':checked'))