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.
Related
I am trying to alter an existing 3rd party html form on my website, using JS.
I have seen several posts about this, but can't quite find an answer that fits my situation.
The form in question has a Checkbox field on it, and I want to hide this and replace it with a Radio Button. However... then I also have to sync them up so that whatever the visitor does on the form to the checkbox, feeds back to the hidden input field, so that when the form is submitted, it has a value in the original field when the form is posted.
So the new Radio Button field, should have a Yes/No choice, and Yes would set the original Checkbox value to TRUE, with No setting it to FALSE.
To clarity... I don't have access to the backend software rendering the form, so only have option to alter it with JS after.
I'm not sure if I understand the question correctly but here is an example how to hide a checkbox in a form, insert there radio buttons and change the checkbox value before the form is submitted.
const form = document.getElementById('form');
const log = document.getElementById('log');
const checkbox = form.querySelector('input[type="checkbox"]');
const checkboxContainer = checkbox.closest('label');
const template = '<label><input type="radio" name="replaced" value="replaced">Yes</label> <label><input type="radio" name="replaced" value="" checked>No</label>';
form.insertAdjacentHTML('afterbegin', template);
checkboxContainer.style.display = 'none';
form.addEventListener('submit', (event) => {
checkbox.checked = form.querySelector('input[name="replaced"]:checked').value !== "";
log.textContent = checkbox.checked; // Show checkbox value
event.preventDefault(); // prevent form submitting
});
<form id="form">
<label>Hidden checkbox: <input type="checkbox" name="checkbox"></label>
<br>
<button type="submit">Submit form</button>
</form>
<p id="log"></p>
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">
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.
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'));
});
});
My first question is this although I doubt if it is possible. However, if it is, it will make my life much easier.
Can you have a radio button group with 2 forms? What I mean is that the same radio button group is found in both form1 and form2.
The reason why I need this is to that if I click on the first 2 radio buttons, the form action will be to one page, while if I click on the last 2 radio buttons, the action will be to another page.
If this is not possible, I would use one form and will have to change the form action depending on which radio button I select. I will give a class to the first two radio buttons and another class to the other 2 radio buttons.
If anyone can let me know which method is better and how to implement it in jQuery, that would be great.
Many thanks in advance
You cannot have a single group of form elements be part of two separate forms. It's just not possible to construct a valid document like that.
Javascript that dynamically updates the URL in the "action" property of the parent <form> should not be too hard to do. As you suggested, the "class" attribute of the radio button elements can be used to guide the code, making it pretty flexible if you need to add one or more buttons later on.
Since you included the jQuery tag:
$(function() {
var actionMap = {
key1: 'http://yoursite.com/some/action/1',
key2: 'http://yoursite.com/some/action/2',
/* ... */
};
$('input:radio').click(function() {
var $rb = $(this);
for (var key in actionMap) {
if ($rb.hasClass(key))
$rb.closest('form').attr('action', actionMap[key]);
}
});
});
or something. You could also use an HTML5-style "data-" attribute to store the URLs directly on the radio button elements, or a key fragment of the URL. (Also might want to handle the "change" event the same way, etc.)
The one form, alternate action pages seems to be the way to go. If you're going to use classes for the radio buttons then something like this would work.
Live example
JavaScript
// override the action page based on which radio button is checked
$('#someForm').submit( function(e) {
if($('.useDefault:checked').length == 1) this.action = 'http://www.google.com';
else this.action = 'http://wikipedia.org';
});
HTML
<form id="someForm" action="#">
<input name="rad" type="radio" value="default0" class="useDefault" /><label>default0</label>
<br />
<input name="rad" type="radio" value="default1" class="useDefault" /><label>default1</label>
<br />
<input name="rad" type="radio" value="alternate0" class="useAlternate" /><label>useAlternate0</label>
<br />
<input name="rad" type="radio" value="alternate1" class="useAlternate" /><label>useAlternate1</label>
<br />
<input type="submit" value="submit"/>
</form>
I have implemented the right solution with some help from Pointy. Here is my code:
$(function() {
$('input:radio').click(function() {
var $rb = $(this);
if ($rb.hasClass('class1')){
$("#myForm").attr("action", "link1.php");
}else if($rb.hasClass('class2')){
$rb.closest('form').attr("action", "link2.php");
}
});
$('#btnProceed').click(function(){
$('#myForm').submit();
});
});