In a dynamically changing fields using jquery same field gets posted twice - javascript

I'm working on a form where I have a text field which will be changed on radio button selection.
$("#id_radio1").click(function() {
$("#multi_language").hide();
$("#single_language").show();
});
$("#id_radio2").click(function() {
$("#single_language").hide();
$("#multi_language").show();
});
Say suppose id_radio1 and id_radio2 are two radio buttons and selecting each changes the form fields differently. Now I was able to do it successfully.
My problem is when I submit the form after single language button is clicked the values are stored as multi as the values of the multi language hidden fields are submitted overridding the values of first.CAn I disable the other field without interference of the same on submission.
How can I correct this?
I'm new to such problem. I want the field to be submitted only once.i.e, if single language field is selected single should be posted and not multi(as it is working now) and when multilanguage is selected multi should be posted.How can I correct this now with the following code.
Fiddle
I have other fields common for both single and multi language in the same form as well, whose values are not changed on submission
Now, in the console I see there are two posts for the same fields in the response i.e. one for single language and other multi language.

You can format your html code as below just if you want to pass the value of the checked field to some other script
<form method="post">
<input id="id_radio1" type="radio" name="name_radio1" value="single" />
<label for="id_radio1">Single Language</label>
<input id="id_radio2" type="radio" name="name_radio1" value="multi" />
<label for="id_radio2">Multi Language</label>
<input type="submit" />
</form>
and in your Jquery Code, you can do this
$("form").on("submit", function(e) {
e.preventDefault();
console.log($("input:checked").val()); //do whatever you want with the checked value
})
Fiddle

You can use the disabled attribute to prevent an element from being sent like so:
$("#id_radio1").click(function() {
$("#multi_language").attr('disabled','disabled').hide();
$("#single_language").removeAttr('disabled').show();
});
$("#id_radio2").click(function() {
$("#single_language").attr('disabled','disabled').hide();
$("#multi_language").removeAttr('disabled').show();
});
Since they are no hidden fields but just hidden by css it should prevent it from being submitted

Why not just have one text input, then in your server-side code simply check which radio button was selected and set the value of the server-side variable accordingly before committing data.
e.g. In PHP for instance:
$language = $_POST['language'];
if($_POST['name_radio1'] == 'single'){
some_function_committing_single_language_value($language);
} else {
some_function_committing_multi_language_value($language);
}
Or have one text input and set the form's onsubmit handler with a Javascript function to insert a hidden field with a name such as 'language_single' or 'language_multi' based on the radio button selection, and set that hidden input's value to the textfield's value.

Related

Change form parameter based on form selection

I have 3 different forms on a single page where the user can switch between using JS. The forms represent different information and only one can be submitted at a time where the user is then redirected to a different page based on the form they selected. The issue is that I have 2 input fields that are common to these forms so they are outside the forms. I am able to submit them alongside a form if I set the :
<input id="default" form="form1">
value.
So I figured it would be a simple thing to just add a function in each script where I hide/show the forms to also change that parameter to the form I want submitted however it doesn't seem to work.
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.form = "form2";
}
I have something like this but it doesn't change the form parameter.
You need to actually give your input an ID of default so you can target it:
<input form="form1" id="default">
use setAttribute
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.setAttribute("form", "form2");
console.log(input1.getAttribute("form"))
}
form2Search();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="default" form="form1">

Button field in form

I want to make 2 buttons in my form to select between windows and mac system. What I want is when the form is submitting i should be able to have one name field name="system" with 2 different value on what the user select. Sure i can do it with checkbox or select tag with options but for design i am questioning my self if its possible to do that? thanks in advance
<legend>With what system the data need to be compatible?</legend>
<button type="button" class="system btn" name="systeme" value="windows">Windows</button>
<button type="button" class="system btn" name="systeme" value="mac">Mac</button>
Mark the selected button by adding a class and add a hidden field to the form when submitting it.
$(".system").on("click",function(){
//if the clicked button is not already selected
if( !$(this).hasClass("selected_system") ){
//remove the "select" from other selected button
$(".selected_system").removeClass("selected_system");
//mark the current button as selected
$("this").addClass("selected_system");
}
});
now when submitting the form append a hidden input field to the form with the selected button's value
$("form").submit(function(){
var sel_button_val = $(".selected_system").val();
$(this).append('<input type="hidden" name="system" value="'+sel_button_val+'"/>')
$(this).submit();
});
It is possible to add two button with same name attribute value but, it will not work in backend as you expected.When you read the form fields in backend using name atrribute it return you array of values if you have more than one same name value in form.
You can achive this by updating the value attribute based on button selected before submiting the form.
Hope, This will solve your problem.

Iterate through all form elements irrespective of their type

I am busy with a form manager for one of our clients. The general idea is that forms will be built for the individual departments and I want to create a micro system which will handle validation etc for the form without redoing too much work. As automated as possible.
My first major task is that I want to on clicking the submit button, iterate through the entire form and based on specific credentials and validation rules validate the form before it gets sent to the server. I have seen a number of posts related to getting example all the input fields in a form, but I am looking for a solution which will iterate through the entire form and it's contents and then do validation on specifically all of the form elements (which includes select boxes, input boxes, text boxes etc).
I could do this separately, but I would preferably like the validation to be done top - bottom so if the first field is example a select and the next is an input field, it should iterate through the form from top to bottom so that I can output errors according to that.
// Sample code:
$(document).ready(function() {
$("#main_submit").click(function() {
// Select all of the form fields here and iterate through them ...
});
});
<form name='test_form' method='POST' action=''>
<div>
<label for='title'>Title</label>
<select name='title'>
<option value=''>Please select ...</option>
<option value='MR'>MR.</option>
</select>
</div>
<div>
<label for='full_name'>Full Name:</label>
<input name='full_name' type='text' />
</div>
.....
</form>
Use the jQuery :input selector:
jQuery("form :input");
Description: Selects all input, textarea, select and button elements.
http://api.jquery.com/input-selector/
Try this:
//loop through all input elements
$("form :input").each(function(){
var thevalue = $(this).val();//the value of the current input element
var thename = $(this).attr('name');//input name
var thetype = $(this).attr('type');//input type
});

Modify underlying form.reset() values

I'm using $('form-selector').get(0).reset() to reset form values to their original page load state.
After editing, the form will submit via $.ajax() and I'll have new "default" values on our server. The form element will still exist in the dom, and the user can submit again to update. I'd like the "default" (reset values) to reflect what's on our server (ignoring any other external updates). Is it possible to update the underlying values that form.reset() will change each form element to without a page refresh?
Cross-browser support would be nice, but since this is an internal app, Google Chrome only is sufficient.
HTML
<form>
<input type="text" value="foo" name="bar" />
<input type="submit" value="Submit" />
<Input type="reset" value="Reset" />
</form>
JAVASCRIPT
$(function(){
$('form').submit(function() {
// Omitting code that sends form values to the server
// TODO: update underlying form.reset()
// values to what's currently in each
// form element.
return false;
});
});
UPDATE
Ack! I failed to mention that I'm looking for something to handle all form element types.
i.e. input[type=text], input[type=radio], input[type=checkbox], select, textarea.
Would be especially awesome if it can handle HTML5 form elements as well...
i.e. input[type=date], input[type=number], input[email], input[url], input[type=range], input[type=color], etc.
Sorry for the confusion.
If you change attributes of the form elements directly, rather than using the .val() method, the new values will be reflected on a form reset. You'll need to treat text fields differently from radio buttons, checkboxes, etc.
$('input').attr('value', function() { return this.value });
$('textarea').prop('innerHTML', function() { return this.value });
$(':checked').attr('checked', 'checked');
$(':selected').attr('selected', 'selected');
$(':not(:checked)').removeAttr('checked');
$(':not(:selected)').removeAttr('selected');
Something like this:
$("#foo").prop("defaultValue", "bar");
As David Budiac mentioned in his comment, this doesn't work for select elements. Select elements have a separate property named defaultSelected.
More about the defaultValue property
I realize that these links go to Microsoft's site but they seem to work in pretty much all mainstream browsers.
Javascript does not know what the reset values are, so you'll have to define them either on page load or make hidden field(s) with the reset values. Then when you call reset, set them.
Let's say you have hidden fields for each field you have in your form, like text boxes (you can do similar ones for dropdowns and radio/select)
If you have 2 text fields (txtfield1 and txtfield2), you would also have hidden fields for them (called txtfield1-hdn and txtfield2-hdn respectively).
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($($(this).attr('id') + '-hdn').val());
});
});
of if you have default values in the text field html then you can just do this:
<input id="Text1" type="text" value="myValue" />
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($(this).attr('value'));
});
});

HTML : hiding input radios on form submit

I've got a HTML form that has two possible types ("id" or "profile")
<form action="process.php">
<input type="radio" name="type" value="id">
<input type="radio" name="type" value="profile">
<input type="text" name="value" value="input">
</form>
So essentially, my resulting URL is
/process.php?type=id&value=input
(or type=profile, depending on what the user picks)
What I want is my URLs to look something like
/process.php?id=input
or
/process.php?profile=input
I have two questions:
1) Is the following jQuery/JavaScript code "bad practice"? I really don't feel like I'm doing it correctly if I do it the following way (even though it works):
<input type="submit" onclick="formSubmit()">
<script>
function formSubmit() {
// if the first radio (id) is selected, set value name to "id", else "profile"
$("form input:text")[0].name = $("form input:radio")[0].checked ? "id" : "profile";
// disable radio buttons (i.e. do not submit)
$("form input:radio")[0].disabled = true;
$("form input:radio")[1].disabled = true;
}
</script>
2) Is there a way to do this without using htaccess rules or JavaScript?
Thanks!
As for your first question, I'd write my jQuery like this:
// store your form into a variable for reuse in the rest of the code
var form = $('form');
// bind a function to your form's submit. this way you
// don't have to add an onclick attribute to your html
// in an attempt to separate your pre-submit logic from
// the content on the page
form.submit(function() {
// text holds our text input
var text = $('input:text', form),
// radio holds all of our radio buttons
radio = $('input:radio', form),
// checked holds our radio button that is currently checked
checked = $('input:radio:checked', form);
// checking to see if checked exists (since the user can
// skip checking radio buttons)
if (checked) {
// setting the name of our text input to our checked
// radio button's value
text.prop('name', checked.val());
}
// disabling our radio buttons (not sure why because the form
// is about to submit which will take us to another page)
radio.prop('disabled', true);
});
As for your second question, you could always move this logic to the server side. It depends if you want the pre-processing logic to be done by the client, or by your server. Either way you should have logic on the server to validate the form. If your js errors out, it could send over the raw form data. Personally I'd put this logic on the server to avoid the overhead of checking to make sure it was pre-processed in the first place. You'll also be able to cut down on your js use which will save you some precious bandwidth.
You could try something like this:
<input type="radio" name="type" value="id" onclick="getElementById('textValue').setAttribute('name','id');">
<input type="radio" name="type" value="profile" onclick="getElementById('textValue').setAttribute('name','profile');">
<form action="process.php">
<input type="text" id="textValue" name="value" value="input">
<input type="submit">
</form>
Put the radio inputs outside the form, have the text input identified by an id so you can use the getElementById function (still needs to be checked if it is supported by the browser). This avoids loading jQuery if you don't need it on this page.
The result is the one expected by you.
But.. I would use server-side processing of the form.

Categories