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;
}
}
});
Related
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);
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.
In my HTML, I have a normal form. The form takes inputs and submits. The user will then click a button called "#addOne". This button, using jQuery, appends a cloned form to the previous form. Each form is numbered, and each form is one less than its previous. The numbers will be used in my SQL WHERE clause. I want the cloned forms to be separate forms, For example, if I enter values for form 9 and click submit, and then enter values for form 8 the information won't collide with each other. Form 8's button should not submit for all the other forms.
Here's my jsFiddle: https://jsfiddle.net/2c2xL0cz/
HTML:
<div class="article_properties">
<form class="article_properties_form" action="" method="POST" enctype="multipart/form-data">
<p style="display: inline">Page Number</p><div style="background-color: #FF355E; padding: 5px; display: inline; margin-left: 5px"<p class="pageNumber"></p></div>
<textarea style="display: none" class="inputNumber" name="pageNumber"></textarea>
<p>Image</p>
<input type="file">
<p>Subtitle</p>
<input type="text" name="subtitle">
<p>Text</p>
<textarea name="text" rows="4"></textarea>
<input id="properties_btn" type="submit" value="Submit/Update">
<hr style="border: 1px dotted lightgray; margin-bottom: 50px">
</form>
<div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"><p style="text-align: center; line-height: 25px">+</p></div>
</div> <!--End of article properties div-->
jQuery/Ajax:
var numPages = 10;
$('.pageNumber').text(numPages);
$('.inputNumber').text(numPages);
$('#addOne').click(function()
{
numPages--;
var articlePropsTemplate = $('.article_properties_form:last').clone();
$('.article_properties_form').append(articlePropsTemplate);
$('.pageNumber:last').text(numPages);
$('.inputNumber:last').text(numPages);
});
$('.article_properties_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
}
});
});
Also, I do not wish to refresh the page when the form submits. For some reason, the dynamically created forms are creating page refresh when the submit button is clicked. There's also a solution in creating a div outside of the form elements, but this technique is making the forms think they're one form, but they should be separate forms all submitting to their respective pageNumbers.
Change this line
$('.article_properties_form').append(articlePropsTemplate);
To the below one
$('.article_properties').append(articlePropsTemplate);
Right now you are appending the new form with in the old form. So the data will get collide. You have to append the form outside the old form. So append the new form to the old form's parent
For prevent page reload of new forms
$('body').on('submit','.article_properties_form', function(e) {
//Your code
});
Or
$(document).on('submit','.article_properties_form', function(e) {
//Your code
});
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)
In my MVC application have included a button called form Field. whenever user clicks on that button dropdownlist gets displayed in modal box that contains text, checkbox etc as option.
code for form field and drop downlist:
<input type="button" id="FormField" name="Form Field" value="Form Field" style="width: 110px; height: 30px; background-color: #FFFFFF;" onclick="return FormField_onclick()" />
function FormField_onclick(box) {
dhtmlx.modalbox({
title: "Form Field Creation Tool",
text: "<div id='form_in_box'><div ><label>Type: <select id='Type' name='Type'><option>Text</option><option>Checkbox</option><option>Radio</option><option>DropDown</option><option>Listbox</option></select></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Select' style='width: 86px' onclick='Select_type(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
Whenever user selects particular option from dropdownlist for example if user selects text option and clicks Select button than textbox should get inserted at cursor position.
code for select button:
function Select_type(box) {
var tp = document.getElementById('Type');
switch (tp) {
case "text":
{
var editor = CKEDITOR.instances.message;
editor.insertHtml('<input type="text" id="tx" name="tx" style="width: 110px; height: 30px" />');
}
break;
case "Checkbox": { var editor = CKEDITOR.instances.message;
editor.insertHtml('<input type="checkbox" id="chk" name="chk" value="Checkbox" style="width: 110px; height: 30px" />');}
break;
case "Radio":
{
var editor = CKEDITOR.instances.message;
editor.insertHtml('<input "radio" id="rd" name="rd" value="radio" style="width: 110px; height: 30px" />');
}
break;
case "DropDown": alert("DropDown");
break;
case "Listbox": alert("Listbox");
break;
}
dhtmlx.modalbox.hide(box);
}
but this doesn't work for me. Even the alert doesn't work. And also don't know how can i include dropdown and list in it
You want to do the switch on:
document.getElementById('Type').value
and not on the element it self, as it doesn't equals none of the cases you provided.
You could use an object literal for the switch statement if you wanted to...
var sw = {
hello: function () {
console.log("hello");
},
goodbye: function () {
console.log("goodbye");
}
}
var str = "hello";
sw[str](); //logs hello
Heres an explanation: http://www.dyn-web.com/tutorials/obj_lit.php
I think you need to clarify your question though and tag it appropriately...