onClick function inside a form with submit button causes error - javascript

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.

Related

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>';

How to use Javascript to validate dynamically generated PHP form?

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;

Get the value of a hidden input in server side Php which was set by javascript

This wordpress stuff driving me mad again.
I have an output page which uses a short code to call a function (Stores)... the code of which in part is beneath.
It has a dropdown and a table of data, ..the data being dependant on the selected option of the drop down.
I use javascript to set the hidden input...successfully.
In fact I tried a normal, non hidden input as well...same result,..on server side, with$_POST["txtSelection"] or
$_POST["hdnSelect"]
But when I try get it's value on the php server side code, it is empty,..
How on earth do I retrieve it?
the hidden input is inside the form tag.
<?php
function Stores()
{
global $wpdb;
global $MyPage;
$MyPage = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
?>
<form name="frmSB_stores" method="post" action="<?php echo $MyPage ?>">
<input type="hidden" name="hdnSelect" id="hdnSelect" value="">
<input type="text" name="txtSelection" size="19" id="txtSelection" value="">
<script type="text/javascript">
function SetDDLValueOnChange (objDropDown) {
var objHidden = document.getElementById("hdnSelect");
if ( objDropDown.value.length > '0')
{
objHidden.value = objDropDown.value; //.substr(0,1);
//alert(" hdn = " + objHidden.value);
window.location = '<?=$MyPage;?>' ;
}
}
</script>
the dropdown's markup here,..then
<table width='100%' border='0' cellspacing='5' cellpadding='3'>
<?php
$Area = $_POST['txtSelection']; //or $_POST['hdnSelect']
which has zilch in it , even though it is set successfully by jvascript
Why is this such an issue in WordPress,
How do i overcome it.
It's nuts spending a full day on something which should be so trivial (works fine in a normal php situation, os asp or asp.net,..but not in WP.)!
TIA
N
This doesn't submit the form it just tell the browser to goto that page. Hence your value always empty.
window.location = '<?=$MyPage;?>' ;
Replace that line with this instead.
document.forms["frmSB_stores"].submit();

How to color HTML elements based on parsing a user command string

I'm working on a little parsing thing to color objects.
For an example, you could type red:Hi!: and "Hi!" would be red.
This is my not working code:
<script type="text/javascript">
function post()
{
var preview = document.getElementById("preview");
var submit = document.getElementById("post");
var text = submit.value;
<?php str_replace("red:*:",'<i class="red">*</i>',text); ?>
preview.value = text;
}
</script>
You have at least two massive problems here.
You can't str_replace with wildcards like you are (the asterisks you use are just that - the asterisk character, not a placeholder).
Your idea of the page-rendering process is off - you can't just call some PHP code in JavaScript and have it update the page. Any PHP code will be executed and printed when your page is generated on the server - it can't interact with the page like JavaScript can (JS can because it is executed within the browser, but the browser never actually sees your PHP code as you can check by going to View->Source and seeing what you see). You certainly cannot reference a JavaScript variable from PHP.
Two options.
Option 1 - Proper Server-Side
if you want to colour objects on page load based on post, do something like this:
<?php
# If the value was posted
$raw = isset($_POST['userstring']) ? $_POST['userstring'] : "";
# Split it based on ':'
$parsed = explode(':', $raw);
$colorClass = "";
$text = "";
if (count($parsed) >= 2)
{
$colorClass = $parsed[0];
$text = $parsed[1];
}
?>
<form action="" method="post">
<input type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
<?php if (strlen($text) > 0) { ?>
<i class="<?php echo $colorClass; ?>">
<?php echo $text; ?>
</i>
<?php } ?>
</div>
Option 2 - Proper Client-Side
Include jQuery in your <head> tag to make your life easier. If you really don't want to include jQuery you can still change the jQuery calls to your getElementById etc. (you'll want to replace the html() call with '.innerhtml' I think - just look it up).
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
function post() {
var split = $('#userinput).val().split(separator, limit)
if (split.length >= 2) {
var color = split[0];
var text = split[1];
$('#preview').html('<i class="' + color + '">' + text + '</i>');
}
return false; // Stop form submit
}
</script>
<form action="" method="post" onsubmit="post()">
<input id="userinput" type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
</div>
</body>
You're mixing server and client side technologies here. The code in the php lock is evaluated once (while still on the server). You're looking for something that will operate entirely on the client side.
This means you need to look into Javascript regular expressions, instead of PHP preg_match type stuff.
http://www.regular-expressions.info/javascriptexample.html
You're looking for this type of thing:
stringObject.replace( regularExpressionVarOrLiteral, replacement );
Josh

Categories