How to use Javascript to validate dynamically generated PHP form? - javascript

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?

This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}

getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;

Related

How to display mysql data through javascript in dynamic form field

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

How to submit a form as well as execute a javascript function in clicking an input button?

This code works, but it shows the heading only for an instant, How we can execute an sql query as well as javascript function to change the innerHTML on a form submission.
//HTML
<div id='heading'> </div>
//form
<form method='post'>
<input type='submit name='option' value='option' onclick='myFunction()' >
</form>
//sql query
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
}
//javascript function
<script>
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
}
</script>
<input type='submit name='option'
Look at your code here. You skip a quote It should be like this <input type='submit' name='option'
As I see your form submitting without AJAX, so once you click "submit" button, the page will be reloaded and return a result of PHP script execution.
If you want to run your "myFunction" before submitting you can do this:
<form id="myForm">
...
</form>
<input type='button' name='option' onclick="myFunction()">
And "myFunction":
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
document.getElementById('myForm').submit();
}
OR, if you want the "heading" div to be shown some time, you can submit the form using timeout:
function myFunction() {
document.getElementById('heading').innerHTML = 'OptionName';
setTimeout(function() {
document.getElementById('myForm').submit();
}, <timeout of submitting in milliseconds>);
}
If my understanding is correct, You want to call the function before the PHP code is executed.
Just change onclick="myFunction()" to onsubmit= "return myFunction()".
It's also a good practice to surrond your document.getElemen.... with a try catch block.
The way you are executing this at the moment isn't going to work. You are posting directly to the same page with your form without AJAX which means the page refreshes. Since JavaScript is client side, it's not going to persist your heading's innerHTML that you set. There are a million and one ways to fix this.
The quickest way to "fix" this is declare what you want the heading to be in your PHP processing and then output that in the H1 element if it exists:
#PHP
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
// Depending on what you want your Heading to be
// $headingName = $_POST['option'];
$headingName = "OptionName";
}
Set your HTML heading like so:
<div id='heading'><?php echo isset($headingName) ? $headingName : '' ?></div>
Also, your input is missing a quotation, and with this change, you don't need the JavaScript portion anymore:
<input type='submit' name='option' value='option'>

First form from many gets submitted on click

Problem: Multiple forms on the same page, but only the first one is being submitted.
Tried the following:
Equating the data-ids of submit button and Form inorder to submit the clicked form (No Luck)
Dynamic form creation using Javascript.(disbanded that idea after a few tries since it was on a deadline)
Usecase
The number of forms depends on the User. If there is just one comment from him, the form submits, while if there are say 4 forms, only the first one will submit.
Javascript:
$(function() {
$(".submit").click(function() {
var data_id = $(this).data('id');
var form_id = $(this.form).data('id');
if (parseInt(data_id, 10) == parseInt(form_id, 10)) {
var commentid = document.getElementByID('commentid');
alert(commentid + formid);
} else {
alert("10");
}
});
});
PHP code:
if($comment['Comment_Username'] ==$this->getUser()->getName())
{$output .='div class="panel" data-class="'.$comment['CommentID'].'">';
$output .='<form class="form" action="" method="post" data- id="'.$comment['CommentID'].'">';
$output .='<textarea name="edit_text' class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
$output .='<input name="commentid" type="hidden" id="commentid" value="'.$comment['CommentID'].'"/>';
$output .='<input type="button' data-id="'.$comment['CommentID'].'" class="submit" value="submit"/>';
Any help would be greatly appreciated.
Thanks in advance
Wrong quote used here
$output .='<textarea name="edit_text" class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';

javascript onchange with 2 different dropdown lists

Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)
Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>
You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function
try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time

onClick function inside a form with submit button causes error

When I use JavaScript button with onClick function inside the form tag in frontend.php, it causes mistake. I need this simple application that does simple job, but it got stuck at this.
I provide you two links. First is within the form tag (frontend.php) and there it doesn't work - ADDMORE BUTTON SIMPLY DOESN'T ADD MORE TEXTAREAS! And the second link is without the form tag, and it works, you can try and submit which will leave you to the welldone.php page.
1.LINK - There is a problem
2.LINK - No form tag, no problem
HTML FORM
<form action="http://www.balkanex.info/dev/frontend.php" method="post">
Title: <br/><input type="text" name="title"><br/><br/>
The question is: <br/><input type="text" name="ask"><br/><br/>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
FRONTEND.PHP FILE
<script>
am = 1;
function more(index) {
am++;
var textarea = document.createElement("textarea");
textarea.name = "answer" + am;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner1").appendChild(div);
}
</script>
<?php
echo '<form action="welldone.php" method="post">';
$content = "";
$title = $_POST['title'];
$question = $_POST['ask'];
if($_POST['ask'] != "") {
$answer = '<textarea name="answer1"></textarea>';
$more = '<button type="button" name="more" onClick="more();">Add more</button>';
$content .= '1) '.$question.'<br/>'.$answer.'<br/><div id="inner1"></div>'.$more.'<br/><br/>';
}
echo $content;
echo'<br/><input type="submit" value="CALCULATE"></form>';
?>
RESULTS WELLDONE.PHP FILE
<?php
echo 'WOW, WELL DONE';
?>
The problem is that, when you use more, browser is uses <button name="more"> instead of function more. Then, you get
TypeError: more is not a function
This behavior is only present in forms, that's why without forms your code works.
You can fix it doing one of these:
Changing function name
Changing button name
Writing unobtrusive javascript, adding the event handler from a <script> element instead ofthe inline onclick attribute.
Anyway, your code is completely invalid and in quirks mode. You should validate it and fix the errors.

Categories