Using prepopulated form, submit only changed fields - javascript

I have an html form that uses select and text inputs. The form comes pre-populated with default values. How can I submit only the inputs that were changed by the user from their default values? Note that this page is to be stored in an embedded system with limited space, so using a javascript library is out of the question.
Example html:
<form>
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<select name="field3">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
To be clear, inputs that the user does not change should not show up in the POST request when the form is submitted.

As per Barmar's suggestion to use an array to track which values have changed, this is the solution I have come up with and it works.
Here is the js:
var tosubmit = []
function add(name) {
if(tosubmit.indexOf(name) == -1)
tosubmit.push(name);
}
function is_changed(name) {
for(var k = 0; k < tosubmit.length; k++)
if(name == tosubmit[k])
return name && true;
return false;
}
function before_submit() {
var allInputs = document.getElementsByTagName("input");
var allSelects = document.getElementsByTagName("select");
for(var k = 0; k < allInputs.length; k++) {
var name = allInputs[k].name;
if(!is_changed(name))
allInputs[k].disabled = true;
}
for(var k = 0; k < allSelects.length; k++) {
var name = allSelects[k].name;
if(!is_changed(name))
allSelects[k].disabled = true;
}
}
html:
<form onSubmit="beforeSubmit()">
<input type="text" name="field1" value="value1" onchange="add('field1')" />
<input type="text" name="field2" value="value2" onchange="add('field2')" />
<select name="field3" onchange="add('field3')">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
This works because form elements that are disabled are not included in the POST Request. Thanks everyone for their suggestions.

If you can use HTML5, you can use the placeholder attribute, example. Keep in mind this won't work with older browsers like IE6-8.
<form>
<input type="text" placeholder="placeholder text" name="field1" value="" />
<input type="Submit" />
</form>
If you can't use that, you'll have to do a detect on form submit with javascript and check the value of the objects your submitting. The other option is to have a label of your preview text and hide it when input boxes are selected or contain a value that isn't empty.

waldol1's method works. Here I'm making a suggestion, and offering an alternate way.
Improvement:
For cleaner code, just use "add(this)" for each input element.
<input onchange="add(this)" />
Then, in the add() function, just add one more line to get the name of the element being clicked
function add(e) {
var name = e.name;
// do stuff
}
Alternate solution:
I'm not submitting a form the classic way; I'm just using input elements and doing stuff with Javascript. I don't care about disabling form elements, and don't want to rely on that as a flag. Instead I'm using a JS object to store my changed variables, then I just run through the object when I build my parameters (in my case, to submit via AJAX request).
Define a global "tosubmit" object (you could use an array if you want).
var tosubmit = new Object();
For any input element I want updateable, I call add(this) when there's a change:
<input onchange="add(this)" />
The JS function adds the changed element to my temporary storage object.
function add(e) {
// Store the element and it's value, ready for use later.
tosubmit[e.name] = e.value;
}
When I'm ready, I build parameters for my AJAX update. In my casI run the function with an ID, in my case. I run through the tosubmit object, and if the update is successful, I clear it out, ready for another use.
function sendUpdate(id) {
// Start building up my parameters to submit via AJAX to server.
var params = "id="+encodeURIComponent(id);
// Run through the tosubmit object, add any updated form elements.
for (var i in tosubmit) {
params = params + "&" + i + "=" + encodeURIComponent(tosubmit[i]);
}
// (Do other stuff, build my http request, etc)
// Eventually submit params with the http request
http.send(params);
}

Related

Getting undefined when trying to send select value to other page

I have a small JavaScript issue.
I have the following form:
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
What I'm trying to do is to get the value from the select tag and use it in page2.
For example, is option is A, the value should be ="a".
I want to use the value="a" in page2.
document.getElementById("output"): here i want to print the result in page2.
What I've tried to do in the second page:
<script>
var select = document.getElementById("activity");
var e = select.options[select.SelectedIndex].value;
document.getElementById("output").innerHTML = e;
<!-- This doesn't show anything. -->
var test = document.getElementsbyName("activity").values;
document.getElementById("output").innerHTML = test;
<!-- The output is: function values() { [native code] } -->
var test = document.getElementsByName("activity").value;
document.getElementById("opinion").innerHTML = test;
<!-- The output is: undefined -->
</script>
So basically, getting the select element by ID or by Name doesn't work.
Getting the select element ID.value doesn't work.
Getting the select element by the index doesn't work.
Any ideas? I've literally tried anything.
Am I writing the code in the wrong place?
Do I have to send this information through the server-side?
P.S.: I am writing the app in Node.js and Express and I'm using handlebars.
Kind regards,
G.
Update:
If you want to get the value to other page, you need to fetch it from url as whole new page get rendered and your old values will not exist exist.
If you are having your values in url just fetch it by this
let url = window.location
I assume, you are trying to get the value of dropdown
select has always the value attribute to it which actually is the value you select from dropdown
You just need to look for the value of select whenever you want the selected option.
Here in your case just attach a onchange listener to select, which triggers whenever the value of select get changed
var select = document.getElementById("activity");
var mySelectValue = select.value // set the default value
select.onchange = function() {
console.log(select.value)
mySelectValue = select.value // update whenever value get changed or new value chosen
}
// Do whatever you want to do with selectvalue
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
So basically, I have fetched the link and I tried to check if the activity = something.
example down below:
if(url.href.indexOf("activity=a") > -1){
activity = "a"
}
document.getElementById("opinion").innerHTML = activity;
Of course, in the page2, I can see "a" as a result which is great! :)

Getting the selected option in Javascript/Node.js

Self teaching Node.js and Javascript stuff. I have in the form in my HTML and select, drop down menu option. How do I get the index of the selected value?
So far im trying this:
var e = req.body.boolean_choice;
boolChoice = e.selectedIndex;
I have the req.body working for getting the inputted values in a text box, but it tells me selectedIndex is not a thing. So then I tried:
var e = req.body.boolean_choice
to see what that gave and it just gave undefined.
Is there a way to do this?
Here is the HTML:
<form action="http://localhost:3000" method="POST">
Form:<br>
<br>
<br>
Text Box 1: <input type="text" name="tb1" size="35" placeholder=""#10SadioMane" OR "#Mane"">
<br>
<br>
<select id="choice" name="choice">
<option value="OR">OR</option>
<option value="AND">AND</option>
</select>
<br>
<br>
<input type="submit" value="Submit">
Form submitting will pass only value property of selection.
Also use debugger in IDE that you use, to explore req.body, instead of trying to guess what's there.
Happy to help.
First of all get the Selected option DOM element
var el = document.querySelector('#choice option:selected');
ibn your case it will be
req.body.querySelector('#choice option:selected');
Now logic is to iterate to the previous siblings in the chain till you reach to the top.
var index = 0;
while( el.previousSibling ! == null){
el = el.previousSibling;
index +=1;
}
console.log(index);

How to structure the code to process multiple variables from mulitple form elements in JavaScript and remember the choices?

E.g. I have an HTML form:
<form role="search" method="get" id="searchform" action="" >
<!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<!-- DROPDOWN TO SELECT ONE CHOICE -->
<select name='country' id='country' class='postform' >
<option class="level-0" value="2">USA</option>
<option class="level-0" value="3">Canada</option>
<option class="level-0" value="4">Mexico</option>
<option class="level-0" value="5">Cuba</option>
</select>
<!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
<div id="color">
<input type="checkbox" name="" value="21" />Beachfront
<input type="checkbox" name="" value="16" />TV
<input type="checkbox" name="" value="20" />Internet
<input type="checkbox" name="" value="17" />Pets Allowed
</div>
</form>
<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>
And I want to be able to make AJAX request every time the user:
1) write something in the search input box and click search button
OR
2) select one choice from the dropdown menu
OR
3) select one or multiple choices from the checkboxes that are checked
The problem is that I don't know how to structure my JavaScript code correctly and what is the best way to remember and manage choices that the user selected before, to take all things in account. For example, not just the search term when he write something and click search button, but also to take in count the dropdown choice (probably done one step before) and maybe the checked options from checkboxes if he has checked something before. Here is what I have so far:
jQuery(document).ready(function($){
// RESULTS SHOULD APPEAR IN #results DIV AFTER AJAX IS DONE
var $maincontent = $('#results');
// SEARCH INPUT PROCESSING
$('#searchsubmit').click(function(e){
e.preventDefault();
var searchval = $('#s').val();
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
searchval : searchval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
}
);
});
// COUNTRY DROPDOWN CHOICE PROCESSING
$('#country').on('change', function() {
var countryval = this.value;
$maincontent.animate({ opacity : '0.1' })
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
countryval : countryval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
$maincontent.animate({ opacity : '1' })
}
);
return false;
});
// CHECKBOXES PROCESSING
$('#color input[type=checkbox]').click(function() {
if (this.checked) {
// code if checked
}
else {
// nothing
}
});
});
As you can see, it's very bad. Because one "function" checks only click, one change and I don't know how to grab values from the checkboxes and make an array and send it via ajax ;(.
Any idea how to structure the JavaScript code so it is not so separated and the checks are somehow in one part (or more logical) instead of three separated parts?
Any ideas are welcome.
Create som logic :
var _do = {
bind: function() {
var self = this;
$('#searchsubmit').on('click', function(e){
e.preventDefault();
self.ajax('searchval', $('#s').val());
});
$('#country').on('change', function() {
self.ajax('countryval', this.value);
});
return self;
},
ajax: function(key, value) {
var data = {action: 'ajax_search_action_do'};
data[key] = value;
$.post(
WPaAjax.ajaxurl, data, function( response ) {
$maincontent.empty().append( response );
}
);
}
}
jQuery(document).ready(function($){
_do.bind();
});
Maybe use jquery.form.js?
http://malsup.com/jquery/form/
It's a great plugin, just structure the form like it was a normal redirection form, add array in name of checkboxes
<input type="checkbox" name="types[]" value="21" />Beachfront
Add target URL to the form, and then...
When u want to submit the form just do
$('searchform').ajaxSubmit({
success: function() {
// callback
}
)
Trigger this on checkboxes change, dropdown change etc. To make the code clean, use one selector
$('#country, #s, #color input').on('change', sendAjaxForm);

How to check a Particular Radio Box in a "Group" using JavaScript

I have a radio box group and I need to select a given radio box using javascript as in the following case, I have to check option with value D3
<input type="radio" name="day" id="day" value="D1" />D1
<input type="radio" name="day" id="day" value="D2" />D2
<input type="radio" name="day" id="day" value="D3" />D3
<input type="radio" name="day" id="day" value="D4" />D4
How can the third option for example be checked?
Be sure putting this radio group in a form and change the theNameOfTheForm to your form's name.
<form name="theNameOfTheForm">
..
..
..
</form>
The java-script function:
<script type="text/javascript">
function select_radio_value(theValue)
{
for (var i=0; i < document.theNameOfTheForm.day.length; i++)
{
if (document.theNameOfTheForm.day[i].value == theValue)
{
document.theNameOfTheForm.day[i].checked = true;
}
}
}
</script>
Now you can use it as a js function on any event. for instance:
<input type='button' name='c3' value='Click Here to check the D3 radio' onClick="javascript:select_radio_value('D3')">
Normally, you'd use document.getElementById('day').val or jQuery('#day').val(). That is, if they have different ids. If they share the id, I'm not sure you can with document.getElementById since it assumes that the ids are different, but perhaps
jQuery('#day')[3].val()
could work, because jQuery actually returns an array of elements that match the criteia
Remove the unique ID from each of the checkboxes. You should only have ONE unique ID on a page.
In JavaScript, access the third checkbox in this group with the following and set it to checked:
var inputs = document.getElementsByTagName('input');
inputs[2].setAttribute('checked', 'checked');
OR, you can simply add checked=checked to your HTML.
function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementById('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}
In many cases you need to have Id names different for your elements.
You can then give them same name and use getElementsByTagName instead.
The the code will look like...
function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementsByTagName('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}
I would give the radio buttons different ids and then do the following :
d3.select("input#thirdRadio").property("checked", "true");

get all values of dropdownlist to see if loaded value has changed using javascript

This is to check if a user is opening another div (form; there are four for the page) without having saved the entry or update for the current form.
I need to compare the current value of dropdowns to all the possible choices of the dropdowns. If there is a difference the user is shown an alert notifying of having not saved the data. There is a not a set number of dropdowns. My script has been able to correctly count the number of dropdowns for each form.
Thanks,
James
You can do this by updating a variable on change of your select and then checking that value whenever you do what it is you do to move on to the next form. Here's the code I have mocked up:
HTML -
<select id="one">
<option value=""></option>
<option>1</option>
<option>2</option>
</select>
<br />
<select id="two">
<option value=""></option>
<option>3</option>
<option>4</option>
</select>
<br />
<select id="three">
<option value=""></option>
<option>5</option>
<option>6</option>
</select>
<br />
<!-- The submit buttons -->
<input type="submit" id="submit" value="Save" />
<br />
<!-- The link that moves on to the next form -->
Move on
Javascript -
// the variable
var selectChanged = false;
// set up everything on load
window.onload = function() {
// bind handlers to submit button, link, an dselects
document.getElementById("submit").onclick = submitForm;
document.getElementById("moveOn").onclick = moveOn;
var selects = document.getElementsByTagName("select");
var numSelects = selects.length;
for (var i = 0; i < numSelects; i++) {
selects[i].onchange = noteChanged;
}
}
function submitForm() {
// set the changed variable to false
selectChanged = false;
}
function moveOn() {
// if the select has changed without save, alert the user and prevent
// link actions
if (selectChanged) {
alert("You have changed a form value but not saved it");
return false;
}
}
// update the value for each time a select changes
function noteChanged() {
selectChanged = true;
}
Here it is in action
What I would do is:
Whenever a change happens (you can attach to the onChange event for any form elements you need to track), set a flag somewhere that indicates the form (or whatever) is "dirty". (a good place to put this is in data- attributes)
When the form gets saved, the saving process can re-set the dirty flag to clean
Whatever method is used to switch forms can check first to see if the dirty flag is set, and if so, display an error (or warning) and prevent the next form from being shown.
With these 3 pieces in place, you should be able to easily detect a dirty (unsaved) form and take the appropriate actions.

Categories

Resources