Sending a html form with hidden elements - javascript

Today I came across a weird behaviour. I have made an html form using Bootstrap for users to subscribe. You can subscribe multiple users at once, but to see the second and the third user's input fields, you have to toggle a select button first (https://prnt.sc/t96lxt). The issue is that I can not send the form for only 1 or 2 users, because some fields of the hidden parts are set to be required.
So, my question is, how can a send a form with hidden parts that contain required fields?
My form is to be found at http://debosvrienden.alfapre.be/nl/inschrijving

Maybe you can try something like this using javascript
const checkBox = document.querySelector("YOUR_CHECKBOX");
checkBox.addEventListener("change", (e) => {
if (e.target.checked) {
document.querySelector(".hidden-input-field-1").setAttribute("required", true);
document.querySelector(".hidden-input-field-2").setAttribute("required", true);
} else {
document.querySelector(".hidden-input-field-1").setAttribute("required", false);
document.querySelector(".hidden-input-field-2").setAttribute("required", false);
}
});
Obviously, you would have to use your own selectors.
Here, you are just getting a reference to your checkbox, and once it changes, you are changing the required attribute of the inputs.

Related

EXT JS How to check field on form opening?

I have order form which contains combobox field. When user select specific value, system enables new set of fields in form.
This part of code looks like:
if (action.result.data.field == "1") {
Order.query('fieldset[itemId="set1"]')[0].enable();
Order.query('fieldset[itemId="set2"]')[0].show();
}
But if user open editing form with already selected specific value, system doesn't show this set of fields. I need system to check specific value on opening the edit form. What class I should use?
Have a look at this ExtJS example. May be this can guide you. In your case, may be you have to listen to form.Panel render event and set the form fields based on the values in the record you got from server/present locally. Something like below.
onSelectionChange: function(model, records) {
var rec = records[0];
if (rec) {
this.getForm().loadRecord(rec);
}
}
load form based on record click

Configuration form with a custom control in leaflet

I'm trying to create a custom control using leaflet; here you can see the jsfiddle: https://jsfiddle.net/1tca13f3/
When the user clicks on the submit button, i need to read the value from the dropdown and the one from the text field.
This...
L.DomEvent.on(this._container, 'click', this._doSomething, this);
...as predictable, doesn't work.. and I can't read the values from the input fields. How can I do this?
The main issue you are having is that you are just alerting the string 'clicked' in your _doSomething() function. You need to look up all the values and then you can do what ever you want with those values. Here is some quick code that will at least get you going in the right direction.
_doSomething: function(event){
if(event.target.className === 'leaflet-control-opt-submit') {
var select = document.querySelector('.leaflet-control-opt-dropdown');
var input = document.querySelector('.leaflet-control-opt-input');
console.log(select.value, input.value)
}
}
it first checks to make sure the event.target is the submit button if it is it looks up the values from the inputs and for now we just console.log() them you can do whatever you want from then on with the values.

Hide the input field div class using javascript

I have a payment form,in which when I click on the internet banking ,all the input field be disabled and instead show some images. this is the fiddle upto which i have done http://jsfiddle.net/f8Fd3/4/ No where I cant hide the input text field using their class id.
this is the js
function cc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("visa");
}
function dc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("mastercard");
}
function ib()
{
}
please check the fiddle to get a clear picture
It is because, by default, when 'button' tag inside a 'form' is clicked, 'form' will be submitted.
It's not redirecting for the other two because there's a HTML5 form validation that prevents the form from being submitted. (that's why you will see an error message when you click Visa/Mastercard)
if you insist on binding events in the dom...you can pass an event object to the handler:
<button onclick="javascript:ib(event)" class="btn btn-1 btn-1c">Internet Banking</button>
and in your function:
function ib(event) {
event.preventDefault();
}
you may wanna do the same to the other two handlers as well.
so the default submit action will be prevented.
and to disable all the text fields:
$('#cards input[type=text]').prop('disabled', true);
to hide them:
$('#cards input[type=text]').hide();
EDIT
by the way. you don't have to use selectors like $('#cards.credit-card'), 'id' should be unique in the DOM, just by using $('#cards') you will get the same element.
The syntax class="class=tokenex_data full gr-input" is incorrect.
Instead use, class="tokenex_data full gr-input"
Then use :
`function ib()
{
$(".tokenex_data").hide();
$(".monthgr-input").hide();
}
`
You want to select all input & select elements and set their property disabled to true:
$('#cards input, #cards select').prop('disabled', true);
Fiddle

Insert input if it does not exist

I am working on an email template editor where the user will select from a list of pre-existing templates and will be able to update the template as necessary. I had problems with using the CKEditor plugin across browsers and so I have attempted to create my own. When the user selects a template it opens in a modal window. To change the images I have included input tags which are removed upon close of the modal. This works so well and so good but if the user then wants to go back into the editor the input buttons are no longer there.
I want to add in the input button in the modal window if it does not exist. I have tried checking the length of the property but I am unable to return a value other than null whether it exists or not. My code is as follows:
function template1InputButtons() {
if ($("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
If I open it the first time the length comes up as one and so nothing is added as expected. If I remove and then click the button again length shows as 0 and input is added correctly as expected. If I then remove the input and click the button again the length comes up as 1 despite the control not existing.
Any ideas?
Try this:
function template1InputButtons() {
if (!$("#imageInput1T1")) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
and also assure that you have placed it inside ready function.
Try this:
if ($("body").find("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
Problem was a similar finding of class attribute article_media on the other modal my mistake thanks for the help anyway

Delete empty values from form's params before submitting it

I have some javascript which catches changes to a form then calls the form's regular submit function. The form is a GET form (for a search) and i have lots of empty attributes come through in the params. What i'd like to do is to delete any empty attributes before submitting, to get a cleaner url: for example, if someone changes the 'subject' select to 'english' i want their search url to be
http://localhost:3000/quizzes?subject=English
rather than
http://localhost:3000/quizzes?term=&subject=English&topic=&age_group_id=&difficulty_id=&made_by=&order=&style=
as it is at the moment. This is just purely for the purpose of having a cleaner and more meaningful url to link to and for people's bookmarks etc. So, what i need is something along these lines, but this isn't right as i'm not editing the actual form but a js object made from the form's params:
quizSearchForm = jQuery("#searchForm");
formParams = quizSearchForm.serializeArray();
//remove any empty fields from the form params before submitting, for a cleaner url
//this won't work as we're not changing the form, just an object made from it.
for (i in formParams) {
if (formParams[i] === null || formParams[i] === "") {
delete formParams[i];
}
}
//submit the form
I think i'm close with this, but i'm missing the step of how to edit the actual form's attributes rather than make another object and edit that.
grateful for any advice - max
EDIT - SOLVED - thanks to the many people who posted about this. Here's what i have, which seems to work perfectly.
function submitSearchForm(){
quizSearchForm = jQuery("#searchForm");
//disable empty fields so they don't clutter up the url
quizSearchForm.find(':input[value=""]').attr('disabled', true);
quizSearchForm.submit();
}
The inputs with attribute disabled set to true won't be submitted with the form. So in one jQuery line:
$(':input[value=""]').attr('disabled', true);
$('form#searchForm').submit(function() {
$(':input', this).each(function() {
this.disabled = !($(this).val());
});
});
You can't do it that way if you call the form's submit method; that will submit the entire form, not the array you've had jQuery create for you.
What you can do is disable the form fields that are empty prior to submitting the form; disabled fields are omitted from form submission. So walk through the form's elements and for each one that's empty, disable it, and then call the submit method on the form. (If its target is another window, you'll then want to go back and re-enable the fields. If its target is the current window, it doesn't matter, the page will be replaced anyway.)
Well one thing you could do would be to disable the empty inputs before calling "serializeArray"
$('#searchForm').find('input, textarea, select').each(function(_, inp) {
if ($(inp).val() === '' || $(inp).val() === null)
inp.disabled = true;
}
});
The "serializeArray()" routine will not include those in its results. Now, you may need to go back and re-enable those if the form post is not going to result in a completely refreshed page.
Maybe some of the proposed solutions worked at the moment the question was made (March 2010) but today, August 2014, the solution of disabling empty inputs is just not working. The disabled fields are sended too in my Google Chrome. However, I tried removing the "name" attribute and it worked fine!
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).removeAttr('name');
}
});
});
Update:
Ok, probably the reason because disabling fields doesn't worked to me is not that something changed since 2010. But still not working in my Google Chrome. I don't know, maybe is just in the linux version. Anyway, I think that removing the name attr is better since, despite what policy takes the browser about disabled fields, there is no way to send the parameters if the name attr is missing. Another advantage is that usually disabling fields implies some style changes, and is not nice to see a style change in the form a second before the form is finally submited.
There is also a drawback, as Max Williams mentioned in the comments, since the remove name attr solution is not toggleable. Here is a way to avoid this problem:
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).data('name', $(this).attr('name'));
$(this).removeAttr('name');
}
});
});
function recoverNames(){
$(this).find('input[name], select[name]').each(function(){
if ($(this).data('name')){
$(this).attr('name', $(this).data('name'));
}
});
}
However, I think this is not a very common case since we are submitting the form so it is assumed that there is no need to recover the missing name attrs.
Your problem helped me figure out my situation, which is a bit different - so maybe someone else can benefit from it. Instead of directly submitting a form, I needed to prevent empty form elements from being collected into a serialized array which is then posted via AJAX.
In my case, I simply needed to loop through the form elements and disable all that were empty, and then collect the leftovers into an array like so:
// Loop through empty fields and disable them to prevent inclusion in array
$('#OptionB input, select').each(function(){
if($(this).val()==''){
$(this).attr('disabled', true);
}
});
// Collect active fields into array to submit
var updateData = $('#OptionB input, select').serializeArray();
Or serialize, clear empty key=value pairs with regex and call window.location:
$("#form").submit( function(e){
e.preventDefault();
//convert form to query string, i.e. a=1&b=&c=, then cleanup with regex
var q = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi,""),
url = this.getAttribute('action')+ (q.length > 0 ? "?"+q : "");
window.location.href = url;
});
Another approach I always recommend is to do that on server side, so you are able to:
Validate the input data correctly
Set default values
Change input values if needed
Have a clean URL or a friendly URL such as "/quizzes/english/level-1/"
Otherwise you will have to deal with text input, select, radio etc...

Categories

Resources