Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?
You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>
Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!
Hey I got this problem I cannot work out by myself. It's html form which passes data to PHP to send mail.
First, I have dropdown list:
<select id="dropdown" name="dropdown">
<option selected="true" disabled="disabled">Choose</option>
<option id="A" value="one#gmail.com">One</option>
<option id="B" value="two#gmail.com">Two</option>
</select>
This dropdown defines the value of next input:
<input type='text' name="to" id="to" value="e-mail"/>
<script>
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
}
</script>
At last, I need to define third input from the value of second.
<input type='text' name="from" id="from" value="Office manager"/>
But this last code doesn't work for me:
<script>
var name;
if (document.getElementById('to').value == "one#gmail.com" {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
</script>
How do I proceed?
JSFiddle
It does if you put it like this
http://jsfiddle.net/170x1xs9/
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
var name;
if (document.getElementById('to').value == "one#gmail.com") {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
}
Syntax Error.
if (document.getElementById('to').value == "one#gmail.com" // No ')'
If you use event in your function, you should pass it as an argument.
document.getElementById('dropdown').onchange = function (event /* <-------- HERE */) {
document.getElementById('to').value = event.target.value
}
By not declaring it, you're using window.event, which might work in some browsers, but it's bad practise.
Check out the solution at: http://jsfiddle.net/jam7m5ca/1/
You forgot to pass the parameter event.
document.getElementById('dropdown').onchange = function (event) {
document.getElementById('to').value = event.target.value;
};
I have multi-selection functionality similar to this (see link): http://jsfiddle.net/eUDRV/341/.
HTML code:
<section class="container" >
<div>
<select id="list" name="list"size="15">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div>
<br><br><br>
<input type="button" id="button_left" value="<--"/>
<input type="button" id="button_right" value="-->" />
</div>
<div>
<select id="selected_values" size="15"></select>
<input name="selected_values" type="hidden"/>
</div>
jQuery/Javascript code:
$(document).ready(function () {
$("#button_right").click(function () {
var selectedItem = $("#list option:selected");
var added = false;
$("#selected_values > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#selected_values"));
updateHiddenField();
});
$("#button_left").click(function () {
var selectedItem = $("#selected_values option:selected"), activeValues;
var added = false;
$("#list > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#list"));
updateHiddenField();
});
function updateHiddenField () {
$('input[name="selected_values"]').val(
$.map($('#selected_values option:selected').toArray(), function (e) {
return e.value;
})
);
}
});
PHP code:
if(!empty($_POST['selected_values'])) {
$_POST['selected_values'] = explode(',', $_POST['selected_values']);
foreach($_POST['selected_values'] as $x) {
$query = "INSERT INTO $table (id1, id2) VALUES ($id1Value, $x)";
db_query($query);
My goal is to iterate through all of the values that are moved into the left column and enter them into a database using PHP. I'm able to get this functionality to work, however, I'm having the exact same issue as seen referenced here: how can I get all options in a multi-options select using PHP?. I'm accessing the values using $_POST["leftValues"] but if the user clicks on one of the options, only that one will be entered into the database. Unfortunately, the accepted solution isn't working for me.
$("form:has(#leftValues)").on('submit', function () {
$("#leftValues option").prop('selected', true);
});
Can someone please explain to me how I can get this solution to work for me or an alternative way of ensuring $_POST["leftValues"] will contain all the options instead of only the selected/highlighted? Any response is greatly appreciated.
You could add a hidden field and update that whenever the lists change.
You'd need to update your html:
<div>
<select id="leftValues" size="5" multiple></select>
<input name="leftValues" type="hidden" />
</div>
and add a function to do the updating:
function updateHiddenField () {
$('input[name="leftValues[]"]').val(
$.map($('#leftValues option:selected').toArray(), function (e) {
return e.value;
})
);
}
And call it in each of your click handlers:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
updateHiddenField();
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected"), activeValues;
$("#rightValues").append(selectedItem);
updateHiddenField();
});
Finally, you can do this in your PHP to get what you originally expected:
$_POST['leftValues'] = explode(',', $_POST['leftValues']);
Finally got it to work. I edited the submit callback, as the original solution suggested.
Added an id to my form tag:
<form id="form" method="post">
When the form is submitted, select/highlight all options in the selected_values list:
$(#form).submit(function () {
$("#selected_values > option").each(function () {
$(this).attr('selected', 'selected');
});
return true;
});
I would like to store the value of a input to JSON (on submit). If the User fill out the input again then submit I would like to add the new value to JSON keeping the previous one.
I use the following to add the input value to JSON but I'm not sure how to keep the previous value sent to JSON.
http://jsfiddle.net/ABE4T/
HTML:
<form method="post" name="myForm" id="myForm">
<input type="text" name="element" />
<input type="submit" value="Add" name="submit" />
</form>
<div id="display"></div>
Javascript:
$.fn.serializeObject = function()
{
var arrayData = this.serializeArray();
var objectData = {};
$.each(arrayData, function(){
if(objectData[this.name] != null){
if(!objectData[this.name].push){
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(this.value || '');
}
else{
objectData[this.name] = this.value || '';
}
});
return objectData;
};
$(document).ready(function(){
$("#myForm").submit(function(){
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
return false;
});
});
Use .append() function instead of .text() function.
DEMO fiddle
You can maintain an array to hold all the values like this
$(document).ready(function(){
var values = [];
$("#myForm").submit(function(){
values.push($("#myForm").serializeObject());
$('#display').text(JSON.stringify(values));
return false;
});
});
Working Fiddle
You are overwriting the value in #display.
Change this line
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
to
$('#display').text($('#display').text() + JSON.stringify($("#myForm").serializeObject()));
Fiddle
How can I get the value of an HTML form to pass to JavaScript?
Is this correct? My script takes two arguments one from textbox, one from the dropdown box.
<body>
<form name="valform" action="" method="POST">
Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type: <select name="cardtype" id="cardtypeid">
<option value="visa">Visa</option>
<option value="mastercard">MasterCard</option>
<option value="discover">Discover</option>
<option value="amex">Amex</option>
<option value="diners">Diners Club</option>
</select><br/>
<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />
</body>
HTML:
<input type="text" name="name" id="uniqueID" value="value" />
JS:
var nameValue = document.getElementById("uniqueID").value;
If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:
JavaScript
function getData(form) {
var formData = new FormData(form);
// iterate through entries...
for (var pair of formData.entries()) {
console.log(pair[0] + ": " + pair[1]);
}
// ...or output as an object
console.log(Object.fromEntries(formData));
}
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault();
getData(e.target);
});
Example: https://codepen.io/kevinfarrugia/pen/Wommgd?editors=1111
Alternatively you could use the below less recommended options:
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
I found this the most elegant solution.
function handleSubmit(e) {
e.preventDefault();
const formData = new FormData(e.target);
const formProps = Object.fromEntries(formData);
}
Here is an example from W3Schools:
function myFunction() {
var elements = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.name] = item.value;
}
document.getElementById("demo").innerHTML = JSON.stringify(obj);
}
The demo can be found here.
document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.
var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
if(form.id == "wanted_id") {
form = document.forms[i];
}
}
Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name
var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);
This is a developed example of https://stackoverflow.com/a/41262933/2464828
Consider
<form method="POST" enctype="multipart/form-data" onsubmit="return check(event)">
<input name="formula">
</form>
Let us assume we want to retrieve the input of name formula. This can be done by passing the event in the onsubmit field. We can then use FormData to retrieve the values of this exact form by referencing the SubmitEvent object.
const check = (e) => {
const form = new FormData(e.target);
const formula = form.get("formula");
console.log(formula);
return false
};
The JavaScript code above will then print the value of the input to the console.
If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods
My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:
const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;
A one liner for ES6
getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))
console.log('Output of getFormData:')
console.log(getFormData('#myTargetForm'))
<!DOCTYPE html>
<html>
<body>
<h2>Get Form Data as Javascript Object</h2>
<form id="myTargetForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Define this function in your Javascript:
getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))
Then just call with any selector e.g.:
getFormData('#myTargetForm')
Expanding on Atrur Klesun's idea... you can just access it by its name if you use getElementById to reach the form. In one line:
document.getElementById('form_id').elements['select_name'].value;
I used it like so for radio buttons and worked fine. I guess it's the same here.
This is the answer of your question.
You can pass the values of the form fields to the function by using this.<<name of the field>>.value.
And also changed input submit to button submit. Called the function from form.
<body>
<form name="valform" method="POST" onsubmit="isValidCreditCard(this.cctextbox.value, this.cardtype.value)">
Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type:
<select name="cardtype" id="cardtypeid">
...
</select>
<br/>
<button type="submit">Verify Credit Card</button>
</body>
Technically you can do it in your function by using document.getElementById("cctextboxid"). But his solution is concise and simple code.
I know this is an old post but maybe someone down the line can use this.
// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];
// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {
// access the desired input through the var we setup
let ccSelection = ccForm.ccselect.value;
console.log(ccSelection);
e.preventDefault();
}
<form name="ccform">
<select name="ccselect">
<option value="card1">Card 1</option>
<option value="card2">Card 2</option>
<option value="card3">Card 3</option>
</select>
<button type="submit">Enter</button>
</form>
Please try to change the code as below:
<form
onSubmit={e => {
e.preventDefault();
e.stopPropagation();
const elements = Array.from(e.currentTarget);
const state = elements.reduce((acc, el) => {
if (el.name) {
acc[el.name] = el.value;
}
return acc;
}, {});
console.log(state); // {test: '123'}
}}
>
<input name='test' value='123' />
</form>
Several easy-to-use form serializers with good documentation.
In order of Github stars,
jquery.serializeJSON
jquery-serialize-object
form2js
form-serialize
<form id='form'>
<input type='text' name='title'>
<input type='text' name='text'>
<input type='email' name='email'>
</form>
const element = document.getElementByID('#form')
const data = new FormData(element)
const form = Array.from(data.entries())
/*
form = [
["title", "a"]
["text", "b"]
["email", "c"]
]
*/
for (const [name, value] of form) {
console.log({ name, value })
/*
{name: "title", value: "a"}
{name: "text", value: "b"}
{name: "email", value: "c"}
*/
}
It's easy with one for-of loop you can get all field values even checkboxes values also.
In your HTML you should bind a handlSubmit() on your forms onsubmit event
<form name="contact_form"
id="contact-form"
class="form-controller"
onsubmit="handleSubmit(event)"
>
in your javascript your code should apply the following logic no matter what name your assigned to your fields.
const handleSubmit = (event)=> {
event.preventDefault();
const formData = new FormData(event.target);
formObj = {};
for (const [fieldName] of formData) {
const fieldValue = formData.getAll(fieldName);
formObj[fieldName] = fieldValue.length == 1 ? fieldValue.toString() : fieldValue
}
console.log('formObj',formObj)
}
Quick solution to serialize a form without any libraries
function serializeIt(form) {
return (
Array.apply(0, form.elements).map(x =>
(
(obj =>
(
x.type == "radio" ||
x.type == "checkbox"
) ?
x.checked ?
obj
:
null
:
obj
)(
{
[x.name]:x.value
}
)
)
).filter(x => x)
);
}
function whenSubmitted(e) {
e.preventDefault()
console.log(
JSON.stringify(
serializeIt(document.forms[0]),
4, 4, 4
)
)
}
<form onsubmit="whenSubmitted(event)">
<input type=text name=hiThere value=nothing>
<input type=radio name=okRadioHere value=nothin>
<input type=radio name=okRadioHere1 value=nothinElse>
<input type=radio name=okRadioHere2 value=nothinStill>
<input type=checkbox name=justAcheckBox value=checkin>
<input type=checkbox name=justAcheckBox1 value=checkin1>
<input type=checkbox name=justAcheckBox2 value=checkin2>
<select name=selectingSomething>
<option value="hiThere">Hi</option>
<option value="hiThere1">Hi1</option>
<option value="hiThere2">Hi2</option>
<option value="hiThere3">Hi3</option>
</select>
<input type=submit value="click me!" name=subd>
</form>
<script>
var inputs = document.getElementById("form_id_here").elements;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type === "text" || inputs[i].type === "textarea") {
console.log(inputs[i].value); // Get value of input tag which you have entered.
}
}
</script>
Some answers above didn't cater for forms with multiple fields with the same name e.g.multiple <input name="categories[]"> so I made this quickly. It expects field with the same name that you want to collect as an array to end in [] as a convention but could be updated to handle other scenarios.
function getFormValues(form) {
const formData = new FormData(form);
return Array.from(formData.entries()).reduce((prev, [inputName, val]) => {
return {
...prev,
[inputName]: inputName.endsWith('[]')
? prev[inputName]
? [...prev[inputName], val]
: [val]
: val,
};
}, {});
}
// alternative if you don't like reducers and nested ternary statements
function getFormValues(form) {
const formData = new FormData(form);
const values = {};
for (const [inputName, val] of formData.entries()) {
if (inputName.endsWith('[]')) {
values[inputName] = values[inputName] ? [...values[inputName], val] : [val];
} else {
values[inputName] = val;
}
}
return values;
}
// then attach this to form submit
function onSubmit(e) {
e.preventDefault();
const values = getFormValues(e.target);
// etc...
}
values gives something like { "single": "something", "categories[]": ["one", "two"] }
<input type="text" id="note_text" />
let value = document.getElementById("note_text").value;