How to collect data from several input boxes? - javascript

I am creating a Polymer application in which search button has several inputs from input boxes. And from that collection of that input boxes search button should perform search operation considering all inputs.
following is the image for scenario -
{ iron-form } is one of the option for that but I want something new and with ease.
Please help me.

I don't have your HTML, so I'm just going to be using elements which I think you will have within your document.
Test this out:
Pure JavaScript:
var form = document.getElementsByTagName("form")[0];
form.onsubmit = function(){ // on form submit
var input = document.querySelectorAll("input");
for(var i = 0; i < input.length; i++){ // loop through each input on the page
alert(input[i].value); // will alert the value of the input
}
return false; // stop form from posting
}
jQuery:
$("form").submit(function(){ // on form submit
$("input").each(function(){ // foreach input
var value = $(this).val(); // grab its value
alert(value); // output its value
});
return false; // prevent form from posting
});
So when the form submits, it will iterate through each input, and output each value through an alert.
Hope this helps! :-)

Since you tagged this with the Polymer tag there is also a Polymer iron-form specific way to handle this. #Caelan is correct but this will not work with Polymer elements (or custom elements). Examples of these elements are paper-input andpaper-checkbox. See Paper Elements for a list of all customized inputs.
<iron-form></iron-form comes with a property method serialize and validate which you can use to collect all inputs (including custom elements) in one function call.
See iron-form.serialize documentation
var form = document.querySelector('iron-form')
form.onsubmit = function(event) {
event.preventDefault();
var data = form.serialize()
// Do something with data
// return false; // could use instead of event.preventDefault()
}
See preventDefault vs return false thread on stack overflow both will work in your case since you do not care about bubbling events.

Related

How to retain a value of dropdown using JS?

I have a three dropdown with 1 submit button. Now, I'm trying to retain the value of each dropdown after the user clicked the input submit. But the Jquery I have is not working. I use PHP to displayed the output of the dropdown when the user clicked it.
Note: The page is refresh when the user clicked the input submit.
How to fix this? See in plunker
JS:
$(document).ready(function(){
$('#dropdown').change(function(){
var option = $(this).find('option:selected').val();
$('#dropdown').val(option);
});
});
Use local storage with all option;
$("#dropdown").change(function(){
var html=$("#dropdown").html();
localStorage.setItem("myapp-selectval",html);
localStorage.setItem("myapp-selectvalselected",$("#dropdown").val()); //to retain selected value
})
Now on document load;
window.onload=function()
{
if(localStorage.getItem("myapp-selectval")!="" && localStorage.getItem("myapp-selectval")!=undefined)
{
$("#dropdown").html(localStorage.getItem("myapp-selectval"));
$("#dropdown").val(localStorage.getItem("myapp-selectvalselected")); //to get previously selected value
}
}
Once again as I said in comment it's not a good solution.
You can get the values easily by making use of the model attribute present in the select element.
First add a onclick function like so
<input type="submit" name="submit" value="Submit" onclick="getValues()"/>
Then get the value on submit of the button(Entire code) Plunkr
I had a look at your code, the way your selectbox rendering is setup we have to explicitly call the updateSelect() function for the options to work well. This function makes your selectbox "dynamic".
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
if(first !== null && second !== null && third !== null) {
setValues(); //this should come after getting the values above
}
function getValues() {
var first = document.getElementsByTagName("SELECT")[0].getAttribute("model");
var second = document.getElementsByTagName("SELECT")[1].getAttribute("model");
var third = document.getElementsByTagName("SELECT")[2].getAttribute("model");
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
}
//on load when this function is called globally, the values from the localStorage will be set to the dropdown values.
function setValues() {
//for first dropdown
document.getElementsByTagName("SELECT")[0].setAttribute("model", first);
document.getElementsByTagName("SELECT")[0].value = first;
updateSelect(document.getElementsByTagName("SELECT")[0]);
//for second dropdown
document.getElementsByTagName("SELECT")[1].setAttribute("model", second);
document.getElementsByTagName("SELECT")[1].value = second;
updateSelect(document.getElementsByTagName("SELECT")[1]);
//for third dropdown
document.getElementsByTagName("SELECT")[2].setAttribute("model", third);
document.getElementsByTagName("SELECT")[2].value = third;
updateSelect(document.getElementsByTagName("SELECT")[1]);
}
To retain the value you have no choice but to use a window.localStorage like so -
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
Then fetch the value
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
If the user is going to refresh the page, your best bet is to have the server send down the value that the user just submitted with the new page load.
If that's impossible for some reason, you can use localStorage:
$(document).ready(function(){
var prevVal = localStorage.getItem('selectValue');
prevVal && $('#dropdown').val(prevVal);
$('#dropdown').change(function(){
var option = $(this).val();
localStorage.setItem('selectValue', option);
});
});
Keep in mind that not all browsers support this API yet.
EDIT: If you don't need the browser to refresh, you can use Ajax:
// ...
$('#myForm').submit(function (event) {
event.preventDefault();
var option = $('#dropdown').val();
var fd = new FormData();
fd.append('dropdown', option);
$.ajax('/path/to/form/target/', {
method: 'POST',
formData: fd
});
// ...
});
//...
Although I assume OP's question asks for a JS solution, I do want to bring something else to the table because I was also searching to solve the same problem. However, I ended up solving it in a manner that I considered to be satisfying.
In my case I'm using Flask as the backend, but I believe the solution should be at least similar for other use cases.
On the HTML where the dropdown is located, I pass a variable from the backend which is originally set to be some default value of my choice. Let's call this variable default_var_set_in_backend. This will ultimately be fed to the HTML and will look like as follows:
<select name="some_name_you_want" onchange="this.form.submit()">
<option selected="selected">{{ default_var_set_in_backend }}</option>
Once a change is made in the dropdown value by the user (in my case it's a GET request), I update the variable default_var_set_in_backend to be equal to this new choice. Now, the HTML will reflect the latest choice made by the user once the page refreshes.

SELECT2 -> Add data without replacing content

I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.
Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.
Instead, each tag is replacing the content and adding itself.
I need the adding to be appended into the box without replacing what's already in there.
Here's my code:
$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
The data is being pulled through via AJAX with a span around each suggested tag.
Hope I'm clear enough.
Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.
Thanks
You should be able to do that with simple:
var test = $('#test');
$(test).select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate"},
{id:3,text:"invalid"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px"
});
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Working example: http://jsfiddle.net/z96Ca/
You are replacing the value with val(mystuff). You want to do the following:
Get the current data in the input with val()
var dataOld = $('#selectPretty').val();
Append the new data with something like*
var dataNew = dataOld.push(value);
Set the input data to new data:
$('#selectPretty').val(dataNew);
*This assumes that val() returns an array
Docs

on form validation if there's no words in the fields it returns the error but still submits the cgi file?

to be more specific, when we submit our empty form which should have information in it should submit an alert saying "please enter a value" it does this but then after selecting okay on the alert it still sends the email on submit. I want it that if there's an error they must fulfill the requirements of the form before the email on submit can be sent. the code is:
this checks to see if there's any values in the fields
function notEmpty(elem, helperMsg) {
if (elem.value.length >= 2) {
return true;
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
the start of the form:
<form method="get" onsubmit="notEmpty();" action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
the submit button:
<input type="submit" name='Submit' value="Send" onClick='notEmpty();'>
any insight to our problem is most welcome!
There are several reasons this will fail.
The first one you will encounter is, because you don't pass any arguments when you call notEmpty, the variable elem will be undefined. When you try to access a property (value) on it, an exception will be thrown and the function will stop.
Let's take this from the top.
First, we'll use a more modern method to apply the event handlers.
Provide a means to identify the form you want to deal with. An id attribute is a good general choice (but use a more meaningful name then I am):
<form id="myForm"
method="get"
action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
Next, get a reference to the form in the DOM and add an event listener to it:
document.getElementById('myForm').addEventListener('submit', notEmpty);
Note that you have to do this after the form has been added to the DOM. The easiest way to achieve this is to place your <script> after the </form> (just before </body> is a popular place). You can also use an event handler that fires when the DOM is ready or the document has loaded.
Old versions of Internet Explorer don't support addEventListerner, if you want to support them see the MDN documentation which has a compatibility routine.
Next, update the notEmpty function. Since it is an event handler, it will get one argument - an event object. It will also be called in the context of the element to which is is bound (the form).
function notEmpty(event) {
var aForm = this;
}
You want to check that some element has a value of a certain length, but there is no sign of such an element in your question. Let's work with this example:
<label> Some data <input name="example"></label>
You can reference the element through the form's elements collection:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
}
Now you can add your test:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
} else {
}
}
If you don't want the form to submit, then prevent the default action on the event:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
// At least two characters, all is well
} else {
alert("An error");
input.focus();
event.preventDefault();
}
}
Your first return true should be removed :P

Preventing form from being submitted with manual validation

I implemented some custom validation logic with JQuery and Unobtrusive validation with help of the following post:
Manually set unobtrusive validation error on a textbox
To save you time reading through that post here is the simple javascript that forces a validation message to be displayed if something fails:
On my textbox .blur():
var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
Works great.
My problem is while the failed validation message is displayed, when submit is clicked the form submits just fine.
How can I implement custom validation with code above and prevent the form from being submitted when the message is displayed ? I tired doing something like $('#SomeFormId').valid = false; but it didn't work.
Thank you.
Using $('#SomeFormId') will not work because when you do:
$('#SomeFormId').valid = false;
and then when you access it in your form submit handler again using (what I assume):
var form = $('#SomeFormId'); // or $(this)
if (form.valid) {
//
}
You're essentially creating two different objects, even though they're referring to the same DOM element. So setting valid = true in one will not update it in the second.
The code you gave is very barebones though, so I'm assuming that your validation is separate from your submit handler (since it's in blur anyway), so what you can do is utilize something like .data() or a flag (just make sure that it's in context).
// on blur
$('#SomeFormId').data('isvalid', false); // invalid
// on submit
var isvalid = $('#SomeFormId').data('isvalid');
if (!isvalid) {
// invalid form
ev.preventDefault();
}
EDIT
The jQuery Event object
When you bind a function as an event handler in jQuery, one of the things that jQuery does silently for you is it "creates" a normalized Event object for you. This will contain information about the event you can use in the handler, and also allows you to control the behavior of the event in some ways.
// setting a submit event on my form
// | whatever you put here
// V is the event object.
$('#SomeFormId').on('submit', function (ev) {
// preventing the default action
// : in a form, this prevents the submit
ev.preventDefault();
});
To check if the form is valid, you can use something like this:
var form = $("#SomeFormId");
form.submit(function(event) {
if(form.valid() == false) event.preventDefault();
}
Edited to add a bit more to it, this will take care of your submission/prevention, now you just add in your validation calls.

submit multiple forms to same page

I have three forms on a page. They each have multiple inputs including files. I would like so that when I submit the last form, the inputs for all three forms are sent to the POST data for the action location. I can jQuery if necessary.
Here's how you could combine multiple forms into one. Now, a warning: if you have more than one form with file-type inputs, you've got a problem that's really hard to solve. The browser will not let you use XMLHttpRequest (ie Ajax, in any form) to post a multi-part form POST with file inputs. You also won't be able to create a new form with the file inputs in it, because you can't set the value of file input elements with Javascript. Thus, the only way this can work is if you have multiple (3? whatever) forms, and only ONE Of them has file inputs. If that's the case, then what you can do is pull all the (non-file) inputs from the other 2 forms into the other form, and then submit that one.
function whenFormsCollide() {
// pass in one or more form elements
var forms = $.makeArray(arguments);
var hasFiles = 0, targetForm = null;
$.each(forms, function(i, f) {
if ($(f).find('input:file').length > 0) {
++hasFiles;
targetForm = f;
}
});
if (hasFiles > 1) throw "More than one form has 'file' inputs";
targetForm = targetForm || forms[0];
$.each(forms, function(i, f) {
if (f === targetForm) continue;
$(f).find('input, select, textarea')
.appendTo($(targetForm));
});
$(targetForm).submit();
}
I haven't tested that, but I've done stuff like it many times and I know that building up a <form> element works fine, even in IE6. (IE has some weird issues with form fields sometimes, but I think this part should be OK. At worst, instead of just being able to "move" the fields with that "appendTo" call you'd have to copy out the names and values and make new form fields.)
You may want to try using serialize() and append the string to your action URL.
You could submit them to hidden Iframes, that way you maintain control of the host page.
You can write one JS function that submits all three forms.
Your only option right now is a jQuery AJAX request (or a XMLHTTP one, but that's not recommended).
Try rethinking your design, I mean, why do you need 3 forms on one page... that's too `formy' for me already.
There is something else you can probably do: put the jQuery UI dialog box container div inside one form (this should work, I guess) and just have the fields within it...
I used below code to submit two forms' data in my website.
The idea is that you get the multiple forms data using serialize and combine that data and equalize that to data parameter of the $.ajax function.
.
// submits two forms simultaneously
function submit_forms(form1_id, form2_id)
{
var frm1_name = $("#" + form1_id).attr('name');
var frm2_name = $("#" + form2_id).attr('name');
if (frm1_name == frm2_name)
{
alert('The two forms can not have the same name !!');
}
else
{
var frm1_data = $("#" + form1_id).serialize();
var frm2_data = $("#" + form2_id).serialize();
if (frm1_data && frm2_data)
{
$("#div_busy").html('<strong>Processing...</strong><br /><img id="busy" src="./images/progress_bar.gif" border="0" style="display:none;" />');
$("#busy").fadeIn('slow');
$.ajax(
{
type: "POST",
url: "process_sticker_request.php",
data: frm1_data + "&" + frm2_data,
cache: false,
error: function()
{
$("#busy").hide('slow');
$("#div_busy").css({'color':'#ff0000', 'font-weight':'bold'});
$("#div_busy").html('Request Error!!');
},
success: function(response)
{
$("#div_busy").hide('slow');
$("#hdnFormsData").html(response);
// open popup now with retrieved data
window.open('', 'popup2', 'toolbars = 1, resizable=1, scrollbars=1, menubar=1');
document.getElementById("prt").action = 'win_sticker.php';
document.getElementById("prt").target = 'popup2';
document.getElementById("prt").submit();
// reset the action of the form
document.getElementById("prt").action = 'list_preview.php';
}
});
}
else
{
alert('Could not submit the forms !!');
}
}
}
Can you explain the sense of separating information in different forms and combine the information later with JS? And when Java Script is disabled your Formulas didn't work?
Put all together in one form. If you want to evaluate only the special data Fields of your Form, check on the server side which submit button was pressed.
When you have a problem an you need JS to fix a normal communication problem, then you have a conceptional problem. JS can help you to customize and give a better UI - but this problem is useless.

Categories

Resources