I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.
Related
I am still working on my school project, which is almost finished.
With your help, I successfully created a working system that allows users to write, edit and delete data to/from the database.
The only problem I have right now us "user-friendly form." I managed to create auto-focus, insert correct values on edit so the user can see what was previously written in that field, etc.
I have my forms hidden with jquery. When a user clicks add, the form slides in. What I need to achieve is: "when a user clicks submit and the page refreshes and adds the element to the database, the form should appear again so users can add data faster."
Here is my code.
$(document).ready(function() {
$('#x').click(function() {
$('.y').toggle("slide");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="x">Click</div>
<div class="y" style="display: none;">
<div class="container">
<form action="insertzunanja.php" method="POST" id="x">
<input type="hidden" name="narocilo" value="0.1412312">
<input type="hidden" name="id" value="id-1">
<input type="text" name="dolzina" style="width:49%;" placeholder="Dolzina (v cm)">
<input type="text" name="sirina" style="width:49%;" placeholder="Sirina (v cm)">
<input type="text" name="kolicina" value="1" style="width:49%;" placeholder="Kolicina">
<input type="text" name="opombe" style="width:49%;" placeholder="Opombe">
<input type="submit" value="Send">
</form>
</div>
</div>
Thanks and best regards.
You can use AJAX call to send the data to php file instead of form action. According to your code you will have something like this:
<div id="x">Dodaj</div>
<div class="y" style="display: none;">
<div class="container">
<input type="hidden" name="narocilo" value="<?php echo $randomNum; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="dolzina" style="width:49%;" placeholder="Dolzina (v cm)">
<input type="text" name="sirina" style="width:49%;" placeholder="sirina (v cm)">
<input type="text" name="kolicina" value="1" style="width:49%;" placeholder="Kolicina">
<input type="text" name="opombe" style="width:49%;" placeholder="Opombe">
<input id="sub" type="submit" value="Send">
</div>
</div>
$(document).ready(function(){
$('#x').click(function() {
$('.y').toggle("slide");
});
});
$("sub").click(function(){
$.post("insertzunanja.php",
{
dolzina: $("input[name=dolzina]"),
sirin: $("input[name=sirina]")
},
function(){
$("input[name=dolzina]").val("");
$("input[name=sirina]").val("");
if($('.y').is( ":hidden" )) {
$('.y').toggle("slide");
}
});
});
Basically, when you click on button you call php with AJAX POST request passing two values dolzina and sirin retrieved by the html code(note: you have more values to pass so change it accordingly) to php file. Jquery deletes the values of the input fields and check if input fields are shown. If not the inputs fields are shown.
If you are using PHP to process the form submission and generate the code in your question, and you always want the form to be displayed after submission, you can do this:
At the PHP code identify submission (e.g. isset($_REQUEST['id']) ).
[if #1 is true] On generating jQuery code, add $('.y').show(); within the ready function (but separated from the existing click function).
Example:
<?php
// your existing code...
?>
$(document).ready(function() {
<?= ( isset($_REQUEST['id']) ? '$(".y").show();' : '' ); ?>
$('#x').click(function() {
$('.y').toggle("slide");
});
});
<?php
// your existing code...
?>
<script>
$(function () {
$("input:checkbox").click(function () {
if ($(this).is(":checked")) {
var id = $(this).attr('id');
if (id) {
$("#txtPassportNumber").removeAttr("disabled");
$("#txtPassportNumber").focus();
}
} else {
$("#txtPassportNumber").attr("disabled", "disabled");
}
});
});
</script>
This is my jquery code am getting one textbox enabled by this
<label for="chkPassport">
<?php
$select_size = $common->select('size_m', '');
$i = 0;
foreach ($select_size as $sizes) {
$s = $sizes['sizename'];
?>
<input type="checkbox" id="chkPassport<?php echo $s; ?>" class="current"/>
<?php echo $sizes['sizename']; ?>
</label>
qty:
<input type="text" id="txtPassportNumber<?php echo $i;?>" disabled="disabled" class="current<?php echo $s; ?>"/>
<br/>
<?php
$i++;
}
?>
I am not getting id of textbox even i am giving
id="txtPassportNumber<?php $i; ?>"
I am having 5 sizes and on every size i want to add qty when i click S i want to enable its textbox when i click M its textbox must enable.I am getting one textbox enabled onclick of size S because it is not taking my id there.Help me for this
You're asking to solve the selection problem so here is a small 'JQuery' code.
I wonted to explain what I've done with the below code. In your code you were trying to use the ID of the element you wanted to change. The problem is ID's need to be unique for each element if you have the same ID for all then all those elements will be considered as one.
Also you were trying to assign a number to the ID (id="txtPassportNumber<?php echo $i;?>") which makes it double hard to identify.
So what I did in my code is to move the listener from ID to class which makes it easier and free up the ID for you to do what ever you want with it. In the script the JQuery listens to see if there's a click event on the .sizeChk class if it's true then it checks if the click event is to check the check box or not. Then if the check box is checked then it looks for the input .next() to the checked check box.
I used .next() because the input is on to the right hand side if the input was to the left hand side you can use .prev(). After finding the input next to the check box it applies the .prop(). I didn't use .attr() because it's old and not encouraged by JQuery it self.
You only have to keep the class in tact and you can use the same class to any other check box to get the same function on those elements.
A side note: It's best you read up on JQuery a little bit more.
Older Answer which match the description.
$(document).ready(function() {
$('.sizeChk').click(function() {
if ($(this).is(':checked')) {
$(this).next("input").prop('disabled', false).focus();
} else {
$(this).next("input").prop('disabled', true);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk1" class="sizeChk" />Small:
<input type="text" id="txt1" class="sizeTxt" disabled/><br><br>
<input type="checkbox" id="chk2" class="sizeChk" />Medium:
<input type="text" id="txt2" class="sizeTxt" disabled/><br><br>
<input type="checkbox" id="chk3" class="sizeChk" />Larg:
<input type="text" id="txt3" class="sizeTxt" disabled/><br><br>
<input type="checkbox" id="chk4" class="sizeChk" />xLarg:
<input type="text" id="txt4" class="sizeTxt" disabled/><br><br>
<input type="checkbox" id="chk5" class="sizeChk" />xxLarg:
<input type="text" id="txt5" class="sizeTxt" disabled/>
New updated code
$(document).ready(function() {
$('.sizeChk').click(function() {
if ($(this).is(':checked')) {
$(this).closest('.sizeGroup').find('input[type=text]').prop('disabled', false).focus();
} else {
$(this).closest('.sizeGroup').find('input[type=text]').prop('disabled', true);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sizeGroup">
<input type="checkbox" id="chk1" class="sizeChk" />Small:<br>
<input type="text" id="txt1" class="sizeTxt" disabled/><br><br>
</div>
<div class="sizeGroup">
<input type="checkbox" id="chk2" class="sizeChk" />Medium:<br>
<input type="text" id="txt2" class="sizeTxt" disabled/><br><br>
</div>
<div class="sizeGroup">
<input type="checkbox" id="chk3" class="sizeChk" />Larg:<br>
<input type="text" id="txt3" class="sizeTxt" disabled/><br><br>
</div>
<div class="sizeGroup">
<input type="checkbox" id="chk4" class="sizeChk" />xLarg:<br>
<input type="text" id="txt4" class="sizeTxt" disabled/><br><br>
</div>
Hope this help.
Here is the old jsFiddle.
Here is the updated jsFiddle
How to get value from checkbox or radio button immediately after clicking on it and write it in textfield without using reset or submit button?
<input type="checkbox" name="age" value="21-29">21-29 <input type="text" name="yourAge" value="">
You can do like this with jQuery click function More Detail Here
<input type="checkbox" name="age" value="21-29" id="age">21-29
<input type="text" name="yourAge" value="" id="yourAge">
JQuery
$("#age").click(function () {
$("#yourAge").val($("#age").val());
});
Fiddle
#Shehary is on point but there is always room for more.
JS
<script>
var changeInput = function (val){
var input = document.getElementById("age");
input.value = val;
}
</script>
HTML
<input type="checkbox" name="age" value="21-29" onclick='changeInput(this.value);' >21-29
<input type="text" name="yourAge" value="" id="age">
Pen
I know this is old, and my code may not be great, but I like to use this.
<?php
$get= "?checked";
$checked= "";
if(isset($_GET['checked'])){
$get= "";
$checked= "checked";
}
?>
<a href="waiting_in_db.php<?=$get?>">
<input type="checkbox" <?=$checked?> >
</a>
But I prefer using CSS and links without the checkbox.
I have a problem, I need to associate a input type checkbox to a input type text.
The situation is as follows:
Extract data from a database. The PK data are the value of the checkbox. When a checbox select an input type text where you can enter a specific number is activated.
Now the problem is that selecting a checkbox input text all kinds are activated. And what I hope is that by selecting the checkbox input only the input associated with the checkbox enabled.
My HTML code (This code creates a input checkbox and input text for each record in the database, and what I want is to activate a specific checkbox is activated, the input type text):
<form action="send.php" method="POST" id="form-touch">
<?php foreach ($data as $key): ?>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="<?php echo $key['pr_id'] ?>">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<?php endforeach; ?>
<input type="submit" value="Send">
</form>
My jquery code (code that activates or deactivates the text field by selecting a checkbox):
$('.id-check').change(function(){
if ($('.id-check').is(':checked') == false){
$('.myinput').val('').prop('disabled', true);
} else {
$('.myinput').val('1').prop('disabled', false);
}
});
How I can achieve what I want? Greetings from Chile.
Try
$('.id-check').change(function() {
if ($(this).is(':checked') == false) {
$(this).closest('div').find('.myinput').val('').prop('disabled', true);
} else {
$(this).closest('div').find('.myinput').val('1').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="send.php" method="POST" id="form-touch">
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="1">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<input type="submit" value="Send">
</form>
you can use .next() jQuery selector. I have modified your jQuery change handler below. It works for me so try it. It should work for you too.
$('.id-check').change(function(){
if ($(this).is(':checked') == false){
$(this).next().val('').prop('disabled', true);
} else {
$(this).next().val('1').prop('disabled', false);
}
});
Goodluck and happy coding! :-)
I have no idea about how javascript works, but I was able to write the following code by copying from different sites.
My aim is to have 2 radio boxes (1 = India, 2 = Other than India) and if Other than India is selected, then a dropdown box is displayed which shows names of all countries.
The dropdown is selected from a database and it is achieved by a custom php function.
I am able to make the code display the dropdown based on my radio box selection.
What I am unable to do is as follows:
I am not able to select any values from the dropdown.
I'm not able to make the dropdown hide if I change the choice in the radio box
Here is the code of the form:
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<br />
<script type="text/javascript">
function onclickradio(entry){
if (entry === true) {
alert("YOU HAVE CHOSEN INDIA");
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '</br><?php dropdown('country');?>';
}
}
</script>
Country: </br>
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="INDIA" name="country" type="radio" checked="checked"/> INDIA
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="OTHER THAN INDIA" name="country" type="radio"/> OTHER THAN INDIA
<br /><br /><br />
State: <input type="text" name="State" maxlength="30"/><br />
Line1: <input type="text" name="Line1" maxlength="50" /><br />
Line2: <input type="text" name="Line2" maxlength="50" /><br />
City: <input type="text" name="City" maxlength="40" /><br />
PIN Code: <input type="text" name="PIN_Code" maxlength="8" /><br />
<input type="submit" name="submit_address" value="Submit Address" />
</fieldset>
</form>
Here is the code for the custom PHP dropdown function:
<?php
function dropdown($tablename) /*remember to add single quote around the input*/
{
$sql="SELECT * FROM ".$tablename;
$result=mysqli_query($GLOBALS["connection"], $sql)
or die('Error in running SELECT query');
$options=""; //initialising the variable, so that it can be concatenated later
while ($row=mysqli_fetch_array($result))
{
$x=0; /*$x is the index of the field in a row (it has to start with $x=0;
because the first index is 0 in php*/
$rowstr=" # "; /*initialising the variable,
so that it can be concatenated later*/
while ($x+1<=mysqli_num_fields($result)) /*mysqli_num_fields gives the actual number of fields, and not the index.
Since the index starts with 0, it is to be incremented by 1
before comparison with the mysqli_num_fields*/
{
$rowstr.= $row[$x]." # "; //concatenation operator
$x=$x+1;
}
$options.="<option value=".$rowstr.">".$rowstr."</option>"; //concatenation operator
}
Echo "<select>".$options."</select>";
}
?>
A few things that come to mind:
Don't put spaces in id values. I recommend that you use lower case as well, so you could have "india" and "not-india" instead.
Use Firefox/Firebug or similar to see if you have any JavaScript errors when you run this
Consider using jQuery or similar to catch change events - it is easy to use and uses the 'unobtrusive' method of adding JS functionality to your page.
Id field of an element can not have space. Just try removing spaces in "OTHER THAN INDIA" or replace to looks like OTHER_THAN_INDIA
Try this:
$(document).ready(function() {
// hide address inputs
$('#address').hide();
// show address inputs if the not india button is pressed
$('#not-india').click(function() {
$('#address').show();
});
// re-hide address inputs if india is selected
$('#india').click(function() {
$('#address').hide();
});
});
You will also have to include jQuery in your page.
Fiddle: http://jsfiddle.net/EN4jB/6/
Please note that I used the following markup - particular attention is due to the id of this div.
<input id="india" name="country" type="radio" checked="checked"/> India
<input id="not-india" name="country" type="radio" /> Not India
<br />
<div id="address">
<p><select>
<option>USA</option>
<option>UK</option>
<option>Ireland</option>
<option>etc...</option>
</select>
</p>
<p>State: <input type="text" name="State" maxlength="30"/></p>
<p>Line1: <input type="text" name="Line1" maxlength="50" /></p>
<p>Line2: <input type="text" name="Line2" maxlength="50" /></p>
<p>City: <input type="text" name="City" maxlength="40" /></p>
</div>
To clear the selection if India is chosen
function onclickradio(entry) {
if(entry===true) {
alert("YOU HAVE CHOSEN INDIA");
document.getElementById('OTHER THAN INDIA').innerHTML = '';
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '<br/><?php dropdown('country');?>';
}
}