Assistance with Extendable Forms in HTML [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making an online entry form for a martial arts competition. I have got on with everything fine so far. However, there is a part where the user selects how many applicants they wish to input into the competition. The amount that they select will determine the amount of entry rows that come up. I am unsure of how to do this though, would if be possible for any of you geniuses to help me?
Thank you in advance.

From your description, if the end-user selects, say, 8 as the number of people they will be signing up in the competition, the next series of signup elements will correspond with the number of they selected.
Here's my HTML form in my PHP file:
KarateCompetition.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name = "my-form" id = "my-form">
<select name = "number-of-participants" id = "number-of-participants">
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
<option value = "4">4</option>
<option value = "5">5</option>
<option value = "6">6</option>
<option value = "7">7</option>
<option value = "8">8</option>
</select>
<div id = "entry-details-area">
<!-- This is where we'll dynamically insert our rows -->
</div>
</form>
</body>
<!--First, grab jQuery from Google we need this-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--Next, include my logic-->
<script src = "karate.js"></script>
</html>
Next, we'll write our custom logic in "karate.js," and we'll be sure to include that file in our PHP page after we have grabbed jQuery from Google (simply inserting the line shown will dynamically include jQuery in your PHP page)
Here's my jQuery (a Javascript library) logic that I'll use to load the HTML elements dynamically when the user selects a specific number of participants:
karate.js:
//This is my HTML select element "number-of-participants"
var participants_selector = $("#number-of-participants");
//This is where I want to add my dynamic HTML input elements
var entry_details_area = $("#entry-details-area");
//Each time a new value is chosen, grab their number of participants
participants_selector.on("change", function()
{
//Get the number of participants that the end-user has selected
var number_of_participants = participants_selector.val();
//Clear out any previously-appended HTML
entry_details_area.empty();
//Next, create a corresponding number of input elements for the number of participants selected.
for (var i = 0; i < Number(number_of_participants); i++)
{
//Remember: Arrays start counting at 0, so to make it human-readable, add +1
var participant_number = i+1;
//Let's add a simple box: "first-name" for each participant
var entry_form_html = '<p>Participant ' + participant_number + ' first name is: '
+'<input name = "first-name-'+participant_number+'" id = "first-name-'+participant_number+'"></p>';
//Add the HTML for each participant
entry_details_area.append(entry_form_html);
}//end of loop
});//end of on-change listener logic
To test, here's a JSFiddle

You can use jquery do append html code dinamically. It would look like this:
<table id='tableid'>
<tr><td>Name</td><td>Age</td></tr>
</table>
<script>
var x = 5; // user input
for(y=0;y<x;Y++){
$('#tableid').append('<html code here to the other <tr> lines>');
}
</script>

Related

jQuery: second dropdown from array based on value of first dropdown

Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>

Disable dropdown box based on selection of another dynamic dropdown box using php and javascript

I have a list of widths in a dropdown box. They are dynamic because each product has different widths so I've setup the code to look for the minimum and maximum. Then it sets up a dropdown list in increments of 1".
Next to the width are 1/8" increments. So for example you could pick 52 1/8.
If the maximum width is 92 inches let's say, the 1/8 increment dropdown box should disappear or disable because since 92 is max.. you can't pick 92 1/8.
How do I make that 1/8ths box disappear or disable? Here is part of my current code for the dropdown box.
<select name="width_str" id="width_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<?php
$counter = $minwidthRS - 1;
$start = $minwidthRS;
for($start; $start < $maxwidthRS + 1; $start++) {
$counter = $counter + 1;
echo "<option value=".$counter.">".$counter."</option>";
}
?>
</select>
Code for the select dropdown box with 1/8ths that I would like to disable or disappear when MAXIMUM above is selected.
<select name="widthfrac_str" id="widthfrac_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<option value="1/8">1/8</option>
<option value="1/4">1/4</option>
<option value="3/8">3/8</option>
<option value="1/2">1/2</option>
<option value="5/8">5/8</option>
<option value="3/4">3/4</option>
<option value="7/8">7/8</option>
</select>
I'm aware of how to send a selected width value over to a PHP page using AJAX and compare it there, but what do I send back in the success callback? Could I send something that tells the container of that 1/8 measurement dropdown to disable or disappear?
Many thanks! If you need more code let me know. The doCalc() script basically uses AJAX and sends the width to php processing page in order to update price instantly.
EDIT (added more code):
Here is part of my script..
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
Not sure if it helps but I learned a little about using a callback to alter an input field and replacing its value with this: $('input[name=x_login]').val(data.loginid);
It would be great if there was code like that to simply change the other dropdown box disabled=disabled? Does that make sense? I'm still learning programming lingo!
You can call another function with onchange(), which should check the number chosen for the first value. If it is the maximum, then toggle function to hide the second element. A neater solution would be to include the 'check for maximum value and toggle if true' inside doCalc.
Remember to make PHP check also the value, since if user chooses the second value AND then the maximum for the first block, it should hide the second one, but it's value might still be sent.
EDIT:
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
if (roomX == <?php echo $maxwidthRS; ?>)
{
document.getElementById('widthfrac_str').style.display = 'none';
// You also need to make the second element's value 0 within those brackets
}
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
There's no problem putting php within javascript if it's in a .php file. It worked as the OP stated in the comments, great!

Dynamic select list & PHP array

I want to create a PHP array of a select list. The list have dynamic options, the options are filled with the help of javascript. I want to get all the options on next page.
So I want to create an array of options. Is there any another way to complete this stuff?
Can anybody help me out? Thank you so much in advance.
<script type = "text/javascript">
var val = "";
function removeOptions(selectbox) {
val = selectbox.value;
for (var i = selectbox.options.length-1; i>=1; i--) {
if (selectbox.options[i].selected) {
addOption(document.form1.list2,val,val);
selectbox.remove(i);
document.form1.list1.focus();
}
}
}
function addOption(selectbox,optiontext,optionvalue ){
var optn = document.createElement("OPTION");
optn.text = optiontext;
optn.value = optionvalue;
selectbox.options.add(optn);
}</script>
//list1
<select name="list1" size="7" multiple="multiple" id="jumpMenu" onchange="removeOptions(this)" style="width:200px">
<option>Choose Area...</option>
<?php foreach($dbh->query($sql) as $row){
$a=$row['name'];?>
<option value="<?php echo $a?>"><?php echo $a?></option>
<?php }?>
</select>
//list2
<select name="list2" size="7" multiple="MULTIPLE" id="list2" style="width:170px">
</select>
First: if You want to use multiple with select box, then this selectbox's name have to contain sharp brackets: name="list1[]" and name="list2[]" - this way a PHP will know that this is an array of values.
Second: learn jQuery - though it may seem hard in the beginning it will save You a lot of time and browser-compatibility problems in the future. And jQuery will save Your a*s many times in the future.
For Your purpose I would recommend not just using onchange events but implement additional 4 buttons between the two multiselectboxes that will move the selected options from one to another or all from one to another. This kind of multiselect looks like the one pictured below.
By the first button >> all the options from 1. select are moved to the second one and vice versa with the 4th button <<.
By the second button > only the selected option(s) is(are) moved the second select and vice versa with the third button <.
By this You only catch the click event on the buttons... That is really easy using jQuery...

Multiple dynamic selections

I need a way of having multiple selections but only one visible at a time.
When the user wants to add another selection he/she clicks a button,checkbox,radio..whatever
They need to be able to add an unlimited number of selections. Any Ideas?
Old question, but might as well add my 2 cents, in case anyone else wants to know an answer.
I would use JavaScript to create a <select> element in a "more" section, from a JavaScript loop. For example, your first page would have
<input type="button" value="New Select Box" onclick="createNewBox();" /><br />
<span id="selectElement1">
<select>[your code for the select box goes here]</select>
<span id="selectElement2"></span>
</span>
Which could setup your basic select element, and the New Select Box would activate this JavaScript function code:
<script type="text/javascript">
// Initialization Code
var currentSelect = 1; // Keeps track of which select box is current
// New Select Box code
function createNewBox()
{
var currentSelect = currentSelect + 1;
var nextSelect = currentSelect + 1;
document.getElementById('selectElement'+currentSelect).innerHTML = "<select>[code goes here]</select><span id=\"selectElement"+nextSelect+"\"></span>";
}
</script>
This whole thing can run with only those two code snippets, and no jQuery code is needed.

JavaScript DOM dynamc Form from PHP

My MySQL Database Provides A List of Items (and integer IDs with them) in a <select> and a qty field for usage on my web form (with style display: none so it is hidden). But: I want the user to be able to select how many choices of this type he wants to enter in the form - how can I dynamically make multiple selects?
Example: The products in the inventory are oranges, bananas and peaches. There is one select tag:
<select name="p[0]">
<option value="2">Orange</option>
<option value="23">Banana</option>
<option value="31">Peach</option>
</select>
QTY <input type="text" name="qty[0]" />
Now I want to add another dropdown allowing the user to chose between ordering one, two or three classes of products. he could choose 2, and then two copies of the above code are inserted into the DOM so he can enter two product choices and quantities. (the Script would give them the names p[0] and p[1] etc.)
Can anyone help me here?
The simplest thing is to clone the nodes you already have as many times as needed (as opposed to creating new DOM via document.createElement() or innerHTML.
To start, surround your existing <select> and <input> with a div which has a well-known ID. Also, you want to add another DIV to put the repeated inputs into:
<div id="template">
<select name="p[0]"> ... </select>
QTY: <input name="qty[0]"/>
</div>
<div id="copies">
</div>
Now, create a function that will replicate the template some N number of times:
function makeCopies(num) {
var template = document.getElementById('template');
var output = document.getElementById('copies');
// Delete existing nodes.
output.innerHTML = '';
// We start with 1, not 0, because we already have the template.
for (var i = 1; i < num; i++) {
var copy = template.cloneNode(true);
// Change the input names according to index.
copy.getElementsByTagName('select')[0].name = 'p[' + i + ']';
copy.getElementsByTagName('input')[0].name = 'qty[' + i + ']';
output.appendChild(copy);
}
}

Categories