I'm looking to use onClick="return confirm('are you sure ?')" to get users to confirm what they are submitting.
Basic form is:
<form>
<Select name='val[]' class='select'><option></option><option value='a'>a</option><option value='b'>b</option><option value='c'>c</option><option value='d'>d</option></select>
<Select name='opt'><option>AAA</option><option>BBB</option><option>CCC</option></select>
<input type='submit' name='submit' value='submit' onClick="return confirm('are you sure ?')">
</form>
When they click submit how do I update the return confirm to show the values they have selected from the dropdown lists?
edit:
I should have mentioned this page is using the Jquery Chosen script from http://harvesthq.github.io/chosen/
The first option is a multiselect and is using chosen to make it look nicer.
The suggestion from dishwasherWithProgrammingSkill works but doesn't show the multivalues selected.
Anyway to do that ?
Update:
Using : var opt3=$('#opt1').val();
Returns me a comma separated list. How do I remove the commas ?
Thanks
I think this is what you are looking for.
<form>
<select name='val' class='select' id='opt1'>
<option></option>
<option value='a'>a</option>
<option value='b'>b</option>
</select>
<select name='opt' id='opt2'>
<option value='AAA'>AAA</option>
<option value='BBB'>BBB</option>
</select>
<input type='submit' name='submit' value='submit' onClick="return function1();">
</form>
<script type='text/javascript'>
function function1(){
var opt1=document.getElementById("opt1").value;
var opt2=document.getElementById("opt2").value;
var response=confirm("Are you sure? option1="+opt1+" option2="+opt2);
return response;
}
</script>
UPDATE
Since you already got the values by using var opt3=$('#opt1').val(); the rest is easy, use the split() function in javascript. It is similar to the explode() function in php.
here is the sample.
var opt3=$('#opt1').val();
var valArray=opt3.split(","); //The parameter determines where you want to split.
for (var i = 0; i < valArray.length; i++) {
alert(valArray[i]);
}
You will have to write a function for it. Using jquery you can use $(form).submit(function(){}); to pull your values in on submit, show the confirm dialog and set the content.
Let me know how you do!
http://api.jquery.com/submit/
It would be best to separate your javascript from your form, and add an event listener. But, if you still want to use onclick you could add an id to each of your form elements, and get the value using getElementById() -
<form>
<select name='val[]' id='val' class='select'><option></option><option value='a'>a</option><option value='b'>b</option><option value='c'>c</option><option value='d'>d</option></select>
<select name='opt' id='opt'><option>AAA</option><option>BBB</option><option>CCC</option></select>
<input type='submit' name='submit' value='submit' onClick="return confirm('are you sure? val='+getElementById('val').value +' opt='+getElementById('opt').value)" />
</form>
see this jsFiddle example - http://jsfiddle.net/rpcBS/
You will need to listen for onSubmit() and not onClick()
<form onSubmit="return confirm('are you sure?);">
<Select name='val[]' class='select'><option></option><option value='a'>a</option><option value='b'>b</option><option value='c'>c</option><option value='d'>d</option></select>
<Select name='opt'><option>AAA</option><option>BBB</option><option>CCC</option></select>
<input type='submit' name='submit' value='submit'>
</form>
onClick will not stop the form from submitting.
Related
I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
How do I make it so that the insertion of HEADING remains permanent?
Move the listener to the form's submit handler. Have the function return false to stop submission:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
<input type="submit">
Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
There is an error in your code, it's missing a closing double qoute:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.
I have a form that I want to submit, and I don't know the best way to call the form.
This is my HTML
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" /><input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil()" />
</form>
Now the Javascript, I included jQuery.
function submitFormInfoEtatCivil() {
var update = "index.php/rh/updateinfo";
var dataString = $( this ).serialize();
// dataString return <empty string>
jQuery.ajax({
});
}
I have many forms with ids : form1, form2, form3 ...
My problem is how to specify the fonction submitFormInfoEtatCivil() to get the form where button is submitted. I used $( this ).serialize() but I am wrong because the output is empty.
You can pass this inside function and then use .closest("form") to get input datas from form where button has been clicked.
Demo Code :
function submitFormInfoEtatCivil(el) {
var update = "index.php/rh/updateinfo";
//use closest to get form where button is clicked
var dataString = $(el).closest("form").serialize();
console.log(dataString)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>
<form id="form" name="form">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>
$(this) that you use refers to button and you are getting empty string when you are serialize() a button.
I strongly recommend an another solution for this problem; you can catch the form when it is submitted with the on() function;
$('form').on('submit',function(){
var thiz = $(this);
var update = thiz.attr("form-url"); //get update url from the form as an attiribute or define it staticly.
var dataString = thiz.serialize();
return false; //to prevent original form action.
});
When you use above code snippet you can remove onclick="submitFormInfoEtatCivil(this)" from your code and also if you want to deep dive with on() function, you can find here an documentation.
I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;
How do I reset the form fields more elegant compared to the code below? The code is working. But if I have lots of form fields it does not look so nice. Is there a more compact way?
<script>
function setSearchCriteria(){
var searchcriteria = document.getElementById("TherapistSearch-SearchCriteria");
searchcriteria.value = "";
}
function setCity(){
var city = document.getElementById("TherapistSearch-City");
city.value = "";
}
function setLastName(){
var lastname = document.getElementById("TherapistSearch-LastName");
lastname.value = "";
}
function setFirstName(){
var firstname = document.getElementById("TherapistSearch-FirstName");
firstname.value = "";
}
}
</script>
<input type="button" class="btn btn-default" value="Reset form"
onclick="javascript:clearForms();javascript:setSearchCriteria();setCity();setLastName();setFirstName();" title="Reset form"/>
Give a css class to your input fields.
<input type="text" id="firstName" class="resettable" />
<input type="text" id="firstName" class="resettable" />
<select id="states" class="selectResettable">
<option value="0">Select an option </option>
<option value="1">Michigan</option>
<option value="2">Ohio</option>
<select>
<input type="button" id="resetBtn" />
And use this css class(es) as jQuery selector(s) to get all of this inputs and set the value to empty/default value. I also removed the onclick from button HTML markup as we are going to do it in the unobtrusive javascript way.
Add this javascript where we are registering the code for the click event on our button.
$(function(){
$("#resetBtn").click(function(e){
alert("Reset button clicked");
//Set the input text fields to empty string
$("input.resettable").val("");
//Reset the dropdowns.
$(".selectResettable").val("0")
//If you want to do something else, Do it here.
});
});
Simply use HTML the way it's meant to be used, and take advantage of the reset button:
<input type="reset" class="btn btn-default" value="Reset form" title="Reset form"/>
This requires no JavaScript, no additional functionality, and is a native component of HTML forms. Using type="button" gives the element the appearance of a button, but strips the default functionality; using type="reset" gives the appearance of a button and gives the default functionality of resetting the parent <form> element to its default page-load state.
References:
<input> element type attribute-values.
<input type="reset" id="resetBtn" class="resettable" />
use reset type of button or call reset method on form as below
<input type="button"
class="btn btn-default"
value="Reset form"
onclick="document.getElementById('myForm').reset();"
title="Reset form"/>
I am creating a form such that when the user click the "submit" button, it prevents the default action, serializes a subset of the fields, and then proceeds to submit all of the information via the POST array (PHP).
I am encountering a problem where the form is basically not submitting when I use the .submit() method. When I disable my javascript, the form submits fine (just with the wrong information, as the array is not serialized). But as soon as I re-enable my js, clicking the submit button does nothing except show my test console.log(var) in console. Here is some of my code, hopefully you can see what I am doing wrong. All of the online documentation says to use .submit(), but it doesn't seem to work, no matter what I try.
HTML:
<form id="entryForm" action="add_entry.php" method="post">
<div class="leftDiv">
<input type="text" class="inputFormTitle" name="entryName" placeholder="Name your entry..." />
<span class="regText">
<b>Entry Properties</b>
Specify entry properties, permissions, etc.</span>
<table class="formTable">
<tr>
<th>Parameter</th>
<th>Value</th>
<tr>
<td>Group</td>
<td><select name="group"><option></option><option>Graham Test</option></select>
</tr>
<tr>
<td>Project</td>
<td><select name="project"><option></option><option>Project 1</option><option>Project 2</option></select>
</tr>
<tr>
<td>Protocol</td>
<td>
<select id="protocolloader" name="protocol">
<option></option>
<option>PCR & Gel</option>
<option>Item Storage</option>
<tr>
<td>Permissions</td>
<td><input type="radio" name="permission" value="0">Only I can access this entry</input>
<input type="radio" name="permission" value="1">Only group members can access this entry</input>
<input type="radio" name="permission" value="2">Everyone can access this entry</input>
</select>
</tr>
</table>
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
<br/>
</div>
<div class="rightDiv">
<input type="text" class="inputFormTitle" id="ppt" placeholder="Please select a protocol" disabled/>
<div class="formHolder" id="protocolForm">
</div>
</div>
<input type="hidden" id="serialInput" name="protocolValues" value="nuttin" />
</form>
And the accompanying javascript:
var entrySubmit = $('#submitEntry');
entrySubmit.on('click', initEntrySubmission);
function initEntrySubmission(e) {
e.preventDefault();
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
$('#entryForm').submit();
}
PHP Form (which I don't think is the issue but figured I would include it anyways)
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['serialInput'];
$filearray = $_POST['fileArray'];
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, filearray, group, project, permissionflag)
VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$filearray', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}
?>
I wouldn't normally include so much HTML but I thought maybe I messed something up in there that may be the issue, and I just don't realize it. I tried to take out most of the break and header tags to clean up the code a bit.
Thanks for any help!
Regards.
The documentation of .submit() states, that
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures.
You have an input that has the name submit.
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" />
I tried it with and without that name. It works without!
I found the following to work:
<script>
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
alert(serializedProtocol);
$('#serialInput').val(serializedProtocol);
return true;
}
</script>
<form id="entryForm" action="" method="post" onSubmit="return initEntrySubmission();">
...
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" value="Submit Entry"/>
</form>
The main things to do are to add an onSubmit to your form tag. The function must return either true or false. Return true will submit the form.
Also, you do need to clean up your HTML, there are select statements in there, without closing tags and your submit button
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
has no ending >, it also has 2 type attributes type="button" and type="submit"(its both a button and a submit?) and has a name=submit, which is also unnecessary .
You don't have to preventDefault(), the Code will still be run before the Form is submitted.
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
}
You can try something like below
In HTML just add
<form id="entryForm" action="add_entry.php" method="post" onsubmit="return false;">
And in JS function
function initEntrySubmission(e) {
var serializedProtocol = $("#protocolForm :input").serialize();
$('#serialInput').val(serializedProtocol);
$('#entryForm').removeAttr('onsubmit');
$('#entryForm').submit();
}
Just change:
$('#entryForm').submit();
To:
$('#entryForm')[0].submit();
Also rename your submit element as #Matmarbon has so eloquently explained.
Explanation:
$('#entryForm').submit(); simply triggers the submit event and takes you back to square one.
$('#entryForm')[0].submit(); submits the form ... more like the default action, without triggering the submit event.