Php Clear textbox when user checks a checkbox - javascript

at the moment I am trying to add some functionality for a user to be able to submit an anonymous suggestion. I am trying to clear a textbox that contains the users name when the user checks the checkbox. However my code does not clear the checkbox when checked. is there a way to clear the checkbox before the form is submitted?
Thanks
<div>
<label style="display: inline-block; margin-left: 10px; letter-spacing: 2px; color: #007A8E;">
<div align="left"><b>Name:</b> </div>
</label>
<div align="left">
<input type="checkbox" style=" margin-left: 110px; outline: 1px solid #0078AE; " name="Anonymous" value="Anonymous" onClick="CheckAnon">
</div>
<label style="margin-left: 2px; color: #0078AE;">
<div align="left">Anonymous</div>
</label>
<div align="left">
<?
function CheckAnon()
{
if(isset($_POST['Anonymous']) == 'Anonymous')
{
$anonFirstName="Anon";
$anonLastName="Anon";
}
else if (isset($_POST['Anonymous']) != 'Anonymous')
{
$anonFirstName = $firstName;
$anonLastName= $lastName;
}
}
?>
</div>
</div>
<div align="left">
<input name="firstname" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E;
border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text"
value="<? echo $anonFirstName?> <? echo $anonLastName?>">
</div>

You can do this at client side using jquery or javaScript.
Assume this text box:
<input type="text" id="fname" />
JavaScript Method:
<script type="text/javascript">
function clearTextBox() {
// Code to clear textbox on Checkbox tick
var textname = document.getElementById("fname"); //get textbox id
textname.value = ""; // clear the textbox
}
</script>

You can do it in PHP as you want.
But, doing it in jQuery is quite simple.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("#Anonymous").change(function(){
if ($(this).is(':checked')) {
$("#firstname").val('');
}
});
});
</script>

You are confusing clientside scripting (JavaScript in your case) with what the server receives (PHP).
The function you call:
onClick="CheckAnon"
Does not exist on the client. Also use: onClick="CheckAnon();"
There are more problems in your code. I advice you to use Firefox and look in the errorlog of javascript. This will help you a lot to trace the bugs.
Also make sure you understand what happens in the client (browser), and the server (after you post a form)
I think you need to clear that up first before you start clearing textboxes with JavaScript)

Related

Check box not working on form before allowed to submit

Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??
<form>
<p>
<input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
</p>
<p>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>
<p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, or javascript, you can easily control if a checkbox group has at least one checked element.
function myFunction() {
document.getElementById("myCheck").required = true;
}
<form action="/action_page.php">
Checkbox: <input type="checkbox" id="myCheck" name="test">
<input type="submit" onclick="myFunction()">
</form>
You can add logic to your clickHandler to check that the box is checked. So instead of calling getRandomImage() directly you add some logic to conditionally call the function.
function clickHandler() {
// get the checkbox element from the DOM
const checkboxElement = document.getElementById('vehicle3');
// see if the checkbox is checked
if (checkBoxElement && checkBoxElement.checked) {
getRandomImage();
} else {
console.log("The checkbox wasn't checked!");
}
}
// add the handler to the button
document.getElementById('generateButton').addEventListener('click', clickHandler);

Clear form after form post

I am trying to do something a little bit tricky.
I am trying to clear my form, inputs especially after I've submitted the form. Whatever, when I am trying to do so. The form clears but the post never executes. I want it do do both, why it is a little tricky is since I am using so I don't have to reload the page after the form post.
<script>
function submitForm() {
$('form[name="cform"]').submit();
$('input[type="text"], textarea').val('');
return;
}
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" onclick="submitForm()" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
Is there even a solution?
Using submit() on its own simply submits the form as if the submit button was pressed with no JS present. Additionally, you'll need to use AJAX for what you're after. Try something like this (adapted from the example on https://api.jquery.com/jquery.post/):
<script>
$('form[name="cform"]').submit(function(e) {
e.preventDefault();
var $form = $( this ),
data = $form.serialize(),
url = $form.attr( "action" );
var posting = $.post( url, data );
posting.done(function( data ) {
$('input[type="text"], textarea').val('');
});
});
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
You'll need to further modify to take into account things like submission failures, but that should get you moving in the right direction. I recommend reading through the documentation at the link listed above for more info on callbacks (e.g. .done() in code above).
submitForm() must return true in order to have the form actually submit.
MKM's answer is correct. To clear all input types on a page, use this instead of $('input[type="text"],textarea').val();
This example clears all inputs in three forms. Tested except for select-multiple.
$(':input','#Form1','#Form2','#Form3').each(function()
{
switch(this.type)
{
case "text":
case "textarea":
case "hidden":
{
this.value = ''; break;
}
case "radio":
case "checkbox":
{
this.checked=false; break;
}
case "select-one":
{
// Set dropdowns to default value
$(this).prop("selectedIndex", 0); break;
}
case "select-multiple":
{
$(this).prop("selectedIndex", 0); break;
}
case "file":
{
$(this).value = ""; break;
}
}
});

document.getElementById JS HTML CSS

I am trying to get my forms NOT TO reset. I am making a <input type="password" /> and whenever I click the button to submit the password, and they get it wrong, I need there to be something that shows that it is incorrect. It works, but only for a split second. Can you help me?
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
margin-top: 220px;
}
#wrg {
visibility: visible;
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="desktop()" id="pass">Sign In</button>
<p id="wrg"></p>
</center>
</form>
The button ends up submitting the form, which causes the window to refresh because there's no action attribute on the form.
You can prevent this by either making the button type="button" (rather than the default submit), using event.preventDefault(), or by returning false, as below. (But as noted in comments below, return false may not be the best approach: it's easy to forget to include the return in both the function and the onclick attribute, without which the form will submit anyway. event.preventDefault is the most explicit and therefore probably best way to handle this.)
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
return false;
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
/*margin-top: 220px;*/
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="return desktop()">Sign In</button>
<p id="wrg"></p>
</center>
</form>
(You do have duplicate pass IDs, which should be unique, and of course clientside authentication as done here isn't the least bit secure, but neither of those issues is directly relevant to your question. getElementById winds up returning the first matching element, which happens to be the one you wanted.)
You are using duplicate IDs for your button and input elements: pass.
Also, it would be easier to just add an event listener to the Sign In button and capture that event inside your function.
document.getElementById("pass").addEventListener('click', desktop);
function desktop(evt) {
evt.preventDefault();
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;");
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
If you do it this way, remember to remove the onclick attribute from the button.

JavaScript only works after refresh

I have an issue. I'm working on the following code. In it, there's a calculator function made with JavaScript. I don't get jQuery yet. It works, but it only does so when I refresh the page. The page is a .php file. I don't know if it's got to do with that or the fact that there is php or database queries in the page, or whatsoever really.
The page is organized in the following fashion:
<div>
<div>
<?php -> catch $_POST values from another page -> some database query(select->echo selected item->turn item into $var) ?>
<div style="background: white; box-shadow: 1px 1px 2px; width: 200px; padding: 10px; float: right; margin-top: -125px; margin-right: -10px; height: 150px;">
<input type="radio" name="opcao" id="opCart" >Cartão<br>
<input type="radio" name="opcao" id="opDin">Dinheiro<br>
<input type="text" id="cholerie" style="width: 70px;" required>
<input type="submit" id="calcular" onclick="calcula()" value="calcular"> Resultado: <p id="resultado"></p>
</div>
<script>
var preco = <?php echo $array[preco]; ?> ;
var pagamento = document.getElementById("cholerie").value;
var troco = Number(preco) + Number(pagamento);
function calcula(){
document.getElementById("resultado").innerHTML = troco;
}
</script>
< some form to catch $_POST values from the database query >
<div> </div>
mysqli_close($conn);
I think the issue is the javascript and its related form.
php only runs when you reload the page. if you need to update page without reloading, you need to use ajax to send asynchronous query to a php page and update your data.
I too feel Dmitry's answer is right, how will you get your live data without reloading the page? You can use AJAX though as he suggested, so go ahead and read on AJAX on google

Submit data from two forms by one independent button and insert data to DB

I'm working on project that is build on Wordpress (I'm using WP because of friendly permissions and rights system) and basically it's written by myself in PHP with a few javascript elements on my own single-pages. Now I need your help. I generate two forms by my PHP script. The template of each form is in MySQL DB table. It's because of friendly editing and administration for each particular row in each form for my not-very-skilled-with-pc collegues that need edit forms without my help. So I have some administration page for forms, collegue makes some changes, save it and script will generate edited form. It works perfectly. Script generate something like below (don't look at messy code, it's only beta without css etc.)
<form id="f1" method="POST" class="form-product-item" style="display: block;">
<fieldset form="f1" name="f1_f">
<legend> FORM 1 </legend>
<table style="width: 320px; max-width: 320px; float: left; margin: 5px">
<tr class="optional f1r1" name="f1r1_v" style="display: block;" >
<td style="width: 120px; min-width: 120px; max-width: 120px; height: 48px; max-height: 48px;">
<div class="optional f1r1" name="f1r1_v" style="display: block;" class="hidden-txt">Row 1 Form 1: </div>
</td>
<td style="width: 140px; min-width: 140px; max-width: 140px">
<input type="text" class="optional f1r1" name="f1r1_v" style="display: block;" class="hidden-txt" placeholder="Row 1 Form 1" size="15" />
</td>
<td style="width: 60px; max-width: 60px; max-width: 60px">suffix</td>
</tr>
</table>
<div style="clear: both"></div>
</fieldset>
<form id="f2" method="POST" class="form-product-item" style="display: block;">
<fieldset form="f2" name="f2_f">
<legend> FORM 2 </legend>
<table style="width: 320px; max-width: 320px; float: left; margin: 5px">
<tr class="optional f2r1" name="f2r1_v" style="display: block;" >
<td style="width: 120px; min-width: 120px; max-width: 120px; height: 48px; max-height: 48px;">
<div class="optional f2r1" name="f2r1_v" style="display: block;" class="hidden-txt">Row 1 Form 2: </div>
</td>
<td style="width: 140px; min-width: 140px; max-width: 140px">
<select id="f2r1_dm" name="f2r1_v" style="width: 120px">
<option selected>- Choose -</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
<td style="width: 60px; max-width: 60px; max-width: 60px">suffix</td>
</tr>
<tr class="optional f2r2" name="f2r2_v" style="display: block;" >
<td style="width: 120px; min-width: 120px; max-width: 120px; height: 48px; max-height: 48px;">
<div class="optional f2r2" name="f2r2_v" style="display: block;" class="hidden-txt">Row 2 Form 2: </div>
</td>
<td style="width: 140px; min-width: 140px; max-width: 140px">
<input type="text" class="optional f2r2" name="f2r2_v" style="display: block;" class="hidden-txt" placeholder="Row 2 Form 2" size="15" />
</td>
<td style="width: 60px; max-width: 60px; max-width: 60px">suffix</td>
</tr>
<div style="clear: both"></div>
</table>
</fieldset>
Now I want to ask you friends, how to make one independent submit button below "FORM 2" (outside from form tags) that submit values from all fields from both forms at once and insert it to DB. I tried some advises I found here on stackoverflow but they did not work for me.
I'm quite begginer with PHP and Java, AJAX I know very cursorily. So, for some advice or step by step tutorial I'll be very appreciate.
Thank you very much for any help ;).
This is as close as I can get to:
Add a button outside the forms at the end:
<input type="button" name="submit" id="submit" value="submit">
You will need to add this library:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
And then what we do is, when the user clicks on submit, we will clone all the other form elements along with its values onto your first form and submit it. This way, while on submit, all your form values will be passed from the first form.
<script type="text/javascript">
jQuery("#submit").click(function(e){
$first_form = $("form").attr('id');
$("form").each(function() {
$('#'+this.id + ' :input').not('#'+$first_form).clone(true).appendTo('#'+$first_form);
//getting all the selected options
var selects = $('#'+this.id).find("select");
$(selects).each(function(i) {
var select = this;
$('#'+$first_form).find("select").eq(i).val($(select).val());
});
//getting all the textarea values
var textareas = $('#'+this.id).find('textarea');
$(textareas).each(function(i) {
var textarea = this;
$('#'+$first_form).find("textarea").eq(i).val($(textarea).val());
});
});
$('#'+$first_form).submit();
});
</script>
On the PHP that the form is being submitted to, you can do a var_dump($_POST); to see if you have received all the values correct.
add a button outside the forms and and in it's onclick call a function say submitAll
window.onload = init;
function init() {
document.forms[0].addEventListener('onsubmit',
function{document.forms[1].submit();});
}
function submitAll(){document.forms[0].submit();}

Categories